Capture images from Raspberry Pi camera module using picamera

0
5143
Raspberry Pi & Camera
Raspberry Pi & Camera

Working with Raspberry Pi camera module is pretty fun, and it gets even more interesting if we can do it via some code. Let’s use Python camera interface to interact with camera module.

First make sure that camera is setup correctly.

For programming, sure we need to install the supported package, picamera


$ sudo apt-get install python-picamera

With this package, we can get a camera object to control the camera module


import picamera
camera = picamera.PiCamera()

To generate a camera snapshot, we use capture() method,


camera.capture('snapshot.jpg')

Execute the script, it will capture an image from camera for sure. We can request camera to show a preview before capturing,


camera.start_preview()

Well, if there is a start then it should have a stop going along,


camera.stop_preview()

So the script will be,


# app.py
import picamera
camera = picamera.PiCamera()
camera.start_preview()
camera.capture('snapshot.jpg')
camera.stop_preview()

While running the script, you might notice that the preview is too short, and we want to increase the preview duration, which can be done via time.sleep().


# app.py
import picamera
camera = picamera.PiCamera()
camera.start_preview()
sleep(5) # hang for preview for 5 seconds
camera.capture('snapshot.jpg')
camera.stop_preview()

We can update the camera preview resolution by specifying the resolution values before starting the preview,


camera.resolution = (800, 600)
camera.start_preview()

The snapshot image can also be resized while capturing


camera.capture('snapshot.jpg', resize=(640, 480))

Finally, we will have a script that start preview at 800×600 resolution for 5 seconds and capture a 640×480 resolution image from camera module.


# app.py
import picamera
camera = picamera.PiCamera()
camera.resolution = (800, 600)
camera.start_preview()
sleep(5)
camera.capture('snapshot.jpg', resize=(640, 480))
camera.stop_preview()

To learn more about the picamera API, read the documetation.