How to get depth data using python api I know how to do this manually but I want to know how to do this with a python script. I was trying to use nodes to connect the z buffer to the output.
However, when I save this, the outputs are all 0s and 1s.

#switch on nodes
scene.use_nodes = True
tree = scene.node_tree
links = tree.links

# clear default nodes
for n in tree.nodes:
    tree.nodes.remove(n)

# create input render layer node
rl = tree.nodes.new('CompositorNodeRLayers')    

# create defocus layer
d = tree.nodes.new('CompositorNodeDefocus')
d.use_zbuffer = True

# create output node
v = tree.nodes.new('CompositorNodeViewer')   
v.use_alpha = False

# Links
links.new(rl.outputs[0], d.inputs[0])  # link Image output to defocus Image
links.new(rl.outputs[2], d.inputs[1]) # link Z-Buffer output to defocus Z
links.new(d.outputs[0], v.inputs[0])

# render
bpy.ops.render.render()

# get viewer pixels
pixels = bpy.data.images['Viewer Node'].pixels
print(len(pixels)) # size is always width * height * 4 (rgba)

# copy buffer to numpy array for faster manipulation
arr = np.array(pixels[:])
fname = "depth.npz"
with open(fname, "wb") as f:
    np.savez(f, arr)
Ok. I finally got the depth data by directly connecting the z data to the viewer node:

# create input render layer node
rl = tree.nodes.new('CompositorNodeRLayers')    

# create output node
v = tree.nodes.new('CompositorNodeViewer')   
v.use_alpha = False

# Links
links.new(rl.outputs['Z'], v.inputs[0]) # link Z to output

# render
bpy.ops.render.render()


And then I output the information into an npz file to be used within python

# get viewer pixels
pixels = bpy.data.images['Viewer Node'].pixels
print(len(pixels)) # size is always width * height * 4 (rgba)

# copy buffer to numpy array for faster manipulation
arr = np.array(pixels[:])
fname2 = "depth.npz" 
with open(fname2, "wb") as f:
    np.savez(f, arr)