Python for Raspberry Pi Cameras: Getting Started

Raspberry Pi with Arducam.

The Python programming language has basically become a lingua franca of machine learning and machine vision.  While there are many other languages that can challenge that title, Python version 3.7 support is included with the Raspberry Pi Operating System (OS).  This makes it a logical starting point for beginners getting used to the Raspberry Pi Camera for the first time.

This project is essentially a direct follow-up on our earlier articles on Setting up the Raspberry Pi 4 and the Raspberry Pi Camera.  Today we will examine how well the camera works in Python 3.7.

Notice of Non-Affiliation and Disclaimer: As of the publication date, we are not affiliated with, associated with, authorized with, endorsed by, compensated by, or in any way officially connected with the Raspberry Pi Foundation., PyImageSearch, HDMI Founders, HDMI Forum, or their owners, subsidiaries or affiliates. The names of the Raspberry Pi Foundation., PyImageSearch, HDMI Founders, HDMI Forum, as well as related names, marks, emblems, and images are trademarks of their respective owners.

External Links: Links to external web pages have been provided as a convenience and for informational purposes only. Unboxing Tomorrow and Voxidyne Media bear no responsibility for the accuracy, legality or content of the external site or for that of subsequent links. Contact the external site for answers to questions regarding its content.

Objectives

  • Double-check your Software Dependencies
  • Try to import the picamera module for Python 3.7
  • Test still image recording in Python
  • Test video recording in Python

Requirements and Obsolescence Note

As much as I like Linux, I’ll put it bluntly by saying future-proofing and backward compatibility of free, open-source software often disappoints, and has for many years.  Guides like this one can become obsolete in just a few years as modules are renamed, backward compatibility is broken, application dependencies or whole repositories go unmaintained, and so on.  To things on-topic, I’ll simply say it’s impossible to guess when this guide could become outdated.

This guide was written in 2020 for the Raspberry Pi Operating System (32-bit) and Linux kernel version 4.1.19.  In the event you find outdated instructions here, your best bet is to refer to official developer resources for the Raspberry Pi, Python, picamera, or one of their dependencies.

With that in mind, this article assumes you have the following in known working condition…

  • A Raspberry Pi (Pi 3B+ or 4 is recommended)
  • Raspberry Pi OS (32-bit)
  • An attached Raspberry Pi Camera (version 2.1 was used here)
  • Your Camera has been enabled (using raspi-config)
  • A 5-volt Power Supply for the Raspberry Pi
  • (Recommended) Back up any data you consider important
  • (Recommended) Anti-static workspace

Starting Python 3.7

In your Raspberry Pi OS Desktop, open the terminal.

This guide will alternate between the terminal and Python’s own command line.  The dollar sign ($) is for things you should type into the terminal.  Don’t enter the dollar sign itself.  The triple-bracket (>>>) will indicate what you should type into the Python command line.

Figure 1: This Guide will Use the Dollar Sign Convention to Distinguish Terminal Commands from Python Commands

In the terminal, enter:

$ sudo apt-get update
$ sudo apt-get upgrade
$ cd /home/pi
$ raspistill -v
Figure 2: The Output of “raspistill -v” Showing Successful Detection of the Camera

If you inspect the output, you should see a line showing the camera information.  This shows that your Raspberry Pi Camera v2.1 is enabled, that your cable is securely attached, and that the picamera library is installed.

Figure 3: The Camera (Sony IMX219) was Properly Identified

Now that we know the camera is usable, enter…

$ python3

This should load the Python environment, which uses the “>>>” prompt.  Try to import the picamera library by typing…

>>> import picamera
>>> import picamera.array
Figure 4: A Lack of Error Messages Indicates the Picamera Resources were Successfully Imported

Create a Test Application

Assuming you got picamera and picamera.array to import, you can exit the Python 3.7 interface by typing:

>>> exit()

Now it’s time to build a Python application that will capture a few seconds of video, and then display the video to the monitor.

Back in the terminal, open the nano text editor by typing…

$ nano testTheCamera.py

Recall that CTRL+O is how you save in the Nano text editor (that’s a letter ‘O’ as in write-Out).  Although the recent versions such as GNU Nano 3.2 seem to have finally come to their senses by permitting CTRL+S for saving as well.  CTRL+X is how you exit the nano editor.

In the resulting text editor, enter the following code…

from picamera.array import PiRGBArray
from picamera import PiCamera
import time

camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 32
camera.rotation = 0
camera.hflip = False
camera.vflip = False
rawCapture = PiRGBArray(camera, size=(640, 480))

camera.start_preview()
time.sleep(5)
camera.stop_preview()

Start_Preview Trouble for Remote Viewing Users

If you use a “headless” Raspberry Pi that has no monitor, then you are probably using a Virtual Network Computing (VNC) connection to view the Raspberry Pi’s desktop.

If this is you, know in advance that the camera.start_preview() will not work unless you find an HDMI or composite monitor to attach.  This is an unfortunate limitation of the start_preview() method.  If you want a workaround that doesn’t involve an HDMI monitor, streaming your video is probably your best bet.  Luckily, this is not an essential feature to have for this guide, so you can skip ahead.

Figure 5: Viewing the Video Preview Requires an HDMI or Composite Video Monitor

Test the Application

Run the application by exiting the Nano editor with CTRL+X.  Then, enter this in the terminal…

$ python3 testTheCamera.py

If you have an attached HDMI or composite video monitor, then you should see 5 seconds of video from the camera.  If you are using a VNC connection, then no video will appear; although your Raspberry Pi power consumption will increase for the same 5 seconds.

Taking Continuous Snapshots

