简体   繁体   English

在pyrender中将场景渲染为图像后如何获取对象的像素坐标?

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

I am trying to obtain the pixel coordinates (x, y) of the object that is rendered using pyrender.我正在尝试获取使用 pyrender 渲染的对象的像素坐标 (x, y)。 The aim is to get the bounding box coordinates of that object.目的是获取该对象的边界框坐标。 I use OffScreenRenderer to render the scene.我使用 OffScreenRenderer 来渲染场景。

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可用信息:camera_to_world 姿势矩阵

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.谢谢你。

You are looking for bpy_extras.object_utils.world_to_camera_view .您正在寻找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在 Blender Stack Exchange 上看到这个答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM