DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Motion Detection As Input
Inspired from the PIL version here
http://gumuz.looze.net/wordpress/index.php/archives/2005/06/06/python-webcam-fun-motion-detection/
First with typical import and Canvas, exit setup
from appuifw import *
from graphics import Image
import camera, e32
#import miso # don't dim the light
app.body = c = Canvas()
running = 1
def quit():
global running
running = 0
app.exit_key_handler=quit
Then the getdata function that reads pixel data from image by saving/reading PNG.
def getdata(im, bpp=24):
import struct, zlib
im.save('D:\\pixels.png', bpp=bpp, compression='no')
f = open('D:\\pixels.png', 'rb')
f.seek(8 +8+13+4)
chunk = []
while 1:
n = struct.unpack('>L', f.read(4))[0]
if n==0: break # 'IEND' chunk
f.read(4) # 'IDAT'
chunk.append(f.read(n))
f.read(4) # CRC
f.close()
return zlib.decompress(''.join(chunk)) # '\x00' prefix each line
Lastly, the real code follows.
last1 = '\x00' * 930 # can be anything
while running:
im = camera.take_photo('RGB', (160,120))
im.rectangle([(10,10),(40,40)], 0xff0000) # red outline
im.rectangle([(120,10),(150,40)], 0xff0000) # no code for this square
# check hot spot whether active
box = Image.new((30,30), 'L') # gray scale
box.blit(im, (10,10,40,40))
data = getdata(box, 8)
# check difference for motion
pixdiff = 0
for i in range(len(data)):
if abs(ord(data[i])-ord(last1[i])) > 15: # pix threshold 15/256
pixdiff += 1
if pixdiff > 90: # img threshold 90/900
im.rectangle([(10,10),(40,40)], fill=0xff0000) # fill
break # motion detected
last1 = data
c.blit(im, (0,0), (8,12)) # show camera
#miso.reset_inactivity_time()
When measured, it takes around 1.1 sec for each loop.
Compared this with 0.9 sec without image processing,
out code is quite efficient.




