I'm trying to render an RGB image and corresponding depth image for a simple scene consisting of a single object. I've been able to render the RGB image without any problem but I'm unable to generate the depth image. I've tried it a couple of ways with no success. Any help will be hugely appreciated. First method: Reading the Z-buffer:
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(type="CompositorNodeRLayers")
composite = tree.nodes.new(type="CompositorNodeComposite")
composite.location = 200,0
links.new(rl.outputs['Z'], composite.inputs['Image'])
scene = bpy.context.scene
scene.render.filepath='depth.png'
bpy.ops.render.render(write_still=True)
This gives an all white output image. I tried some variations based on comments online, like linking to composite.inputs['Z'], saving into a .exr file instead of .png. But in all cases, it saves a .png file which is either all black or all white. I have seen examples where I can link to a CompositeNodeViewer and then read bpy.data.images['Viewer Node'].pixels, but it is too slow/clunky for my use. Second method: Using a mist pass:
scene.render.layers['RenderLayer'].use_pass_mist = True
scene.world.mist_settings.start = 0
scene.world.mist_settings.depth = 10
links.new(rl.outputs['Mist'], composite.inputs['Image'])
scene.render.filepath = 'depth.png'
bpy.ops.render.render(write_still=True)
This creates a segmentation mask of the image, 0 in background and 1 in object pixels. I want a depth image, with gradation between [0, 255] for the foreground pixels also. What am I doing wrong ? Thanks for any help in advance !