Writing camera software on a Raspberry Pi with Picamera2
My calibration scripts started out on a laptop with cv2. VideoCapture(0).
Code: rpi-capture.py in camera_calibration_with_charuco · Watch: The upgraded rover with a Pi camera
My calibration scripts started out on a laptop with cv2.VideoCapture(0). In June 2025 I added a Raspberry Pi version with autofocus, and a small script turned out to touch most of what’s different about cameras on a Pi. Here’s what I’d tell anyone starting today.
The old camera stack is gone
If you search for Raspberry Pi camera code, half of what you find uses raspistill, raspivid or the original picamera Python library. None of that works on Raspberry Pi OS Bookworm. The camera now runs on libcamera, the command-line tools are rpicam-still and rpicam-vid, and the Python library is Picamera2.
Picamera2 comes from apt, not pip, because it depends on libcamera’s Python bindings, which pip can’t build. If you use a virtual environment, create it so it can see system packages:
sudo apt install python3-picamera2 python3 -m venv —system-site-packages .venv source .venv/bin/activate pip install opencv-python
Without —system-site-packages, import picamera2 fails inside the venv even though it’s installed. It’s the Python version of a package that’s installed globally but missing from your project’s node_modules.
Getting frames into OpenCV
from picamera2 import Picamera2
camera = Picamera2()
config = camera.create_preview_configuration(
main={"size": (1920, 1080), "format": "RGB888"}
)
camera.configure(config)
camera.start()
frame = camera.capture_array() # a NumPy array, shape (1080, 1920, 3)
That array goes straight into any OpenCV function. No conversion, no temporary files.
RGB888 is really blue, green, red
This one looks like a bug the first time you see it. Picamera2 uses libcamera’s format names, and in that naming scheme RGB888 means each pixel is stored as blue, green, red in memory. So the array you get is in BGR order.
That happens to be exactly what OpenCV expects, so cv2.imwrite(“shot.jpg”, frame) saves the right colours. The surprise comes when you hand the same array to something that expects real RGB, like Pillow or matplotlib. Red and blue swap, and skin tones go blue. If you need RGB:
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
Name your magic numbers
The autofocus setup in my script used raw numbers, with comments saying what they meant:
cam.set_controls({
"AfMode": 2, # 2 = Auto mode
"AfTrigger": 0, # 0 = Start AF
"AfSpeed": 1, # 1 = Normal speed
"AfRange": 0, # 0 = Full range
})
Three of the four comments are wrong. In libcamera, AfMode 2 is continuous autofocus, AfSpeed 1 is fast, and AfRange 0 is normal (full is 2). AfTrigger only does anything in auto mode, so in continuous mode it’s ignored.
None of that crashes, which is why it’s easy to miss. libcamera ships named enums, and using them makes the code say what it does:
from libcamera import controls
camera.set_controls({
"AfMode": controls.AfModeEnum.Continuous,
"AfSpeed": controls.AfSpeedEnum.Fast,
"AfRange": controls.AfRangeEnum.Normal,
})
It’s the same argument as TypeScript enums or string unions over bare numbers. A wrong comment is worse than no comment, and an enum can’t drift from what it means.
Whether continuous autofocus is what you want is another question. For calibration it definitely isn’t, and that gets its own post.
The frame you save might be old
The capture loop looked like this:
while True:
frame = camera.capture_array()
user_input = input("Press Enter to capture (or 'q' to quit): ")
if user_input.lower() == 'q':
break
cv2.imwrite(image_filename, frame)
Read it in order. The frame is grabbed first, then the script waits for Enter. So the image you save is the one taken right after the previous save, before you moved the board into its next position. For calibration, where every image should show the board somewhere new, that quietly gives you near-duplicates.
The fix is to capture after the key press:
import os
import cv2
from picamera2 import Picamera2
from libcamera import controls
camera = Picamera2()
config = camera.create_preview_configuration(main={"size": (1920, 1080), "format": "RGB888"})
camera.configure(config)
camera.set_controls({"AfMode": controls.AfModeEnum.Continuous})
camera.start()
os.makedirs("images", exist_ok=True)
index = 1
while True:
if input("Enter to capture, q to quit: ").strip().lower() == "q":
break
frame = camera.capture_array() # taken after Enter, so it's the shot you aimed
cv2.imwrite(os.path.join("images", f"{index}.jpg"), frame)
print(f"saved images/{index}.jpg")
index += 1
camera.stop()
It’s the same class of bug as reading a value before an await and using it after: the code looks sequential, but the world moved in between.
Working headless
One thing the Pi script gets right: it uses input() instead of cv2.imshow() and a key press. imshow needs a display, so it fails over SSH. A prompt in the terminal works anywhere, which matters when the Pi is bolted to a robot with no screen.
When you do want to see the camera, rpicam-hello shows a preview on a connected monitor, and is the quickest check that the camera is detected at all.