Raspberry Pi Camera – Basic Motion Detection

Here’s a very basic method for implementing motion detection using a Raspberry Pi and camera.

This script works by taking an image and comparing it to the last significant image taken – if the images differ by 10% (this can be configured to suit your environment), the new image will be saved.

The idea here is that images are only stored when a significant change has been detected. The image comparison algorithm has been taken from Rosetta Code.

Pre-Requisites

First, we need to install some pre-requisite packages, including picamera – a Python library for interacting with the Pi Camera – and Pillow – a Python image management library.

The first set of packages can be installed via apt-get – run this command from your Raspberry Pi:

sudo apt-get install python-picamera python3-picamera python-pip python-dev python-setuptools libjpeg-dev

Once this has completed, install Pillow:

sudo pip install Pillow

Configuration

The script for capturing and processing images can be checked out from my GitHub repository.

After checking out the script, you will need to mark camera.py as executable:

chmod 755 /path/to/camera.py

There are a number of configuration options you can change in camera.cfg including:

  • width: The width of the images to be captured by the camera. Defaults to 640.
  • height: The height of the images to be captured by the camera. Defaults to 480.
  • path: The path that images will be saved to. Defaults to /opt/python-camera/images/.
  • threshold: This is the percentage difference a new image must be, compared to the last reference image, before it will be saved. Defaults to 10.

You can also set the logging level by changing the value of level in  logging.cfg. This defaults to DEBUG. Changing to a lower level, such as INFO, will prevent any messages from being logged.

Running the Script

The easiest method to run the script is to schedule it via cron, or your preferred scheduling tool.

To run the script every minute via cron, add the following line to your crontab:

* * * * * /path/to/camera.py

That should be it! Images will be saved under the images directory whenever a significant change is detected.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s