Example code for using the Pi camera with Python.

Example code for using the Pi camera with Python.

The following is example Python code for the Raspberry Pi camera. The camera module supports over 30fps at 1080p and has many features that can easily be set in a Python program. This code which will take the raw camera data and allow you to save frames as jpeg images or work with the raw image data right in Python. To use this you will need a Raspberry Pi with standard Pi Camera attached. The code was tested with Python 3.5 on the “stretch” version of Raspbian.

First we import all the necessary Python modules. The cv2 module is super useful for show raw image data in a window. PIL is an image processing library and is very useful for modifying, manipulating and saving image data.


#!/usr/bin/python3.5

from picamera.array import PiRGBArray

from picamera import PiCamera

import time

import cv2

import sys

from PIL import Image, ImageDraw

Next we create and configure our camera object. This is where you can set the resolution, ISO, stability and other settings. We sleep for 1 second to allow time for the camera to setup.


camera = PiCamera()

camera.resolution = (640, 480)

camera.framerate = 30

camera.iso = 800

camera.vflip = True

rawCapture = PiRGBArray(camera, size=(640, 480))

time.sleep(1)

Next is the big loop. This loops will continue until you hit the “q” key or kill the software. The loop is continuously grabbing frames. The frames are raw and are convert to a numpy array called image. This image is then convert to a PIL object where we can save the image. OpenCV also has a save function but I thought it would be helpful to show conversion to PIL in case you want to run more tools on the image.

The frame is save to a jpeg file and it’s also displayed in an OpenCV window.


for frame in camera.capture_continuous(rawCapture, format="rgb", use_video_port=True):

    image = frame.array

    pil_image = Image.fromarray(image)

    pil_image.save("/tmp/test.jpg", "JPEG", quality=87, optimize=True, progressive=True)

    cv2.imshow("Frame",image)

    key = cv2.waitKey(1) & 0xFF

    rawCapture.truncate(0)

    if key == ord("q"):

        break

Leave a Reply