How to get pixel coordinates of object after rendering the scene as image in pyrender?

2k views Asked by At

I am trying to obtain the pixel coordinates (x, y) of the object that is rendered using pyrender. The aim is to get the bounding box coordinates of that object. I use OffScreenRenderer to render the scene.

r = pyrender.OffscreenRenderer(viewport_width=640,
                            viewport_height=480,
                            point_size=1.0)
color, depth = r.render(scene)

Available info: camera_to_world pose matrix

First I tried to plot the centroid of the object as below:

x, y = trimesh_mesh.centroid[:2]
height, width = image.shape[:2]
x = int(x * width)
y = int(y * height)
plt.imshow(image)
plt.scatter(x, y)
plt.show()

I get the following: image plot

Similary the bounding box plot for same object is here

Does anyone know how I can get the exact centroid and box coordinates of the rendered object? Thank you.

1

There are 1 answers

1
Finni On

You are looking for bpy_extras.object_utils.world_to_camera_view.

Use it like so:

import bpy
import bpy_extras

scene = bpy.context.scene
obj = bpy.context.object   # object you want the coordinates of
vertices = obj.data.vertices   # you will get the coordinates of its vertices

for v in vertices:
    # local to global coordinates
    co = v.co @ obj.matrix_world
    # calculate 2d image coordinates
    co_2d = bpy_extras.object_utils.world_to_camera_view(scene, camera, co)
    render_scale = scene.render.resolution_percentage / 100
    render_size = (
        int(scene.render.resolution_x * render_scale),
        int(scene.render.resolution_y * render_scale),
    )

    # this is the result
    pixel_coords = (co_2d.x * render_size[0],
                    co_2d.y * render_size[1])

    print("Pixel Coords:", (
          round(pixel_coords[0]),
          round(pixel_coords[1]),
    ))

See this answer on the Blender Stack Exchange