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.
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
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.