The Raspberry Pi camera module can take picture when a motion occurs, so you can use it for surveillance purposes. Here is how this can be done:
1. First, make sure that your Raspberry Pi is running the latest firmware by running the command:
2. If not already installed, install the picamera python module by using this command:
sudo apt-get install python-picamera
3. You will also need to install Python Imaging Library (PIL) to add image processing capabilities to your Python interpreter. This can be done by running this command:
sudo apt-get install python-imaging-tk
4. Now that the software required is installed you’ll need to create your Python script, copy the following code into a file called “motion.py”, either by using Nano or a text editor in the GUI:
import io import os import picamera import time from datetime import datetime from PIL import Image camera = picamera.PiCamera() difference = 20 pixels = 100 width = 1280 height = 960 def compare(): camera.resolution = (100, 75) stream = io.BytesIO() camera.capture(stream, format = 'bmp') stream.seek(0) im = Image.open(stream) buffer = im.load() stream.close() return im, buffer def newimage(width, height): time = datetime.now() filename = 'motion-%04d%02d%02d-%02d%02d%02d.jpg' % (time.year, time.month,time.day, time.hour,time.minute, time.second) camera.resolution = (width, height) camera.capture(filename) print 'Captured %s' % filename image1, buffer1 = compare() timestamp = time.time() while (True): image2, buffer2 = compare() changedpixels = 0 for x in xrange(0, 100): for y in xrange(0, 75): pixdiff = abs(buffer1[x,y]- buffer2[x,y]) if pixdiff > difference: changedpixels += 1 if changedpixels > pixels: timestamp = time.time() newimage(width, height) image1 = image2 buffer1 = buffer2
Be sure to get the right indentation of the code.
5. The Python script will need to be executable, that’s done by the following command:
chmod +x motion.py
6. And finally, run the script with the command:
Your Raspberry Pi should now detect motion and take a picture every time it happens.