Monday, July 28, 2014

DIY Motion Detection Using a Raspberry Pi Camera

I received a Raspberry Pi camera for my birthday because my wife is awesome and she asked me what I wanted. I figured it would be fun to make a security camera that will take video when changes are detected. I was told that I should check out OpenCV, and they (Shihgian) were right! The do-it-yourself version that I mention below "worked", but definitely checkout sites like PyImageSearch for great tutorials on how to use OpenCV with your Raspberry Pi.

There is existing software for doing motion detection, but the whole reason I wanted a raspberry pi and camera was to have fun writing code.

The approach I decided to take is to:

1. Take two photos in quick succession (using raspistill).
2. Write a Java app that will
2.1. Make a mosaic out of the photos, and use the average RGB value for each tile.
2.2. Compare each tile from the two mosaic images, and create a new image to show the changes.  The areas where no significant difference were found the code will write out a 0 RGB value (black).  Areas where a significant change is found will use the second mosaic image's RGB value for the tile being compared.
2.3. Check the output image to see if areas that have changed are large enough to seem interesting.  If any of the changed areas are large enough, then send a message to a message queue to request that a video be recorded.
3. If a message is read from the queue requesting that a video to be created, then:
3.1. Record a video.
3.2. Upload the video to a storage area.
3.3. Write a message to a message queue with the location of the video file.

I have the steps 1 through 2.2 done, and I'm pretty happy with the results so far. Here is an example of a couple of images that were taken and compared, and the output of the comparison was created.

Image 1 - notice the white truck towards the center of the image:

Image 2 - the white truck has moved:

Notable Differences:

My next project should be to incorporate something like this (joke):
Autonomous Backyard Defender