How to get Color and Z-Depth from Viewer Node? I read some article how to get the z-Depth values from the Viewer Node. So i created a scene with a camera and a Plane with distance z=2. Then i tried to get RGB values and also z-Depth with compositing Nodes.

Code from my Plugin:

bpy.context.scene.render.use_compositing = True
bpy.context.scene.use_nodes = True
tree = bpy.context.scene.node_tree
links = tree.links
for n in tree.nodes:
    tree.nodes.remove(n)
rl = tree.nodes.new('CompositorNodeRLayers')      
viewer = tree.nodes.new('CompositorNodeViewer')   
viewer.use_alpha = False
links.new(rl.outputs[0], viewer.inputs[0])  # link Image output to Viewer input

# render and get result
bpy.ops.render.render()
links.new(rl.outputs[0], viewer.inputs[0])  # link Image output to Viewer input
pixels = bpy.data.images['Viewer Node'].pixels
print(pixels[0])
arr = np.array(pixels[:])
arr = np.delete(arr, np.arange(3, arr.size, 4)) # delete alpha
arr = arr.reshape((height,width,3))

# save z-depth 
links.new(rl.outputs[2], viewer.inputs[0])  # link Image output to Viewer input
bpy.ops.image.reload()
pixelsZ = bpy.data.images['Viewer Node'].pixels
print(pixelsZ[0])
arrZ = np.array(pixels[:])[::4] # every 4th px


Both pixel arrays are the same. I tried this also manually and there it works perfectly. I thought about refreshing the image (in the image editor it refreshs the Viewer Node automatically when i change the node links), but even this didn't work.

Have anybody an idea how to fix this or what i'm doing wrong?

edit: I think i got the problem: I have to render again, after changing the nodes. is there an option to change and read the information without rerendering?
I am trying to do something similar. I (think) I made it by connecting the Render Image to Viewer Image and by connecting Render Z to Viewer Alpha. I used your code as a starting point.

import bpy
import numpy as np

bpy.context.scene.render.use_compositing = True
bpy.context.scene.use_nodes = True
tree = bpy.context.scene.node_tree
links = tree.links

for n in tree.nodes:
    tree.nodes.remove(n)
rl = tree.nodes.new('CompositorNodeRLayers')      

vl = tree.nodes.new('CompositorNodeViewer')   
vl.use_alpha = True
links.new(rl.outputs[0], vl.inputs[0])  # link Renger Image to Viewer Image
links.new(rl.outputs[2], vl.inputs[1])  # link Render Z to Viewer Alpha

#render
bpy.context.scene.render.resolution_percentage = 100 #make sure scene height and width are ok (edit)
bpy.ops.render.render()

#get the pixels and put them into a numpy array
pixels = np.array(bpy.data.images['Viewer Node'].pixels)
print(len(pixels))

width = bpy.context.scene.render.resolution_x 
height = bpy.context.scene.render.resolution_y

#reshaping into image array 4 channel (rgbz)
image = pixels.reshape(height,width,4)

#depth analysis...
z = image[:,:,3]
zf = z[z&lt;1000] #
print(np.min(zf),np.max(zf))


I wouldn't use Viewer Depth channel since Image pixels (RGBA) are floats whereas depth are ints.