Sub topic 15
Scripting cameras with bpy
This chapter shows how to build, aim, and switch cameras from Python. Every setting from the earlier chapters has a matching property in the bpy API. This chapter assumes you know the Blender concepts those properties control: focal length, sensor size, depth of field, and timeline markers. It also assumes you can read basic Python. Run the scripts from the Text Editor with Alt+P, or paste them into the Python console.
Object and data are separate
A Blender camera is two datablocks. The camera object holds the transform (location, rotation, constraints). The camera data holds the optical settings (lens, sensor, clipping, depth of field). The object points to the data through its .data property.
This split explains most scripting behavior:
bpy.data.camerasstores camera data.bpy.data.objectsstores the objects that use it.- Several camera objects can share one camera data block, so a lens change affects all of them.
- The scene renders through whichever object is assigned to
scene.camera. Camera data alone never renders.
Creating a camera
The data-API route avoids bpy.ops, which depends on the current context (active area, selection, mode) and can fail when run from a background process. Create the data, wrap it in an object, and link the object into a collection.
import bpy
scene = bpy.context.scene
cam_data = bpy.data.cameras.new("ShotCamera")
cam_data.lens = 50 # focal length in mm
cam_data.sensor_width = 36 # sensor width in mm
cam_obj = bpy.data.objects.new("ShotCamera", cam_data)
scene.collection.objects.link(cam_obj)
cam_obj.location = (7.0, -7.0, 5.0)
scene.camera = cam_obj # make it the active cameraKeep the cam_obj variable. If an object named ShotCamera already exists, Blender names the new one ShotCamera.001. A later bpy.data.objects["ShotCamera"] would then return the older object without raising an error.
Field of view from the lens
Field of view depends on focal length and sensor width: fov = 2 * atan(sensor_width / (2 * focal_length)). You can compute it yourself, which is useful when you want to choose a lens for a target angle.
import math
sensor_width = 36 # mm
for focal_length in (24, 50, 85):
fov = 2 * math.atan(sensor_width / (2 * focal_length))
print(f"{focal_length} mm -> {math.degrees(fov):.1f} degrees")This prints about 73.7, 39.6, and 23.9 degrees. A longer lens on the same sensor gives a narrower view.
Blender also exposes the result as cam_data.angle in radians. It follows the sensor fit setting, so it can differ from the horizontal angle on a portrait frame. Use angle_x and angle_y when you need a specific axis. To set the view by angle instead of millimeters, assign cam_data.angle directly. Blender updates lens to match.
| Property | Meaning | Typical value |
|---|---|---|
| `lens` | Focal length in mm | 50 |
| `sensor_width` | Sensor width in mm | 36 |
| `sensor_fit` | `'AUTO'`, `'HORIZONTAL'`, `'VERTICAL'` | `'AUTO'` |
| `type` | `'PERSP'`, `'ORTHO'`, `'PANO'` | `'PERSP'` |
| `ortho_scale` | Frame size for orthographic cameras | 6.0 |
| `clip_start`, `clip_end` | Near and far cutoff distances | 0.1, 1000 |
| `shift_x`, `shift_y` | Lens shift as a fraction of the frame | 0.0 |
Projection and clipping
Switch the projection by setting cam_data.type. An orthographic camera ignores lens and uses ortho_scale instead, so changing the focal length will appear to do nothing.
import bpy
cam_data = bpy.data.cameras.new("PlanView")
cam_data.type = 'ORTHO'
cam_data.ortho_scale = 8.0
cam_data.clip_start = 0.1
cam_data.clip_end = 100.0If geometry disappears in the camera view, check the clip range first. Objects closer than clip_start or farther than clip_end are not drawn or rendered. A large clip range with a tiny clip_start also reduces depth precision, so keep the range as tight as the scene allows.
Aiming the camera
A Blender camera looks down its local -Z axis, and its local +Y axis points up in the frame. A Track To constraint with those two axes keeps the camera pointed at a subject while you move the camera.
import bpy
cam_obj = bpy.data.objects["ShotCamera"]
target = bpy.data.objects["Subject"]
con = cam_obj.constraints.new(type='TRACK_TO')
con.target = target
con.track_axis = 'TRACK_NEGATIVE_Z'
con.up_axis = 'UP_Y'This script needs an object named Subject to exist. Any empty or mesh works.
The constraint is live: move the subject and the camera follows. If you want a one-time aim that you can then edit by hand, compute the rotation with mathutils instead:
import bpy
cam_obj = bpy.data.objects["ShotCamera"]
target = bpy.data.objects["Subject"]
direction = target.location - cam_obj.location
cam_obj.rotation_euler = direction.to_track_quat('-Z', 'Y').to_euler()Use the constraint when the subject moves or when you animate the camera position. Use the computed rotation when you want plain rotation values that you can keyframe or edit later.
Depth of field
Depth of field lives under cam_data.dof. Enable it, choose a focus target, and set the f-stop. A lower f-stop gives a shallower focus zone and more blur.
import bpy
cam_data = bpy.data.objects["ShotCamera"].data
target = bpy.data.objects["Subject"]
cam_data.dof.use_dof = True
cam_data.dof.focus_object = target
cam_data.dof.aperture_fstop = 2.8If you have no focus object, set cam_data.dof.focus_distance in scene units. When both are set, the focus object takes priority. Depth of field blur is visible in rendered output and in Rendered viewport shading, but the Solid viewport does not show it.
Resolution and composition aids
Render resolution sets the aspect ratio of the frame. Together with the sensor fit, it decides which sensor dimension the lens value applies to. The thirds overlay and passepartout (the darkened area outside the frame) help you judge the framing in camera view.
import bpy
scene = bpy.context.scene
scene.render.resolution_x = 1920
scene.render.resolution_y = 1080
scene.render.resolution_percentage = 100
cam_data = bpy.data.objects["ShotCamera"].data
cam_data.show_composition_thirds = True
cam_data.show_passepartout = TrueResolution is a scene setting, not a camera setting. If you use several cameras in one scene, they all render at the same resolution and aspect ratio. Use passepartout_alpha (0 to 1) to control how dark the outside area is. Lens shift (shift_x, shift_y) moves the frame without rotating the camera, which keeps vertical lines parallel in architectural shots.
Switching cameras with markers
A timeline marker bound to a camera makes that camera active from its frame onward. This produces a cut during animation.
import bpy
scene = bpy.context.scene
cam_b = bpy.data.objects["CameraB"]
marker = scene.timeline_markers.new("CutToB", frame=48)
marker.camera = cam_bBlender applies marker bindings when the frame changes, not at the moment you create the marker. If you read scene.camera right after this script, it may still show the old camera. Call scene.frame_set(scene.frame_current) to force the update. Renders handle this for you, because each rendered frame sets the frame first.
Bind a marker for every camera you want in the sequence, including the first one. The camera before the first marker is whatever scene.camera held.
Animating camera properties
Camera data properties accept keyframes through the same API as any other property. Keyframe the data block, not the object, for lens and depth of field values.
import bpy
cam_data = bpy.data.objects["ShotCamera"].data
cam_data.lens = 35
cam_data.keyframe_insert(data_path="lens", frame=1)
cam_data.lens = 85
cam_data.keyframe_insert(data_path="lens", frame=72)This creates a slow zoom from 35 mm to 85 mm. Keyframes on cam_obj.location and cam_obj.rotation_euler use the object instead. A common mistake is calling keyframe_insert on the object with "lens" as the path, which fails because the object has no such property.
Cleaning up
Deleting a camera object leaves its camera data behind as an orphan until Blender purges unused data on save and reload. In scripts that run repeatedly, remove both.
import bpy
name = "ShotCamera"
obj = bpy.data.objects.get(name)
if obj is not None:
cam_data = obj.data
bpy.data.objects.remove(obj)
bpy.data.cameras.remove(cam_data)Removing the object first lets the data block lose its last user. Removing the data first would leave the object with a broken reference.
Common errors
AttributeErroronscene.camera: the scene has no camera yet, or you assigned a non-camera object. Check thatobj.type == 'CAMERA'.- Lens changes have no effect: the camera is orthographic (use
ortho_scale), or the lens unit is set to field of view and you are reading the wrong property. - Subject appears off-center after aiming: the Track To up axis is wrong, or a parent transform is rotating the camera. Check both.
- Marker cut does not happen in the viewport: the frame has not changed since the marker was created. Call
frame_set.
Exercise
Write a script that creates a camera named "Cam24" with a 24 mm lens, links it to the scene, and prints its horizontal field of view in degrees. What property would you read to get the angle from Blender, and what value do you expect for a 36 mm sensor?
Show answer
Create the data with bpy.data.cameras.new("Cam24"), set lens = 24 and sensor_width = 36, wrap it with bpy.data.objects.new("Cam24", cam_data), and link it with scene.collection.objects.link(cam_obj). Then print math.degrees(cam_data.angle_x). The expected value is about 73.7 degrees, from 2 atan(36 / (2 24)).
Exercise
A scene has cameras A and B. You want a cut from A to B at frame 60. Which two markers do you create, and why does scene.camera still show the old camera right after the script runs?
Show answer
Create one marker at frame 1 bound to camera A and one at frame 60 bound to camera B, using scene.timeline_markers.new(name, frame=...) and setting marker.camera. Blender applies marker bindings when the frame changes, so scene.camera updates only after a frame change, for example with scene.frame_set(scene.frame_current).