raspberry pi camera v2.1

Since its release, the Picamera library which allows to control and to exploit the camera of Raspberry Pi has evolved a lot. In this article, we will see the changes introduced in version 1.8 as well as the new features of version 1.9 (if you need, the official documentation can be found here). For those who take the running train and discover the Raspberry Pi, we will start with a small reminder of the steps to follow to activate the camera on the Raspbian distribution.

Which camera to choose for Raspberry Pi?

Before getting to the heart of the matter, here’s a quick reminder of the cameras available for the Raspberry Pi. The current version 2 is available in two versions.

The first one designated v2.1 is a traditional color camera based on a CMOS 8MP sensor (the pixels do not overflow on the neighbors in case of saturation).

The second designated camera v2.1 NoIR is equipped with a sensor on which the infrared filter has not been installed. The camera is more sensitive when there is little light.

Attention, some denominations are misleading, it is not a night vision camera. In full black, the sensor will be completely blind. On the other hand, by adding a complementary light (2 or 3 infrared LED), the sensor is (really) very powerful. In full black, you can hope to see at 10m, which is enough to make a 100% DIY surveillance camera. To read more, you can read this detailed comparison.

Alongside the official Raspberry products, many manufacturers (mainly Chinese) sell compatible cameras. Very often the performance is lower but the budget too.

Here is a brief summary of the main technical features.

Color camera v2.1 official Raspberry Camera v2.1 NoIR (1) official Raspberry Asian NoIR (1) camera

(2x Red Leds)

raspberry pi camera v2.1 raspberry pi v2.1 noir camera official  noir compatible camera raspberry pi
Connector CSI CSI CSI, compatible Raspberry
Dimensions 25 × 24 × 9 mm 25 × 24 × 9 mm 25 x 24 x 26 mm

25 x 75 x 26mm (avec Leds)

Resolution 8MP

3280 × 2464 pixels

8MP

3280 × 2464 pixels

5MP

2592 × 1944 pixels

Sensor CMOS Sony IMX219 CMOS Sony IMX219 CMOS OmniVision OV5647
Video resolution (max.) 1080p30 1080p30 1080p30
Sensor size 1/4 pouces 1/4 pouces 1/4 pouces
Driver V4L2  V4L2  V4L2
Focale 3.60 mm 3.60 mm 3.60 mm
Field of vision 53°(horiz.) x 41°(vert.) 53°(horiz.) x 41°(vert.) 75,7° (horiz.)
Price About €28 About €29 Aliexpress, about €18

Banggood, à partir de 15€

(1) The NoIR designation means that the camera is not equipped with an infrared filter. That is to say that it has a much better sensitivity in low light. This sensitivity can be improved with additional LED lighting. Additional lighting is even mandatory outside or at night. They are not night vision cameras. In return, the image is much less colored. This type of camera is mainly intended for video surveillance.

Which camera for the Raspberry Pi Zero W?

The Raspberry Pi Zero W just as the 1.3 revision has a camera connector. Yes, but it is smaller than Raspberry Pi. It is quite possible to use a v2.1 camera or v2.1 NoIR by replacing the flexible table with a compatible table (also called camera ribbon).

If you already have a camera, you can buy it in Asia about €2.

adaptateur nappe camera raspberry pi zero 1.3

Connect the camera to the Raspberry

The Raspberry Pi has a dedicated CSI connector to communicate with compatible cameras. The CSI connector is located right next to the HDMI video output. Before connecting the camera to Raspberry, stop Raspbian and unplug the card.

Lift the connector

raspberry pi camera connector connecteur picamera

There is no sense indicator on the ribbon. Insert the ribbon by placing the tracks toward the HDMI connector.

raspberry pi connect ruban camera picamera

Close the connector. It is locked by lowering it all the way down. There is no “click” that confirms the closing of the connector. Pull slightly to make sure the ribbon is in place and properly secured. As you can imagine, this is not a foolproof mechanical assembly. Do not use too much mechanical action on the ribbon, otherwise the camera will be disconnected.

camera connectee raspberry pi 3

Enable camera module on Raspbian

