2
$\begingroup$

I know there're many questions similar to mine, but they are a bit too old and not working with newest version of blender.

I found this two, but have no idea how to use them:

bge.types.KX_Camera.getScreenPosition

freestyle.utils.bounding_box(stroke)

And I guess it does what I need, but I can't figure out how to use it. I'm bad with python, and scripting.

I have a scene with a terrain and plants on it. I need to get 2d pixel coordinates of every plant. From top corner to bottom corner, to make a rectangle shape box of every leaf (similar to this, I guess, but maybe I'm wrong).

I have a terrain with plants: enter image description here And I want to get coordinates of every leaf object in json format, to make my software automatically detect position of a leaf object on the picture, when I load a picture and json data into it. So it would look similar to this, once finished: enter image description here Any ideas on how to make it work? At least I would like to know how to get 2d pixel coordinates of multiple objects from rendered image with python? Or is it possible to get 2d coordinates(from top corner to bottom corner) of bounding boxes of every object?

Here's what I've figured out so far, using a default cube with default position and scale:

import bpy
from bpy_extras.object_utils import world_to_camera_view

scene = bpy.context.scene

# needed to rescale 2d coordinates
render = scene.render
res_x = render.resolution_x
res_y = render.resolution_y

obj = bpy.data.objects['Cube']
cam = bpy.data.objects['Camera']

# use generator expressions () or list comprehensions []
verts = (vert.co for vert in obj.data.vertices)
coords_2d = [world_to_camera_view(scene, cam, coord) for coord in verts]

# 2d data printout:
rnd = lambda i: round(i)

print('x,y')
for x, y, distance_to_lens in coords_2d:
    print("{},{}".format(rnd(res_x*x), rnd(res_y*y)))

Console output:

x,y
1308,772
1281,345
946,631
947,166
967,890
967,498
611,779
637,354

Now what's left is to find object's bounding box minimum & maximum x,y 2d coordinates and how to get them?

      # bbox vertices 3d xyz location
        obj = bpy.data.objects['Sphere']
        obj.bound_box

        [v[:] for v in obj.bound_box]

    output:

    [(-0.9999998211860657, -1.0000003576278687, -1.0),
     (-0.9999998211860657, -1.0000003576278687, 1.0), 
(-0.9999998211860657, 1.0, 1.0), 
(-0.9999998211860657, 1.0, -1.0), 
(1.000000238418579, -1.0000003576278687, -1.0), 
(1.000000238418579, -1.0000003576278687, 1.0), 
(1.000000238418579, 1.0, 1.0), 
(1.000000238418579, 1.0, -1.0)]

How to convert those 3d coords to 2d world_to_camera_view x,y coords?

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.