# Convert Cycles depth/z to distance to image plane

I want to simulate a depth sensor with Blender Cycles, but the z-pass returns the length of the sight ray and not the distance to the image plane. Here is a formula to convert the depth map, but I am not sure how to derive the terms from Blender, or a Python script using the Blender API.

I guess the focal length (f) can be derived with

bpy.context.object.data.lens_unit = 'MILLIMETERS'
f = 1000 * bpy.context.object.data.lens


The y-coord of the principal point by using the resolution

cy = bpy.context.scene.render.resolution_y / 2


The y-coord of a pixel (ys) and the length of the sight ray (zs) are also clear, but how can I derive the density (d)?

I got it with a slightly different formula. Given the field of view (fov) as

bpy.context.object.data.lens_unit = 'FOV'
fov = bpy.context.object.data.angle


and the intrinsic components of the camera as

f = (im_width / 2) / tan(fov / 2)
px = im_width / 2
py = im_height / 2


I can transform the depth as follows

zc[v,u] = zs[v,u] * f / sqrt(f**2 + (px - u - 0.5)**2 + (py - v - 0.5)**2)