With Picamera2 you control the Raspberry Pi camera straight from Python: take photos, encode video, stream the picture live to a browser, or hand every single frame to OpenCV as a NumPy array. The command-line tools rpicam-still and rpicam-vid are great for quick tests – but as soon as the camera becomes part of a project of your own, there is no way around the Python library.
This guide walks through Picamera2 from installation to motion detection. I ran every script on a Raspberry Pi 3 with current Raspberry Pi OS and an IMX219 module; wherever the Pi 5 or the Camera Module 3 behave differently, it says so. If you haven’t connected a camera yet, start with the basic Raspberry Pi camera setup – this article is about the Python side.
Picamera2 is Raspberry Pi’s official Python library for the camera modules. It is built on the libcamera stack, has replaced the old Picamera library since 2022 and comes pre-installed on Raspberry Pi OS (Desktop). Current version: 0.3.39 (November 2026, also as a Raspberry Pi OS package), free and open source, runs on every Pi from the Zero to the Pi 5.
What is Picamera2 – and how do libcamera and rpicam fit in?
Since Raspberry Pi OS switched to the libcamera stack there are three layers worth telling apart: libcamera is the library that talks to the sensor and does the image processing (exposure, white balance, denoising). The rpicam-apps (rpicam-hello, rpicam-still, rpicam-vid) are ready-made command-line programs on top of it. And Picamera2 is the Python interface to that same libcamera – with an API that is deliberately simple: open the camera, configure it, start it, grab a frame. The complete reference is the official Picamera2 manual (PDF), the source code lives on GitHub.
Important if you know older tutorials: the previous library picamera (without the 2) no longer works with the current camera stack. Code with from picamera import PiCamera cannot be reused as is – the concepts are similar, but the API is different. raspistill and raspivid are gone as well.
What you need
- A Raspberry Pi – Picamera2 runs on every model from the Zero to the Raspberry Pi 5*. I tested on a Pi 3; for Full HD video and OpenCV processing a Pi 4 or Pi 5 is noticeably more relaxed.
- A camera module with a CSI connector: the Raspberry Pi Camera Module 3* with autofocus, the older Camera Module 2 or a compatible clone such as the Arducam 8MP IMX219 NoIR I used for this article – it is currently out of stock, and the Camera NoIR V2* has the same sensor without an IR filter in units made before November 2026 – newer ones use the Sony IMX355 (which camera suits which purpose is covered in the camera module comparison). USB webcams are not what this is about – you talk to those from Python via OpenCV directly.
- On the Pi 5, the 22-to-15-pin camera adapter cable* – the Pi 5’s small camera ports do not fit the modules’ standard cable.
- Current Raspberry Pi OS, 64-bit. Desktop or Lite does not matter; I explain the installation differences in a moment.
- SSH access or a terminal on the Pi – every example runs without a screen.
Before you start Python, check once on the command line that the camera is detected at all:
rpicam-hello --list-cameras
If this says No cameras available!, Picamera2 won’t help either – then the cable, the port or config.txt come first (see troubleshooting at the end). This is what it looks like on my Pi:
Available cameras
-----------------
0 : imx219 [3280x2464 10-bit RGGB] (/base/soc/i2c0mux/i2c@1/imx219@10)
Modes: 'SRGGB10_CSI2P' : 640x480 [200.16 fps - (1000, 752)/1280x960 crop]
1640x1232 [81.07 fps - (0, 0)/3280x2464 crop]
1920x1080 [47.57 fps - (680, 692)/1920x1080 crop]
3280x2464 [21.19 fps - (0, 0)/3280x2464 crop]
Installing Picamera2 – or checking whether it is already there
On regular Raspberry Pi OS with desktop, Picamera2 is already installed. A one-liner shows whether that is the case for you and which version is running:
python3 -c "import picamera2; print('ok')"
dpkg -l python3-picamera2 | grep ^ii
If Picamera2 is installed, the first line answers with ok and the second with the package line including the version – this is what I got:
ok
ii python3-picamera2 0.3.37-1 all Libcamera based python library
If the package is missing, the first line ends with ModuleNotFoundError: No module named 'picamera2' and the second reports dpkg-query: no packages found matching python3-picamera2 – then continue with the next section.
Installing on Raspberry Pi OS Lite
The Lite image ships without Picamera2. Install it via apt – not via pip. Raspberry Pi recommends this explicitly, because only the apt package is guaranteed to match the system’s libcamera version. The --no-install-recommends option leaves out the Qt and desktop dependencies you don’t need without a screen:
sudo apt update
sudo apt install -y python3-picamera2 --no-install-recommends
Installing OpenCV – on the desktop image too
The image processing further down also needs OpenCV – the most widely used open-source library for computer vision. It brings ready-made functions for everything beyond “save the image”: converting colour spaces, finding edges and contours, comparing images, detecting faces or objects, drawing text and shapes. In Python the module is called cv2, and images in it are plain NumPy arrays – exactly the format Picamera2 delivers. OpenCV isn’t preinstalled on either image, not even on Raspberry Pi OS with desktop. Install it via apt as well:
sudo apt install -y python3-opencv
First script: take a photo
The basic pattern of every Picamera2 script has four steps: create the camera object, choose and apply a configuration, start the camera, grab an image. Save the following as photo.py, for example with nano photo.py (Ctrl+O then Enter to save, Ctrl+X to exit):
from picamera2 import Picamera2
picam2 = Picamera2()
config = picam2.create_still_configuration()
picam2.configure(config)
picam2.start()
picam2.capture_file("photo.jpg")
picam2.stop()
print("saved: photo.jpg")
python3 photo.py
After about a second, photo.jpg sits in the current directory at full sensor resolution – on the IMX219 that is 3280 × 2464 pixels, a good 1.9 MB. The many INFO lines libcamera writes to the terminal along the way are normal, not errors. To get rid of them, set the environment variable LIBCAMERA_LOG_LEVELS=*:ERROR before the import.
Two details worth a look: capture_file() tells from the file name which format to write – .jpg, .png or .bmp. And between start() and the capture, Picamera2 gives the sensor a few frames by itself so exposure and white balance have settled. You no longer have to wait artificially like in the old days.
Understanding configurations: preview, still and video
A configuration defines which image streams the camera delivers, at what size and in which format. Picamera2 ships three presets that differ mainly in resolution and buffer count. I read these values straight from the objects:
| Preset | Main stream (main) | Buffers | Meant for |
|---|---|---|---|
create_preview_configuration() | 640 × 480, XBGR8888 | 4 | Preview, quick analysis, motion detection |
create_still_configuration() | full resolution, BGR888 | 1 | Single photos in best quality |
create_video_configuration() | 1280 × 720, XBGR8888, 30 fps | 6 | Video recording and streaming |
The presets are starting points, not limits: every value can be overridden with an argument. Besides the main stream main you can request a second, smaller stream called lores – worth its weight in gold when you want to save a full frame and run calculations on a small copy at the same time, as in the motion detection further down:
from picamera2 import Picamera2
picam2 = Picamera2()
config = picam2.create_still_configuration(
main={"size": (1640, 1232)},
lores={"size": (320, 240), "format": "YUV420"},
)
picam2.configure(config)
print(picam2.camera_configuration()["main"])
print(picam2.camera_configuration()["lores"])
Sensor modes: resolution versus frame rate
The sensor itself only knows a few fixed operating modes, and libcamera automatically picks the matching one for the size you asked for. picam2.sensor_modes tells you which ones exist – for the IMX219 it looks like this:
| Sensor mode | Max. frame rate | Field of view |
|---|---|---|
| 640 × 480 | 200 fps | heavily cropped (1280 × 960 from the centre) |
| 1640 × 1232 | 81 fps | full sensor, 2:1 binned |
| 1920 × 1080 | 47 fps | cropped to 16:9 |
| 3280 × 2464 | 21 fps | full sensor |
The rule of thumb that follows: if you want the full field of view, take 1640 × 1232 (fast) or the full resolution (slow). 1920 × 1080 sounds like Full HD, but on the IMX219 it cuts a much tighter section out of the sensor – the picture looks “zoomed in”. On the Camera Module 3 with its IMX708 the modes are different, the principle is the same – here are the values from the sensor driver and the output of rpicam-hello --list-cameras, not measured by me:
| Sensor mode (IMX708) | Max. frame rate | Field of view |
|---|---|---|
| 1536 × 864 | 120 fps | cropped (3072 × 1728 from the centre), 2:1 binned |
| 2304 × 1296 | 56 fps | full sensor, 2:1 binned |
| 4608 × 2592 | 14 fps | full sensor |
So for video and streams on the Camera Module 3, 2304 × 1296 is the sweet spot: full field of view at 56 fps. The full 4608 × 2592 resolution, at 14 fps, is only useful for photos.
Controlling the camera: exposure, white balance, autofocus
Everything that influences the camera at runtime goes through set_controls() with a dictionary. The control names are libcamera’s; the most important ones are ExposureTime (microseconds), AnalogueGain, AwbMode, ColourGains plus Brightness, Contrast, Saturation and Sharpness. capture_metadata() shows which values the camera is currently using – it is also the tool for finding out why an image is too dark or has a colour cast.
Manual exposure
import time
from picamera2 import Picamera2
picam2 = Picamera2()
picam2.configure(picam2.create_still_configuration(main={"size": (1640, 1232)}))
picam2.start()
time.sleep(1)
meta = picam2.capture_metadata()
print(f"auto: {meta['ExposureTime']} us, gain {meta['AnalogueGain']:.2f}, lux {meta['Lux']:.0f}")
picam2.capture_file("auto.jpg")
# disable auto exposure and set fixed values
picam2.set_controls({"AeEnable": False, "ExposureTime": 10000, "AnalogueGain": 1.0})
time.sleep(0.5) # wait a few frames until the new values take effect
picam2.capture_file("manual_10ms.jpg")
picam2.set_controls({"ExposureTime": 60000, "AnalogueGain": 4.0})
time.sleep(0.5)
picam2.capture_file("manual_60ms.jpg")
picam2.stop()
In my test setup in dim room light (around 50 lux), auto exposure had picked 66 ms and gain 8. That is the longest exposure it uses with default settings; beyond that it only turns up the gain, and with it the noise. The 10 ms image is almost black as expected, the 60 ms image at gain 4 usable. The half second of waiting after set_controls() is not superstition: new values only apply after a few frames, an immediate capture_file() still returns the old image.
White balance
from libcamera import controls
# preset: Auto, Tungsten, Fluorescent, Indoor, Daylight, Cloudy
picam2.set_controls({"AwbMode": controls.AwbModeEnum.Tungsten})
# or fixed colour gains (red, blue) - switches AWB off automatically
picam2.set_controls({"ColourGains": (1.6, 1.4)})
# back to automatic white balance
picam2.set_controls({"AwbEnable": True})
The enumerations for these presets come from libcamera.controls, not from Picamera2 itself – hence the extra import. Fixed colour gains are the right choice for timelapses and anything that compares images: otherwise the white balance drifts from frame to frame and the footage flickers.
The image controls Brightness, Contrast, Saturation and Sharpness are set via set_controls() as well; they act inside the camera’s image pipeline, not on the file afterwards. Saturation: 0 conveniently gives you a clean greyscale image straight from the camera.
Autofocus on the Camera Module 3
The Camera Module 3 has a motorised autofocus that you drive with three controls – here according to the official Picamera2 manual, my IMX219 test module has no focus motor:
from libcamera import controls
# continuous autofocus (for video and streams)
picam2.set_controls({"AfMode": controls.AfModeEnum.Continuous})
# focus once, then shoot - autofocus_cycle() waits for the result
picam2.set_controls({"AfMode": controls.AfModeEnum.Auto})
success = picam2.autofocus_cycle()
picam2.capture_file("focused.jpg")
# manual focus in dioptres: 0 = infinity, 10 = about 10 cm
picam2.set_controls({"AfMode": controls.AfModeEnum.Manual, "LensPosition": 2.0})
On modules without a focus motor – Camera Module 2, HQ Camera, most clones – these controls don’t exist: set_controls() and autofocus_cycle() fail there with RuntimeError: Control AfMode is not advertised by libcamera. To check whether your module has autofocus, use "AfMode" in picam2.camera_controls beforehand. On the Camera Module 2 and its clones, the focus is set at the factory and can at most be adjusted by hand at the lens; Raspberry Pi gives a range of roughly 10 cm to infinity for the Camera Module 2. If you often switch between close and distant subjects, the Camera Module 3’s autofocus is the better choice.
Image upside down? Rotating and mirroring
If the camera hangs the wrong way round – as it did in my test setup – don’t rotate the image afterwards, let libcamera do it. The rotation is part of the configuration and then applies to all streams at once, including video and the live stream:
from libcamera import Transform
from picamera2 import Picamera2
picam2 = Picamera2()
config = picam2.create_still_configuration(transform=Transform(hflip=1, vflip=1))
picam2.configure(config)
hflip mirrors horizontally, vflip vertically, both together make the 180-degree rotation. A 90-degree rotation is something the sensor cannot do – if you need it, do it in the image itself, for example with OpenCV.
NoIR modules: loading the right tuning file
This one caught me first when testing: my module is the NoIR variant without an infrared filter, and every photo under room light had a strong pink cast. That is not a defect but physics – without the filter, infrared light ends up in the red channel. libcamera ships separate tuning files for this case but always picks the regular file for the sensor name automatically, i.e. imx219.json instead of imx219_noir.json. You pass the right one when creating the camera object:
from picamera2 import Picamera2
tuning = Picamera2.load_tuning_file("imx219_noir.json")
picam2 = Picamera2(tuning=tuning)
The difference is obvious: with the NoIR file the colours under artificial light are neutral instead of magenta, and the metadata show the blue gain dropping from 1.07 to 0.75. ls /usr/share/libcamera/ipa/rpi/vc4/ lists the available tuning files (on the Pi 5 the directory is pisp instead of vc4); for the Camera Module 3 NoIR the file is called imx708_noir.json. In daylight the cast never disappears completely – that is not what the NoIR module is made for anyway; it is for night shots with IR illumination.
imx219_noir.json only fits modules with the IMX219. Camera Module 2 units made from November 2026 use the Sony IMX355, and rpicam-hello --list-cameras shows which sensor yours has. For the IMX355, libcamera currently only ships the regular imx355.json, with no separate NoIR file (as of November 2026).
Recording video
Video adds two building blocks: an encoder that compresses the frames and an output that writes the result somewhere. The simplest example records five seconds as a raw H.264 stream:
import time
from picamera2 import Picamera2
from picamera2.encoders import H264Encoder
from picamera2.outputs import FileOutput
picam2 = Picamera2()
picam2.configure(picam2.create_video_configuration(main={"size": (1280, 720)}))
encoder = H264Encoder(bitrate=5_000_000)
picam2.start_recording(encoder, FileOutput("clip.h264"))
time.sleep(5)
picam2.stop_recording()
An .h264 file, however, is just the bare video stream without a container – VLC plays it, most other players and every smartphone do not. For a proper MP4 file you only swap the output.
Writing MP4: PyavOutput instead of FfmpegOutput
Picamera2 has two classes for this, and the choice matters. FfmpegOutput pipes the stream to an external ffmpeg that re-timestamps the frames – on my Pi, five seconds of recording regularly produced files tagged as 60 fps that ran just under four seconds. The newer PyavOutput writes the container directly from Python and carries over the camera’s real timestamps; with it, frame rate and length were correct. The Picamera2 developers describe exactly this problem in the class documentation as the reason for the rewrite.
import time
from picamera2 import Picamera2
from picamera2.encoders import H264Encoder
from picamera2.outputs import PyavOutput
picam2 = Picamera2()
picam2.configure(picam2.create_video_configuration(main={"size": (1280, 720)}))
picam2.start_recording(H264Encoder(bitrate=5_000_000), PyavOutput("clip.mp4"))
time.sleep(5)
picam2.stop_recording()
If you just need a clip of fixed length, one call does it – and it produces an MP4 file as well. All it needs beforehand is picam2 = Picamera2(); if the camera isn’t configured yet, the function applies the video configuration and starts the camera itself:
picam2.start_and_record_video("clip.mp4", duration=10)
Hardware or software encoder: Pi 4 versus Pi 5
The class name H264Encoder is the same on every model, but the technology behind it is not. On the Pi Zero through Pi 4, Picamera2 uses the video chip’s hardware encoder (/dev/video11, driver bcm2835-codec), leaving the CPU largely free. The Pi 5 no longer has a hardware encoder for H.264 – there Picamera2 automatically puts a libav-based software encoder behind the same name, so the code runs unchanged but costs CPU time. According to Raspberry Pi the Pi 5 is designed to handle 1080p at 30 fps in software too; on the Pi 3, by contrast, 720p was the sensible maximum for me.
Live stream in the browser
A picture you can open from any device on the network is the most common camera project of all – and with Picamera2 it is done in about 60 lines. The principle: a JpegEncoder keeps delivering JPEG frames, and a small HTTP server from the Python standard library sends them to the browser as an MJPEG stream. Save the script as stream.py:
import io
import logging
import socketserver
from http import server
from threading import Condition
from picamera2 import Picamera2
from picamera2.encoders import JpegEncoder
from picamera2.outputs import FileOutput
PAGE = """\
<html>
<head><title>Picamera2 live stream</title></head>
<body style="margin:0;background:#111">
<img src="stream.mjpg" style="max-width:100%;height:auto;display:block;margin:auto" />
</body>
</html>
"""
class StreamingOutput(io.BufferedIOBase):
def __init__(self):
self.frame = None
self.condition = Condition()
def write(self, buf):
with self.condition:
self.frame = buf
self.condition.notify_all()
class StreamingHandler(server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.send_response(301)
self.send_header('Location', '/index.html')
self.end_headers()
elif self.path == '/index.html':
content = PAGE.encode('utf-8')
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.send_header('Content-Length', len(content))
self.end_headers()
self.wfile.write(content)
elif self.path == '/stream.mjpg':
self.send_response(200)
self.send_header('Age', 0)
self.send_header('Cache-Control', 'no-cache, private')
self.send_header('Pragma', 'no-cache')
self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')
self.end_headers()
try:
while True:
with output.condition:
output.condition.wait()
frame = output.frame
self.wfile.write(b'--FRAME\r\n')
self.send_header('Content-Type', 'image/jpeg')
self.send_header('Content-Length', len(frame))
self.end_headers()
self.wfile.write(frame)
self.wfile.write(b'\r\n')
except Exception as e:
logging.warning('Removed streaming client %s: %s', self.client_address, str(e))
else:
self.send_error(404)
self.end_headers()
class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):
allow_reuse_address = True
daemon_threads = True
picam2 = Picamera2()
picam2.configure(picam2.create_video_configuration(main={"size": (1280, 720)}))
output = StreamingOutput()
picam2.start_recording(JpegEncoder(), FileOutput(output))
try:
address = ('', 8000)
server = StreamingServer(address, StreamingHandler)
print("Stream running on http://<pi-ip>:8000 - Ctrl+C to stop")
server.serve_forever()
finally:
picam2.stop_recording()
After python3 stream.py, open http://<pi-ip>:8000 in a browser. The stream runs without encryption and without a password – it is meant for your home network, not the internet. To watch it while away from home, use a VPN or Raspberry Pi Connect. On the Pi 3 the load for 720p with this script stayed within reason; the JpegEncoder works in software, so for several simultaneous viewers or Full HD a Pi 4 or 5 is the better base.
Frames as NumPy arrays: OpenCV and motion detection
The real reason to pick Python over the rpicam tools: capture_array() returns the image as a NumPy array – a table of numbers with the shape (height, width, 3), one 8-bit value per colour channel and pixel. That opens up all of image processing, and the tool for it is OpenCV: the library takes such arrays and computes on them without you having to write pixel loops. As a first example we convert a frame to greyscale and let OpenCV find the edges in it with the Canny algorithm – the result is a black-and-white image containing nothing but the outlines. The same three lines are the entry point to everything else: counting contours, detecting colours, reading QR codes or feeding a face detection model.
import cv2
from picamera2 import Picamera2
picam2 = Picamera2()
picam2.configure(picam2.create_still_configuration(main={"size": (1640, 1232)}))
picam2.start()
frame = picam2.capture_array("main")
print(frame.shape, frame.dtype) # (1232, 1640, 3) uint8
gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
edges = cv2.Canny(gray, 100, 200)
cv2.imwrite("edges.jpg", edges)
picam2.stop()
Colour channels: RGB or BGR?
Here lurks a trap that catches everyone who saves colour images with OpenCV: the default configuration reports the format BGR888, but the array arrives in RGB order – libcamera names its formats the wrong way round. I checked it with a red figure in front of the camera: saved directly via cv2.imwrite() (OpenCV expects BGR), the red cap turns blue. So for greyscale, COLOR_RGB2GRAY is correct, and whoever writes or displays colour images with OpenCV converts first:
bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
cv2.imwrite("colour.jpg", bgr)
Alternatively, request the array in the order OpenCV wants right away – then, fittingly confusing, the format in the configuration is called RGB888: main={"size": (1640, 1232), "format": "RGB888"}.
Motion detection with the lores stream
Simple motion detection needs no AI: compare two consecutive greyscale frames, and if enough pixels have changed on average, something happened. You compute that on the small lores stream and only save the full frame from main when it matters. The trick with YUV420: the first rows of the array are the brightness (Y), i.e. a greyscale image without any conversion:
import time
import numpy as np
from picamera2 import Picamera2
picam2 = Picamera2()
config = picam2.create_still_configuration(
main={"size": (1640, 1232)},
lores={"size": (320, 240), "format": "YUV420"},
)
picam2.configure(config)
picam2.start()
time.sleep(1)
THRESHOLD = 6.0 # mean pixel difference that counts as motion
previous = None
while True:
yuv = picam2.capture_array("lores")
current = yuv[:240, :320].astype(np.int16) # Y plane = greyscale image
if previous is not None:
diff = np.abs(current - previous).mean()
if diff > THRESHOLD:
print(f"motion detected (difference {diff:.1f})")
picam2.capture_file(time.strftime("motion_%Y%m%d_%H%M%S.jpg"))
time.sleep(2) # pause so not every frame triggers
previous = current
time.sleep(0.1)
You have to measure the threshold for your setup, it depends on the light: with a static scene the difference sat constantly around 2.1 to 2.6 for me (the sensor noise at roughly 50 lux), waving in front of the camera produced values between 15 and 54. So the 6 has room on both sides; with plenty of light the sensor is less noisy and you can go lower. Run the script once with print(diff) in the loop and read off the numbers before you fix the threshold.
Timelapse by script
rpicam-still --timelapse can do timelapses too, but in your own script you control what makes a timelapse good: frozen exposure and white balance so nothing flickers. For that you read the automatic values after they have settled and write them back as fixed controls:
import time
from picamera2 import Picamera2
INTERVAL = 30 # seconds between two frames
FRAMES = 240 # 240 frames = 2 hours, gives 10 s of video at 24 fps
picam2 = Picamera2()
picam2.configure(picam2.create_still_configuration(main={"size": (1920, 1440)}))
picam2.start()
time.sleep(2)
meta = picam2.capture_metadata()
picam2.set_controls({
"AeEnable": False, "AwbEnable": False,
"ExposureTime": meta["ExposureTime"], "AnalogueGain": meta["AnalogueGain"],
"ColourGains": meta["ColourGains"],
})
for i in range(FRAMES):
start = time.time()
picam2.capture_file(f"tl_{i:04d}.jpg")
time.sleep(max(0, INTERVAL - (time.time() - start)))
picam2.stop()
The line with max(0, …) subtracts the capture time from the interval, otherwise the timing drifts a little with every frame. ffmpeg then builds the video. It comes preinstalled on Raspberry Pi OS with desktop; on Lite, install it first with sudo apt install -y ffmpeg:
ffmpeg -framerate 24 -i tl_%04d.jpg -c:v libx264 -pix_fmt yuv420p timelapse.mp4
If you plan timelapses over several days, with cron instead of an endless loop, you’ll find that variant in the article Timelapse photography with the Raspberry Pi camera.
Excursion: Picamera2 in a virtual environment (optional)
First things first: you do not need a virtual environment for this tutorial. Every example runs with the system Python (python3 script.py), because everything required – Picamera2, NumPy, OpenCV – comes from apt. You’ll only need one when your camera project requires a library that is not available as an apt package: a specific NumPy version, a Telegram bot, an AI library from PyPI.
That is when the virtual environment (venv) comes into play: a separate Python folder per project that pip installs into without touching the system. Advantage: every project has its own versions, nothing collides, and a broken experiment is deleted along with its folder. Disadvantage: by default the environment is sealed off from the system – and that clashes with Picamera2, which is supposed to come from apt, not from PyPI. Concretely you hit two hurdles. First, pip on current Raspberry Pi OS refuses to install system-wide – on purpose, so pip packages don’t overwrite the apt packages the system depends on:
$ pip3 install picamera2
error: externally-managed-environment
On Lite, pip3 isn’t installed at all, so the shell reports pip3: command not found instead; inside a virtual environment you still get pip. Second, a normal virtual environment does not see the system’s apt packages – an import picamera2 ends there with ModuleNotFoundError. One option solves both: create the environment with access to the system packages. Picamera2, libcamera and OpenCV then come from apt, everything else you install into the environment with pip as usual:
# create the environment (once)
python3 -m venv --system-site-packages ~/camera-env
# activate it (in every new shell)
source ~/camera-env/bin/activate
# test: the apt packages are visible
python -c "import picamera2, cv2; print('picamera2 and OpenCV available')"
# example: install a pip package into this environment only
pip install python-telegram-bot
# scripts then run with the environment's Python
python photo.py
# leave the environment
deactivate
Without --system-site-packages you can pull Picamera2 into the environment via pip, but you may get a version that does not match the installed libcamera – exactly the case Raspberry Pi warns about. The price of the option: the environment is no longer fully isolated, an apt upgrade can change the system packages inside it. For camera projects that is the right compromise; if you want maximum isolation, you have to do without Picamera2.
💡 GitHub: All scripts from this article are ready to download in the raspberry.tips GitHub repository – with English comments, exactly as they appear in the text, and a README with the prerequisites.
Troubleshooting
“No cameras available!” or RuntimeError: No camera number 0 found when creating Picamera2(): libcamera sees no camera. Check rpicam-hello --list-cameras first. On the Pi 5 the module belongs on one of the two small ports with the adapter cable; on the Pi 3 and Pi 4 the ribbon cable’s contacts face the HDMI port and the latch must be closed firmly. Clones like my Arducam module are not detected by the firmware automatically – then, as Arducam’s guide describes it as well, set camera_auto_detect=1 to 0 in /boot/firmware/config.txt, add dtoverlay=imx219 (or your module’s sensor name) below it and reboot. Whether the sensor answers is revealed by dmesg | grep imx: a failed to read chip id means cable or module, not software.
RuntimeError: Camera __init__ sequence did not complete: Usually the camera is already in use – another script, a forgotten stream or rpicam-vid is still running. Only one process can use the camera at a time. ps aux | grep -E "python|rpicam" shows the culprit.
ModuleNotFoundError: No module named 'picamera2': Either a Lite image without the apt package, or you are inside a virtual environment without --system-site-packages – see the excursion right above this troubleshooting section.
Images are too dark although auto exposure is on: With default settings, auto exposure on the Camera Module 2 stops at about 66 ms – on the IMX219 and the newer IMX355 alike – and then only raises the gain. With "AeExposureMode": controls.AeExposureModeEnum.Long it allows up to 120 ms. Anything longer has to be set manually: turn AeEnable off and set ExposureTime as in the example above. Raspberry Pi specifies up to 11.76 s for the Camera Module 2. Otherwise, more light helps – and capture_metadata() tells you where auto exposure currently stands.
Preview window: start_preview(Preview.QTGL) fails: Over SSH without a desktop there is no window. Leave the preview out – start() then uses a “null preview” internally, and all captures still work. On the desktop with a screen, Preview.QTGL shows the live image in a window.
Pink cast in every image: NoIR module – load the tuning file, see above.
Frequently asked questions about Picamera2
Picamera was the Python library for the old, proprietary camera stack of Raspberry Pi OS. Picamera2 is its successor based on libcamera and, since 2022, the only supported route. Old scripts with from picamera import PiCamera no longer run on current Raspberry Pi OS; the API is structured similarly but is not compatible.
On Raspberry Pi OS with desktop it is pre-installed. On Raspberry Pi OS Lite you install it with sudo apt install python3-picamera2 --no-install-recommends. Raspberry Pi does not recommend installing via pip, because the version may then not match the system’s libcamera.
Only necessary if your project needs pip packages – for the examples here the system Python is enough. If you do: create the virtual environment with python3 -m venv --system-site-packages. It then sees the apt packages picamera2, libcamera and OpenCV, and pip installs everything else into the environment. Without this option, import picamera2 ends with ModuleNotFoundError, and pip install picamera2 in the system Python on the desktop image fails with externally-managed-environment.
Yes, with identical code. Two differences: the Pi 5 needs the 22-to-15-pin adapter cable for the camera modules, and it has no hardware encoder for H.264 – Picamera2’s H264Encoder works in software there automatically and loads the CPU more than on the Pi 4.
With the H264Encoder and PyavOutput as the output: picam2.start_recording(H264Encoder(), PyavOutput("clip.mp4")). PyavOutput carries over the camera’s timestamps directly; with the older FfmpegOutput, frame rate and duration of the file were wrong in our tests. For clips of fixed length, picam2.start_and_record_video("clip.mp4", duration=10) is enough.
Only to a limited extent. Picamera2 is built for the camera modules on the CSI connector. According to the manual it can open USB webcams, but only with the main stream in MJPEG or YUYV format; don’t expect video recording or the Pi camera modules’ controls to work there. For webcams, OpenCV (cv2.VideoCapture(0)) is usually the simpler route in Python, and ffmpeg on the command line.
Conclusion
Picamera2 takes the tedious part off your hands – sensor modes, exposure, encoders – and leaves you the interesting one: what happens with the images. Four lines for a photo, an encoder and an output for video, an array for everything OpenCV can do. You now know the three stumbling blocks that cost me time while testing: the virtual environment without system packages, the swapped colour channels and the wrong tuning file on the NoIR module. The rest is experimenting – have fun with it.