I am developing a short macro to find the optimal distance to place the camera from an object, so it is fully contained in the render.

One simple solution is to use the maximum side of the bounding box. However, this gives silly results in the case of highly asymmetrical boxes.

My solution is to use the convex hull of the 'shadow' of the points comprising the mesh and minimise the mean square difference between the area of the convex hull and the render window.

However, I notice that the camera matrix does not update after changing the camera position. This can be seen either by printing the camera matrix or printing th loss.

My version of Blender is 3.4.1.

Can someone please advise what I have done wrongly?

    import bpy
    import numpy as np
    from scipy.spatial import ConvexHull

    def CalcAreaLoss(obj, location, distance):

        scene = bpy.context.scene
        camera = scene.camera
        #Change camera position to z
        camera.location = location(distance)

        # Project the convex hull vertices to camera space
        cam_vertices = [_v.co @ camera.matrix_world.inverted() for _v in obj.data.vertices]
        # Find the convex hull of the bounding box vertices
        hull = ConvexHull(cam_vertices)
        # Find the area of the hull and the frame
        area_hull = hull.volume
        area_frame = scene.render.resolution_x*scene.render.resolution_y

        # Calculate square difference
        loss = (area_hull-area_frame)**2
    return loss

    # Example usage
    obj = bpy.context.active_object
    center = obj.location
    location =  lambda d: (center[0], center[1], center[2]+d)
    loss_0 = CalcAreaLoss(obj, location, 0)
    loss_1 = CalcAreaLoss(obj, location, 5)

    print(loss_0, loss_1)


1 Answer 1

import bpy

cam = bpy.context.scene.camera
cam.location.x += 1
  • $\begingroup$ Thank you so much for this solution. Have been looking for a solution to a related problem (finding pixel space bounding boxes after camera movements) and I have been debugging this for 12+ hours and nothing helped. You are nothing short of a hero! $\endgroup$ Commented Aug 21, 2023 at 0:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .