Monday, August 20, 2012

Webcam based Motion Detection: Unix Style!

I've been playing around with the idea of using cheap USB webcams as motion sensors.  My PIR solution would detune in the presence of heat (a kitchen stove!).

I picked up a cheap Logitech webcam (C200 for $15 at Micro Center) and started writing some C code... but hey, wait -- that isn't the Unix way.

I downloaded a camera streamer (fswebcam) and graphicsmagic (a cleaner ImageMagick) and threw together this little script:


#!/bin/sh
THRESH=10 # Motion Threshold
SCALE=64x48
sudo umount /tmp/rd 2>/dev/null
sudo mkdir /tmp/rd 2>/dev/null && sudo chmod 777 /tmp/rd && \
sudo mount -t tmpfs -o size=100K tmpfs /tmp/rd/
trap "sudo umount /tmp/rd" EXIT 
fswebcam -q --greyscale --no-banner --scale $SCALE - >/tmp/rd/before.dat
while true; do
    sleep 0.5
    fswebcam -q --greyscale --no-banner --scale $SCALE - >/tmp/rd/after.dat 
    gm compare -metric RMSE /tmp/rd/before.dat /tmp/rd/after.dat null: \
|awk -v TH=$THRESH '/Total/{ if($3 > TH) printf("Motion!(%f)\n",$3)}'
    mv /tmp/rd/after.dat /tmp/rd/before.dat
done

Note: I am using a ramdisk to keep it fast (and embedded friendly).  The scale of the image is reduced to keep comparisons cheap and fast.

I now need to see if I can port this to my Beaglebone!

No comments:

Post a Comment