In this tutorial you will learn how to use the Raspberry Pi camera with the Python picamera library. You will use picamera to capture images and videos, and also to customize the settings of the Pi camera.
The tutorial works for Raspberry Pi 4, but also for previous versions of the board: RPi 2 and RPi 3.
Let’s get started!
Setup – Raspberry Pi camera, picamera library, Python3, IDE
First, make sure you have installed an OS on your Raspberry Pi, plugged the camera, and enabled it. If you haven’t done that yet, check out this Raspberry Pi camera tutorial where you’ll get all the setup steps, as well as a tour of the raspistill terminal command.
Then, if you have installed Raspberry Pi OS, everything is already configured for you. Python3 is the default, you can also use the Thonny IDE for Python, and the picamera Python library is installed.
To check if the picamera library is installed, open a Python Shell (either from the Thonny IDE, or simply type
python3 in a terminal), and execute
import picamera. If you don’t get any message when you press ENTER, it means that everything is fine and you can use the picamera module. If, however, you get an error such as ” ModuleNotFoundError: No module named ‘picamera’ “, you’ll need to manually install the module.
You are learning how to use Raspberry Pi to build your own projects?
Check out Raspberry Pi For Beginners and learn step by step.
Get this course for FREE for 14 days! Just click on the link above.
No worries, it’s quite easy. First make sure you have pip3 available on your environment, and then install the picamera module from pip3.
$ sudo apt install python3-pip $ pip3 install picamera
Take a picture with Python and picamera
Open up an IDE, such as Thonny Python IDE, or any other IDE/text editor of your choice.
Basic code with picamera module
Here’s the Python code to take a picture with the Raspberry Pi camera, using the picamera library.
from picamera import PiCamera camera = PiCamera() time.sleep(2) camera.capture("/home/pi/Pictures/img.jpg") print("Done.")
Let’s bread this code down line by line.
from picamera import PiCamera
First, we import the PiCamera class from the picamera module. We are going to use that class to get access to the physical camera.
camera = PiCamera() time.sleep(2)
Then we create an object from the PiCamera class. When we create this object, the camera will start initializing itself. To do that it needs about 2 seconds.
That’s why we are then waiting for 2 seconds, before we do anything else. If you want to see the difference, you can try commenting that line, and you’ll see that the quality of the picture we take is not that great – because the camera did not have enough time to adjust to the brightness and other characteristics of the room.
You can use the capture() function from the camera object to take a picture. You will have to give at least one argument: the path and name of the file to store the picture. Here we store the picture in the Pictures/ directory of the pi user, which is the default user on Raspberry Pi OS. Don’t forget the extension (most common: “.jpg”, you can also use “.png”), this will be helpful if you want to share and open the picture in Windows for example.
And I’ve also added a print to get a visual clue to know when the picture has been taken.
Now, run the program, and you should have a new picture file in your Pictures/ directory!
Customize the pictures you take with picamera
Great, you can now take a photo. But what if you want to change the resolution, flip the image, apply some effects, etc ?
Well, you can do all of that with the picamera Python library.
Simply set the options after you’ve created the camera object, and before you take a picture.
from picamera import PiCamera import time camera = PiCamera() camera.resolution = (1280, 720) camera.vflip = True camera.contrast = 10 camera.image_effect = "watercolor" time.sleep(2) camera.capture("/home/pi/Pictures/img.jpg") print("Done.")
As you can see, all settings are attributes of the PiCamera class. To see the list of all settings and values you can use, check out the PiCamera API documentation. Use CTRL+F to quickly search any setting on the page.
So, what did I change here?
camera.resolution = (1280, 720): this setting will change the resolution of the pictures you take. The default resolution for the standard Pi camera module v2 is 3280 x 2464. You may not need such a high resolution every time, because it impacts the size of the file a lot. So, to set the resolution, simply use the “resolution” attribute. You will need to give a tuple with 2 numbers: first the width, then the height, in pixels.
camera.vflip = True: depending on how you position the camera, you may see that the image is upside down. Instead of physically modifying the position of the camera or do post-processing work, you can fix this by setting the “vflip” attribute to True. “vflip” means “vertical flip”. You can also find the same for horizontal flip, using the “hflip” attribute. Finally, if you want to rotate the image, you can also use the “rotation” attribute, and give a number of degrees for the rotation. For example, using
camera.rotation = 180will have the same effect as setting the “vflip” attribute to True.
camera.contrast = 10: The contrast setting goes from -100 to 100, 0 being the default (no change). Here with 10 we increase the contrast a little bit. On the documentation, you can find many other similar and complementary settings, such as saturation, brightness, and so on. Make sure to check what is the range for accepted values, and what is the default value. For example, the brightness setting goes from 0 to 100, 50 being the default.
camera.image_effect = "watercolor": You can also use a bunch of complete premade settings to apply effects on your pictures. This is quite similar to the filters you can applies with smartphones. Here the value is a string describing the name of the effect. The complete list is available on the documentation. Use CTRL+F with “image_effect” to easily find the list.
Now that those 4 settings are set, we can wait for 2 seconds for the camera to be initialized.
time.sleep(2) can be executed either just after creating the camera object, or after changing the settings. The result will be the same.
After that, all pictures you take will have the characteristics you’ve chosen. You can then change any setting at anytime, the modification will affect the next picture you take.
Make the name of the picture unique
You can now take customized pictures with the Raspberry Pi camera, Python, and the picamera library. But there’s still one small thing to do.
As you can see, if you execute the script multiple times with the same file name, then the new picture will erase the previous one. How to solve that?
There is a simple way to overcome this issue: you can add the timestamp to the name of the file. This way, every file name will be unique, because a timestamp is never twice the same (until now, we haven’t discovered how to go back in the past).
from picamera import PiCamera import time camera = PiCamera() time.sleep(2) camera.resolution = (1280, 720) camera.vflip = True camera.contrast = 10 camera.image_effect = "watercolor" file_name = "/home/pi/Pictures/img_" + str(time.time()) + ".jpg" camera.capture(file_name) print("Done.")
You can see the changes on the highlighted lines.
First, we import the time library to get access to time functionalities.
Then, instead of giving a hard-coded path and name for the picture, we build one, including the current timestamp in seconds with the
Now you can run the same script multiple times, and see that every time you have a new picture file. And even better, you can easily sort all pictures by name, which is also the order in which they’ve been taken.
Note: this is one way to easily make the name unique, but of course you can use any other method you want. You could use an UUID, or simply a counter (img1.jpg, img2.jpg), but in this case you would need to also store the counter somewhere so you don’t overwrite the previous pictures when you run the program again.
Record a video with Python and picamera
Let’s now see how to record a video with your Raspberry Pi camera and Python.
from picamera import PiCamera import time camera = PiCamera() time.sleep(2) camera.resolution = (1280, 720) camera.vflip = True camera.contrast = 10 file_name = "/home/pi/Pictures/video_" + str(time.time()) + ".h264" print("Start recording...") camera.start_recording(file_name) camera.wait_recording(5) camera.stop_recording() print("Done.")
And let’s break this code down line by line.
from picamera import PiCamera import time camera = PiCamera() time.sleep(2) camera.resolution = (1280, 720) camera.vflip = True camera.contrast = 10
First, we import the PiCamera class from the picamera module, and also the time module, as we did before.
The way to setup the camera is the same for pictures and videos. You create a PiCamera object, you wait 2 seconds, and you choose whatever settings you want to apply.
file_name = "/home/pi/Pictures/video_" + str(time.time()) + ".h264"
For the file name, here again we use the timestamp to make the name unique. Note that we use “.h264” for the extension, which is a pretty common extension with a good quality/size ratio.
print("Start recording...") camera.start_recording(file_name) camera.wait_recording(5) camera.stop_recording() print("Done.")
And then, we record a video. To do that you need to call 3 functions consecutively.
The name of the functions is pretty self explanatory.
- First, we start recording with
start_recording(file_name)and also we give the name of the file to save the video into.
- Then, and this is important, we have to use the
wait_recording(time_in_seconds)function to continue recording for the amount of seconds we want.
- Finally, we can stop recording with
To make it nicer when you execute the program, you can also add a print before, and another one after those 3 lines. This will tell you when the recording is starting and when it’s finishing.
Conclusion – picamera Python library
In this tutorial you’ve seen how to use the picamera Python library to take pictures and videos with your Raspberry Pi camera.
This is a great first step, because many cool and impressive applications you can do with your Pi require to use the camera.
If you want to go further you can:
- Check out the Pi camera API documentation and try different settings on your own.
- Combine pictures and videos with computer vision to make your applications smarter. OpenCV is a good starting point. This library is also available for Python and makes a great combo with the picamera module.