How To Use Picamera2 to Take Photos With Raspberry Pi
When Raspberry Pi OS postponed from based on Debian Buster to direct hit, the transition was not the smoothest. For many years, Raspberry Pi OS used three tools to access the official Raspberry Pi camera. The first two were raspistill/raspivid, which offered control and access to the camera from the Linux terminal.
It was a powerful and flexible means of working with the camera, capable of both Produce video effects and stream videos without overtime. The other tool was a community-made project called PiCamera. Originally created by Dave Jones, Picamera has evolved from a collaborative project into an indispensable tool. Picamera provided a pure Python means of interacting with the camera, and being Python based also meant we could blend the camera into our projects.
With the switch to Bullseye, we saw Picamera sadly collapse. Raspberry Pi LTD even went so far as to offer one “Legacy” version of Buster with Picamera and security updates. This was a stopgap while the developers were working on Picamera2. With the Release of Raspberry Pi OS in September 2022 We now have a working Picamera2 module that we can use in our projects.
In this guide we will learn how to use Picamera2’s pretty awesome API [pdf] to take pictures, record videos and work with the GPIO to respond to input to take a picture.
For the projects you need
Connecting your Raspberry Pi camera
The Raspberry Pi camera was part of the Best Raspberry Pi Accessories almost as long as the Pi has been with us. Almost every Raspberry Pi model has a camera connector (CSI) (with the exception of the first Raspberry Pi Zero model), and this meant that the camera quickly became a must-have accessory for your Pi. The same is still true, thanks to the official HQ camera offers much better image quality and a range of interchangeable lenses.
Connecting any official camera to the Raspberry Pi is easy, just follow these steps.
3. Insert the cable with the blue tab facing the USB/Ethernet port.
4. Gently slide the tabs down to fix the cable.
5. Secure / mount the camera so it doesn’t tip over and touch the Pi or its GPIO. One method is to use modeling clay/Blu Tack.
Installing the Picamera2 software
1. Start the Pi.
2. Open a terminal and Update the installed software.
sudo apt update
sudo apt upgrade -y
3. Install the Picamera2 Python3 module. It comes pre-installed for the latest versions of Raspberry Pi OS (as of September 2022), but this command will also update your version to the latest version.
sudo apt install -y python3-picamera2
Taking photos with Picamera2
Taking photos with Picamera2 is the most basic task you can do with the module. It has been designed to be easy to use, but beneath its simplicity hides a complex module that we can customize to our needs.
In this project we will capture an image using a preview to frame the capture.
1. Open Thonny. You can find it in the main menu.
2. In a new file Import the Picamera2 module along with the preview class. In a new row, import the time module. The Picamera2 module allows us to control the camera and the time is used to control how long the preview image stays on screen.
from picamera2 import Picamera2, Preview
import time
3. Create an object, picam2, which is used to reference the Picamera2 module and control the camera.
picam2 = Picamera2()
4. Create a new object, camera_config and Use it to set the resolution of the still image (main image) to 1920×1080. and a “Low Resolution” image with a size of 640 x 480. This low-resolution image is used as a preview image when aligning a shot.
camera_config = picam2.create_still_configuration(main={"size": (1920, 1080)}, lores={"size": (640, 480)}, display="lores")
5. Load the configuration.
picam2.configure(camera_config)
6. Start the preview window and Then start the camera.
picam2.start_preview(Preview.QTGL)
picam2.start()
7. Hold the code for two seconds.
time.sleep(2)
8th. Take a picture and save it as test.jpg.
picam2.capture_file("test.jpg")
9. Save the code as camera-test.py and Click Run to start. A preview window will appear where you can frame your shot. If two seconds delay is too short, change the delay according to your needs.
10 Open the system file manager and Double-click test.jpg to view the image.
Complete code list
from picamera2 import Picamera2, Preview
import time
picam2 = Picamera2()
camera_config = picam2.create_still_configuration(main={"size": (1920, 1080)}, lores={"size": (640, 480)}, display="lores")
picam2.configure(camera_config)
picam2.start_preview(Preview.QTGL)
picam2.start()
time.sleep(2)
picam2.capture_file("test.jpg")
Recording a video with Picamera2
HD video recordings are now a matter of course for us. The same goes for the Raspberry Pi, thanks to numerous models of official (and unofficial) cameras. Picamera2 allows us to record videos in different resolutions with different encoders.
In this project we show how to record a basic 1080P video stream while viewing the stream in a lower resolution window.
1. Open Thonny and create a new file. You can find Thonny in the main menu.
2. Import the H264 encoder from the Picamera2 module.
from picamera2.encoders import H264Encoder
3. Import the Picamera2 module along with the preview class. Next, import the time module.
from picamera2 import Picamera2, Preview
import time
4. Create an object, picam2, which is used to reference the Picamera2 module and control the camera.
picam2 = Picamera2()
5. Create a new object, video_config and Use it to set the still image resolution (main) to 1920×1080. and a “lowres” image with a size of 640 x 480. This low-resolution image is used as a preview image when aligning a shot.
video_config = picam2.create_video_configuration(main={"size": (1920, 1080)}, lores={"size": (640, 480)}, display="lores")
6. Load the configuration.
picam2.configure(video_config)
7. Set the bit rate of the H264 encoder.
encoder = H264Encoder(bitrate=10000000)
8th. Set the output file to test.h264. This will create a file containing the video.
output = "test.h264"
9. Launch the preview window, then start recording with the encoder settings and save the video in the output file.
picam2.start_preview(Preview.QTGL)
picam2.start_recording(encoder, output)
10 Use a sleep mode to record ten seconds of video. The previous record command is not a blocking line of code. With a sleep command we prevent the recording from stopping after fractions of a second.
time.sleep(10)
11. Stop the camera recording and close the preview window.
picam2.stop_recording()
picam2.stop_preview()
12. Save the code as video-test.py and Click Run to start. The preview window appears and you have ten seconds to record a video.
13. Watch the video.You can get there in the file manager by locating test.h264. And double click the video file to play it in VLC.
Complete code list
from picamera2.encoders import H264Encoder
from picamera2 import Picamera2, Preview
import time
picam2 = Picamera2()
video_config = picam2.create_video_configuration(main={"size": (1920, 1080)}, lores={"size": (640, 480)}, display="lores")
picam2.configure(video_config)
encoder = H264Encoder(bitrate=10000000)
output = "test.h264"
picam2.start_preview(Preview.QTGL)
picam2.start_recording(encoder, output)
time.sleep(10)
picam2.stop_recording()
picam2.stop_preview()
Using a trigger to take a picture on the Raspberry Pi
Camera triggers are a classic Raspberry Pi project. They are used to prank images/videos of animals, intruders or unwilling family members. A trigger can be a sensor like a passive infrared (PIR) motion sensor, an ultrasonic sensor, or in our case, a simple push button.
In this project, we’ll create a simple trigger-activated camera trap. We press the button, frame the shot with the preview window and the file is then automatically saved on our Pi, using the current time and date as the file name.
The wiring for this project is simple. The button is connected to GPIO17 and GND via a breadboard and two female to male wires.
1. Open Thonny and create a new file. You can find Thonny in the main menu.
2. Import the Picamera2 module along with the preview class. Next Import the time module.
from picamera2 import Picamera2, Preview
import time
3. Import the datetime, GPIO Zero and Signal modules. Datetime is used to generate a timestamp for our image filenames. GPIO Zero is used for a simple button interface. Signal is used to prevent Python code from exiting.
from datetime import datetime
from gpiozero import Button
from signal import pause
4. Create an object, picam2, which is used to reference the Picamera2 module and control the camera.
picam2 = Picamera2()
5. Create an object, a button, and Use the object to store the GPIO pin that our button is connected to.
button = Button(17)
6. Create a new object, camera_config and Use it to set the resolution of the still image (main image) to 1920×1080. and a “Low Resolution” image with a size of 640 x 480. This low-resolution image is used as a preview image when aligning a shot.
camera_config = picam2.create_still_configuration(main={"size": (1920, 1080)}, lores={"size": (640, 480)}, display="lores")
7. Load the configuration.
picam2.configure(camera_config)
8th. Create a function, capture(), to store a series of commands executed when the shutter button is pressed. Code within the function is automatically indented to indicate that it belongs to the function.
def capture():
9. Launch a preview window. This allows us to shape our image.
picam2.start_preview(Preview.QTGL)
10 Create an object, a timestamp, and Use it to store the time and date of the trigger event.
timestamp = datetime.now().isoformat()
11. Start the camera, then pause for two seconds to give yourself time to frame the picture.
picam2.start()
time.sleep(2)
12. Set the capture file, ultimately the image file, to use the current timestamp as the filename.
picam2.capture_file('/home/pi/%s.jpg' % timestamp)
13. Finally in function stop the preview, and Stop the camera.
picam2.stop_preview()
picam2.stop()
14 Use GPIO Zero’s Button class to respond to a button press by calling our “Capture” function. Finally Use pause() to prevent the code from ending.
button.when_pressed = capture
pause()
fifteen. Save the code as trigger-test.py and Click Run to start the code.
16 Push the button to start the camera and take a picture.
17 Open the system file manager and Double click on the image to view it.
Complete code list
from picamera2 import Picamera2, Preview
import time
from datetime import datetime
from gpiozero import Button
from signal import pause
picam2 = Picamera2()
button = Button(17)
camera_config = picam2.create_still_configuration(main={"size": (1920, 1080)}, lores={"size": (640, 480)}, display="lores")
picam2.configure(camera_config)
def capture():
picam2.start_preview(Preview.QTGL)
timestamp = datetime.now().isoformat()
picam2.start()
time.sleep(2)
picam2.capture_file('/home/pi/%s.jpg' % timestamp)
picam2.stop_preview()
picam2.stop()
button.when_pressed = capture
pause()