I am trying to make a script that will determine the exact coordinates of an object's bounding box in the render. (I later want to limit the rendered space to that area.)
So far I managed to get the coordinates from the object's bound_box And I managed to take the scale and location into account but I failed with the rotation.
My problem is that I have the coordinates of my bounding box but I don't know how to make them follow the rotation, like the bounding box in the viewport does. When I run the script with a cube it works fine, but when the cube is being rotated the coordinates that are being printed out do not change.
import bpy
import bpy_extras
import mathutils
scene = bpy.context.scene
obj = bpy.context.object
co = bpy.context.scene.cursor_location
scale = bpy.data.objects['cube'].scale
bounding_box_vertices = []
for i in range(8):
bounding_box_vertices.append(i)
bounding_box_vertices[i]=[1, 2, 3]
#the Coordinates from bound_box are saved to bounding_box_vertices[[],[]]
for i in range(8):
for j in range(3):
bounding_box_vertices[i][j]=bpy.data.objects['cube'].bound_box[i][j]*bpy.data.objects['cube'].scale[0] + bpy.data.objects['cube'].location[j]
def rendered_coords(x):
co = mathutils.Vector((bounding_box_vertices[x][0], bounding_box_vertices[x][1], bounding_box_vertices[x][2]))
co_2d = bpy_extras.object_utils.world_to_camera_view(scene, obj, co)
render_scale = scene.render.resolution_percentage / 100
render_size = (int(scene.render.resolution_x * render_scale), int(scene.render.resolution_y * render_scale))
#print("Pixel Coords:", (
return([round(co_2d.x * render_size[0]), round(co_2d.y * render_size[1])])
# ))
#prints ou the 8 X and Y coordinates that the bounding box would have on the render (even though its invisible of course)
for i in range(8):
final_coords = rendered_coords(i)
print(final_coords[0])
print(final_coords[1])