Next, it’s time to capture and save a series still images using Python.  Like the raspistill, this test will capture still images from the Raspberry Pi Camera and then save them to the /home/pi directory.  This example was provided by the picamera official guide. In the terminal, create a new project by entering:

$ nano testTimedCapture.py

In the Nano editor environment, enter the code below. (Note: Fixed truncated code on line 10 on 2020.08.28)

import picamera
import time

with picamera.PiCamera() as camera:
    camera.resolution = (1280, 720)
    camera.rotation = 0
    camera.vflip = False
    camera.hflip = False
    time.sleep(1) # Camera warm-up time
    for i, filename in enumerate(camera.capture_continuous('image{counter:02d}.jpg')):
        print('Captured %s' % filename)
        # Capture one image a minute
        time.sleep(60)
        if i == 59:
                break

Like before, run it by entering:

$ python3 testTimedCapture.py

Just like with the raspistill application, you can adjust the rotation to equal 0, 90, 180, or 270.  Other values will be rounded off to one of those values.  Likewise you may set camera.vflip or camera.hflip to mirror the image as you see fit.

Recording Video to a File

Return to the terminal.  Create a new Python file by typing in:

$ nano testVideoRecord.py

In the resulting nano editor, enter the following lines of code…

import picamera

with picamera.PiCamera() as camera:
    camera.resolution = (640, 480)
    camera.start_recording('my_video.h264')
    camera.wait_recording(60)
    camera.stop_recording()

Save (CTRL+O) and then exit (CTRL+X). Execute program by entering:

$ python3 testVideoRecord.py

Open the Raspberry Pi File Manager.  Make sure you’re viewing the /home/pi directory, and then locate the “my_video.h264” video file.  If you have the full Raspberry Pi OS image with recommended files, you should have an application called VLC Media Player that can open it.  Double-click to open, and you should see your video appear in no time.

Figure 6: Captured Video as Recorded Through the Protective Semi-Transparent Lens Tape

Note that my camera still has the protective tape covering the lens.  This protects the lens from debris, but slightly impairs the image quality.

Closing Remarks

Getting picamera and picamera.array working is an important step toward doing more advanced (more interesting) things such as video streaming and object detection. 

Of course, with more advanced features come more technical frustrations.  Surprises like the video preview problem for VNC users are one of the nastier and less-talked-about aspects of free, open source Linux software.  While I’m sure the picamera developers had their reasons for drawing previews this way (I’d imagine this was to improve frame rate or latency), new users will find that sort of thing counterintuitive and irritating.  There are a few workarounds that don’t involve HDMI, however all of them are beyond the scope of today’s topic.

Things will tend to get even more challenging as you work with larger machine vision frameworks such as OpenCV.  If you’re looking for more insights on what this process may look like, machine vision researcher Dr. Adrian Rosebrock is curating a site dedicated to the OpenCV platform on Raspberry Pi.  It is an external website: https://www.pyimagesearch.com/2016/08/29/common-errors-using-the-raspberry-pi-camera-module/).

In summary, be careful about how you allocate your time to developing open source projects, and always allow way more time than you expect to use.

List of Commands Used Today

$ sudo apt-get update
$ sudo apt-get upgrade
$ cd /home/pi
$ raspistill -v

$ python3
>>> import picamera
>>> import picamera.array
>>> exit()

$ nano testTheCamera.py
$ python3 testTheCamera.py

$ nano testTimedCapture
$ python3 testTimedCapture.py
$ nano testVideoRecord.py

$ python3 testVideoRecord.py
$ sudo apt-get install gpac
$ MP4Box -add my_video.h264 my_video.mp4

References

[1]Nano-editor.org, “Changes between v5.1 and v5.2,” [Online]. Available: https://www.nano-editor.org/dist/latest/ChangeLog. [Accessed 24 Aug. 2020].
[2]Raspberry Pi Foundation, “How to control the Camera Module with Python code,” Raspberry Pi Foundation, [Online]. Available: https://projects.raspberrypi.org/en/projects/getting-started-with-picamera/4. [Accessed 24 Aug. 2020].
[3]“6. Frequently Asked Questions (FAQ),” PiCamera, [Online]. Available: https://picamera.readthedocs.io/en/release-1.10/faq.html#the-preview-doesn-t-work-on-my-pitft-screen. [Accessed 24 Aug. 2020].
[4]“5. Frequently Asked Questions (FAQ),” PiCamera, [Online]. Available: https://picamera.readthedocs.io/en/release-1.12/faq.html. [Accessed 24 Aug. 2020].
[5]PiCamera, “4. Basic Recipes,” [Online]. Available: https://picamera.readthedocs.io/en/release-1.10/recipes1.html#recording-video-to-a-file. [Accessed 24 Aug 2020].
[6]A. Rosebrock, “Common errors using the Raspberry Pi camera module,” PyImageSearch.com, 29 Aug. 2016. [Online]. Available: https://www.pyimagesearch.com/2016/08/29/common-errors-using-the-raspberry-pi-camera-module/. [Accessed 24 Aug. 2020].

Important Notice: This article and its contents (the “Information”) belong to Unboxing-tomorrow.com and Voxidyne Media LLC. No license is granted for the use of it other than for information purposes. No license of any intellectual property rights is granted.  The Information is subject to change without notice. The Information supplied is believed to be accurate, but Voxidyne Media LLC assumes no responsibility for its accuracy or completeness, any error in or omission from it or for any use made of it.  Liability for loss or damage resulting from any reliance on the Information or use of it (including liability resulting from negligence or where Voxidyne Media LLC was aware of the possibility of such loss or damage arising) is excluded.