Before you can use the camera module, it is necessary to activate it. Open the Menu and then Preferences and open the Raspberry Pi Configuration panel. Go to the Interfaces tab and activate the camera module.

 raspberry pi configuration camera

If you use Raspberry Pi only from the command line or from an external SSH connection, you can also access raspi-config with the sudo raspi-config  command. Go to menu 6 (Enable Camera) and answer with Yes.

raspberry pi activer module camera v2

In any case, you will have to restart to take the new setting into account.

Installing the Picamera library

The Picamera library is one of the basic packages of the Raspbian distribution. However, it does not cost a lot to check that all necessary packages are present on your system. Run the dpkg-query -l ‘* picamera *’  command to enumerate packets that contain the string * picamera *. You should have the following 3 packages installed on your system.

dpkg-query -l '*picamera*'
Souhait=inconnU/Installé/suppRimé/Purgé/H=à garder
| État=Non/Installé/fichier-Config/dépaqUeté/échec-conFig/H=semi-installé/W=attend-traitement-déclenchements
|/ Err?=(aucune)/besoin Réinstallation (État,Err: majuscule=mauvais)
||/ Nom                               Version               Architecture          Description
+++-=================================-=====================-=====================-========================================================================
ii  python-picamera                   1.12                  armhf                 Pure Python interface to the Raspberry Pi's camera module.
un  python-picamera-docs              <aucune>              <aucune>              (aucune description n'est disponible)
ii  python3-picamera                  1.12                  armhf                 Pure Python interface to the Raspberry Pi's camera module.

If not, start by installing them

sudo apt-get install python-picamera python3-picamera

Take advantage to put your system on

sudo apt-get update
sudo apt-get upgrade
sudo reboot 

Raspberry Pi Firmware Update

Warning. It is best to make a backup copy of the SD card before updating the firmware. Follow this guide if necessary.

Another point to check is the Raspberry firmware (GitHub repository). Before updating the firmware, you can check the firmware version number with the command uname -a

$ uname -a
Linux raspberrypi 4.4.26-v7+ #915 SMP Thu Oct 20 17:08:44 BST 2016 armv7l GNU/Linux

The revision number is located next to #. This is the 915.

Then, run the rpi-update  command to update the firmware. The operation lasts a few minutes

$ sudo rpi-update
 *** Raspberry Pi firmware updater by Hexxeh, enhanced by AndrewS and Dom
 *** Performing self-update
 *** Relaunching after update
 *** Raspberry Pi firmware updater by Hexxeh, enhanced by AndrewS and Dom
 *** We're running for the first time
 *** Backing up files (this will take a few minutes)
 *** Remove old firmware backup
 *** Backing up firmware
 *** Remove old modules backup
 *** Backing up modules 4.4.26-v7+
This update bumps to rpi-4.4.y linux tree
Be aware there could be compatibility issues with some drivers
Discussion here:
https://www.raspberrypi.org/forums/viewtopic.php?f=29&t=144087
##############################################################
 *** Downloading specific firmware revision (this will take a few minutes)
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   168    0   168    0     0     58      0 --:--:--  0:00:02 --:--:--    58
100 51.8M  100 51.8M    0     0   262k      0  0:03:22  0:03:22 --:--:-- 1452k^N
 *** Updating firmware
 *** Updating kernel modules
 *** depmod 4.4.37-v7+
 *** depmod 4.4.37+
 *** Updating VideoCore libraries
 *** Using HardFP libraries
 *** Updating SDK
 *** Running ldconfig
 *** Storing current firmware revision
 *** Deleting downloaded files
 *** Syncing changes to disk
 *** If no errors appeared, your firmware was successfully updated to df7fffc29d6f0e561f324699d0018756a0d0afbc
 *** A reboot is needed to activate the new firmware

Finally, restart the Raspberry

sudo reboot 

After the update, the firmware is switched to revision # 936.

$ uname -a
Linux raspberrypi 4.4.37-v7+ #936 SMP Fri Dec 9 16:56:49 GMT 2016 armv7l GNU/Linux

Functions deprecated since version 1.8

Since version 1.8 of the piCamera library, many changes have been made. These functions will be permanently removed from the library as of version 2.0. For now, all existing codes can work. Developers have clarified the writing of many functions.

It is possible to add a marker in your code to find deprecated functions more easily. For this add this piece of code to your projects:

import warnings
warnings.filterwarnings('default', category=DeprecationWarning)

For example, if you run the following code (from official documentation)

import io
import time
import picamera

import warnings
warnings.filterwarnings('error', category=DeprecationWarning)

with picamera.PiCamera() as camera:
    camera.resolution = (1280, 720)
    camera.framerate = (24, 1)
    camera.start_preview()
    camera.preview_fullscreen = True
    camera.preview_alpha = 128
    time.sleep(2)
    camera.raw_format = 'yuv'
    stream = io.BytesIO()
    camera.capture(stream, 'raw', use_video_port=True)

You will get the following messages:

python livepreview.py 
/usr/lib/python2.7/dist-packages/picamera/mmalobj.py:297: PiCameraDeprecated: Setting framerate or gains as a tuple is deprecated; please use one of Python's many numeric classes like int, float, Decimal, or Fraction instead
  "Setting framerate or gains as a tuple is "
/usr/lib/python2.7/dist-packages/picamera/camera.py:3396: PiCameraDeprecated: PiCamera.preview_fullscreen is deprecated; use PiCamera.preview.fullscreen instead
  'PiCamera.preview_fullscreen is deprecated; '
/usr/lib/python2.7/dist-packages/picamera/camera.py:3340: PiCameraDeprecated: PiCamera.preview_alpha is deprecated; use PiCamera.preview.alpha instead
  'PiCamera.preview_alpha is deprecated; use '
/usr/lib/python2.7/dist-packages/picamera/camera.py:1854: PiCameraDeprecated: PiCamera.raw_format is deprecated; use required format directly with capture methods instead
  'PiCamera.raw_format is deprecated; use required format '
/usr/lib/python2.7/dist-packages/picamera/camera.py:1365: PiCameraDeprecated: The "raw" format option is deprecated; specify the required format directly instead ("yuv", "rgb", etc.)
  'The "raw" format option is deprecated; specify the '
/usr/lib/python2.7/dist-packages/picamera/camera.py:1848: PiCameraDeprecated: PiCamera.raw_format is deprecated; use required format directly with capture methods instead
  'PiCamera.raw_format is deprecated; use required format '

Camera.capture function

The capture format had to be defined in a raw_capture variable and then called

Old syntax

camera.raw_format = 'rgb'
camera.capture('output.data', format='raw')

New syntax

Now you directly pass the desired parameter directly into the format option like this.

camera.capture('output.data', format='rgb')

Recording quality: the quantization parameter becomes quality

The funny quantization denomination is abandoned to profit you term quality much clearer.

camera.start_recording('foo.h264', quantization=25)

Becomes

camera.start_recording('foo.h264', quality=25)

Fractional numbers

Previously, it was necessary to pass the fractional number (widely used for image ratios) in the form (numerator, denominator). Since version 1.8, the piCamera library supports Python types int, float, Decimal and fraction. For example, to indicate the framerate, you can do like this now

camera.framerate = Fraction(72, 3)
camera.framerate = Decimal('24')
camera.framerate = Fraction('48/2')

Preview: preview

It is possible to have several layers overlay. To do this, the preview function has been separated from the library. The preview_alpha, preview_fullscreen, and preview_window attributes are now methods of the preview function.

Old syntax

camera.start_preview()
camera.preview_alpha = 128
camera.preview_fullscreen = False
camera.preview_window = (0, 0, 640, 480)

New syntax

camera.start_preview()
camera.preview.alpha = 128
camera.preview.fullscreen = False
camera.preview.window = (0, 0, 640, 480)

Even easier, we can now pass all the parameters when calling the preview function like this

camera.start_preview(alpha=128, fullscreen=False, window=(0, 0, 640, 480))

Finally, the previewing attribute is now obsolete. To test whether the camera is already started, we must do so now

if camera.preview:
    print('The camera preview is running')
else:
    print('The camera preview is not running')

Zoom replaces crop

The crop function could be confusing because it might suggest that this function could cut the image when it was not. The semantics is corrected.

Old syntax

camera.crop = (0.25, 0.25, 0.5, 0.5)

New syntax

camera.zoom = (0.25, 0.25, 0.5, 0.5)

What’s new in version 1.9

Version 1.9 is mostly version that fixes several bugs and introduces some new functions:

  • The sensor_mode parameter is used to force the setting of the camera during initialization(#165)
  • The refresh rate as well as the resolution of the camera can be specified as initialization arguments, which reduces the initialization time(#180)
  • Raspstill still_stats support(#166)
  • Fixed the led attribute that should now work on the Raspberry Pi B + model(#170)
  • Fixed a memory leak in the renderer that could appear after repeated overlay creation / destruction(#174)
  • Fixed a bug when recording an MPEG movie when the resolution was higher than VGA (#47 and #179).
  • Fixed a bug on the metadata of the PiCameraCircularIO function. The backward compatibility is no longer assured, it will be necessary to take all the existing codes in following the new spécifications of the attributes(#177)
  • Other bug fixes #176#167, #168, #171, #172, #182

Example: live image display of the camera with snapshot at the keyboard

The Raspbian distribution is delivered without any default utility to directly view the image produced by the camera module. It does not matter, it is the opportunity to show how to implement the Picamera library to interact with the camera module. With a live display, you can easily adjust the focus of the lens without having to record a long video.

Here is a small Python program that performs the following operations:

  • Live view of the camera in full screen
  • Keyboard functions (using the Pygame library)
    • Space bar: save a snapshot. The image is saved in the same directory as the Python program. A counter is incremented at each snapshot. Caution, the counter is reset every time the program is started.
    • Enter / Return: Record a 10-second video clip. It is possible to change the duration in the take_video function
    • Esc: exit the program

To retrieve events from the keyboard (we can also retrieve the events of the mouse, a touch screen …), we will use the Pygame library which is dedicated to the creation of games in Python. Begin by installing the Pygame library on your environment.

pip install pygame

For example, go to the /home/pi/Documents  folder and open the text editor by naming the file (eg livecamera.py). Paste the code below.

import io, time, os, sys, picamera, pygame

# Display warning for deprecated Picamera functions (since v1.8) / affiche alerte si une fonction depreciee est utilisee 
import warnings
warnings.filterwarnings('default', category=DeprecationWarning)

pics_taken = 0
vid_taken = 0

# Init pygame and screen / initialise pygame et ecran
pygame.init()
res = pygame.display.list_modes() # return the resolution of your monitor / resolution du moniteur
width, height = res[0] # In case of trouble, set manually the resolution with: width, height = 1650, 1050
print "Screen resolution :", width, "x", height
screen = pygame.display.set_mode([width, height])
pygame.display.toggle_fullscreen()
pygame.mouse.set_visible = False

# Picamera object / objet Picamera
camera = picamera.PiCamera()
#camera.resolution = (1280, 720)
camera.framerate = float(24)

# Define functions / fonctions
def take_pic():
    global pics_taken
    pics_taken += 1
    camera.capture('image_' + str(pics_taken) + '.jpg')

def take_video() :
    global vid_taken
    vid_taken += 1
    camera.start_recording('video_' + str(vid_taken) + '.h264')
    #Recording duration / duree enregistrement (15s)
    camera.wait_recording(15)
    camera.stop_recording()

def quit_app():
    camera.close()
    pygame.quit()
    print "You've taken", pics_taken, " pictures ", vid_taken, " videos. Don't forget to back them up (or they'll be overwritten next time)"
    sys.exit(0)

#Start camera preview / Demarre affichage en direct
camera.start_preview()

while(True):
  pygame.display.update()
  for event in pygame.event.get():
      if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_ESCAPE:
          quit_app()
        elif event.key == pygame.K_SPACE:
          take_pic()
        elif event.key == pygame.K_RETURN:
          take_video()
        elif event.key == pygame.K_TAB:
           camera.start_preview()

Subscribe to the weekly newsletter

No spam and no other use will be made of your email. You can unsubscribe anytime.

DIY Projects