UsingACameraAsASensor

From XPUB & Lens-Based wiki


Code attached below.

Using motion to read from the camera

The free software motion is very multi-purpose. One use is simply as a motion detector using a webcam, and to pipe it's motion data into a PyGame program for a live visualisation.

Installing

sudo apt-get install motion


Using configutation files, it's possible to customize what the software does (take pictures, print out motion data). See the .conf files in the attached code.

Visualising the data with PyGame

A first program to simply display a box representing the area of the screen motion detects motion in.

#!/usr/bin/python

import sys
import pygame
from pygame.locals import *
from pygame.time import Clock
from time import sleep
import thread

def reader ():
    while True:
    	line = sys.stdin.readline()
    	if (not line): break
    	line = line.strip()
    	if line.startswith("motion"):
    		# print "read motion data:", line
    		(x, y, w, h, numpixels) = [int(x) for x in line.split()[1:]]
    		evt = pygame.event.Event(USEREVENT, {"x" : x, "y": y, "w":w, "h":h})
    		pygame.event.post(evt)

(mx, my, mw, mh) = (10, 10, 50, 50)
pygame.init()
# screen = pygame.display.set_mode((640, 480), FULLSCREEN, 32)
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("motionbox")
clock = Clock()

thread.start_new_thread(reader, ())

while True:
	for event in pygame.event.get():
		if event.type==QUIT or \
		(event.type == KEYDOWN and event.key == K_ESCAPE):
			sys.exit()
		elif event.type == USEREVENT:
			# print event
			mx = event.x
			my = event.y
			mw = event.w
			mh = event.h
			# adjust mx, my (as they are a center point)
			mx -= mw/2
			my -= mh/2
	
	screen.fill((0, 0, 0))
	pygame.draw.rect(screen, (255, 255, 255), (mx, my, mw, mh), 1)
	pygame.display.update()
	clock.tick(30)


Putting the pieces together

motion -c motionbox.conf | python -u motionbox.py


Attachments