How to read Z Pass value from Render Layer using Python

When i show the Render Result in the UV Image Editor, hold the mouse key and move the cross, Blender shows X: Y: Z: below the image.
I want to export the these X,Y,Z-Values of the Render Pass to a file. How can i access this data using Python?

I haven’t found a way to access those values directly from the “Render Result” image, but there’s a workaround:

Enable composite nodes in node editor and hook the z output of the render layer node to a viewer node. Click on the viewer node to make it active. Make sure the z pass is on in render properties, layers tab (it is on by default). Render the image.

Now the z depth info is encoded in the active image in the image editor and you can read out the pixel values.

I hope this is correct, I’m not good with indices and double loops, but should get you an idea.

Edit: warning, pixel access is slow, best start with a small image for testing.

import bpy
im =["Viewer Node"]

im_width = im.size[0]
im_height = im.size[1]

rgba_offset = 0 # 0 = red, 1 = green, 2 = blue and 3 = alpha.
                # in this image: red = green = blue = z depth

for y in range(im_height):
    for x in range(im_width):
        z = im.pixels[(y * im_width + x) * 4 + rgba_offset]
        # now write x, y, and z to a file

Here’s info from the API.