Third party cookies may be stored when visiting this site. Please see the cookie information.

PenguinTutor YouTube Channel

Raspberry Pi Picamera2 - New software library for pi camera

This is an introduction to the PiCamera2 library for the Raspberry Pi OS, controlling the Raspberry Pi cameras. This was a recent addition to the Raspberry Pi OS. This has replaced the proprietary drivers used in the earlier version of the Raspberry Pi OS, with one that is open source and uses the libcamera open source camera library.

In the video below I provide an introduction to the new camera using a Raspberry Pi 3 and an official HQ (high quality) camera module. In my case the camera is attached to a microscope lens, but this will work the same whether you are using it with any of the different lenses that are available. It will also be the same for other Raspberry Pi cameras, although it’s the high quality camera that needs special consideration due to the memory usage.

Please Subscribe and click the bell icon to be notified of my future videos.

Useful commands

Test the camera using:
libcamera-hello

Download the example software from the Raspberry Pi GitHub repository:
git clone https://github.com/raspberrypi/picamera2.git

Increase the CMA (Contiguous Memory Allocator) memory
edit /boot/config.txt
update dtoverlay=vc4-kms-v3d
dtoverlay=vc4-kms-v3d,cma-320

Source code for microscope capture program

The following code is based on the picamera2 example libraries, also using gpiozero to capture button presses.



#!/usr/bin/python3

import sys

import select

import time

from gpiozero import Button



from picamera2 import Picamera2, Preview



# Button is connected to GPIO 4

button = Button(4)



request = "none"



# Loop to keep taking photos

while True:

    picam2 = Picamera2()

    picam2.start_preview(Preview.QTGL)



    preview_config = picam2.create_preview_configuration()

    picam2.configure(preview_config)



    picam2.start()



    # Loop to wait on request

    while True:

        if button.is_pressed:

            request = "capture"

            break

        

        key_input = select.select([sys.stdin], [], [], 1)[0]

        if key_input:

            key_value = sys.stdin.readline().rstrip()

            # If q then quit

            if (key_value == "q"):

                request = "quit"

                break

            # Any other key capture

            else:

                request = "capture"

                break



    if request == "quit":

        break



    metadata = picam2.capture_file("captures/microscope-"+time.strftime("%Y%m%d-%H%M%S")+".jpg")

    print(metadata)

    picam2.close()



picam2.close()

Related projects

Also see:

Future projects

For the latest updates please:
Subscribe to the PenguinTutor YouTube Channel
and
Follow @penguintutor on Twitter

Previous Pi-power home automation
Pi-power home automation
Next PGZ Animation library
PGZ Animation library