Motion detection as input
http://gumuz.looze.net/wordpress/index.php/archives/2005/06/06/python-webcam-fun-motion-detection/
First with typical import and Canvas, exit setup
1 2 from appuifw import * 3 from graphics import Image 4 import camera, e32 5 #import miso # don't dim the light 6 7 app.body = c = Canvas() 8 9 running = 1 10 def quit(): 11 global running 12 running = 0 13 app.exit_key_handler=quit
Then the getdata function that reads pixel data
from image by saving/reading PNG.
1 2 def getdata(im, bpp=24): 3 import struct, zlib 4 im.save('D:\\pixels.png', bpp=bpp, compression='no') 5 f = open('D:\\pixels.png', 'rb') 6 f.seek(8 +8+13+4) 7 chunk = [] 8 while 1: 9 n = struct.unpack('>L', f.read(4))[0] 10 if n==0: break # 'IEND' chunk 11 f.read(4) # 'IDAT' 12 chunk.append(f.read(n)) 13 f.read(4) # CRC 14 f.close() 15 return zlib.decompress(''.join(chunk)) # '\x00' prefix each line
Lastly, the real code follows.
1 2 last1 = '\x00' * 930 # can be anything 3 while running: 4 im = camera.take_photo('RGB', (160,120)) 5 im.rectangle([(10,10),(40,40)], 0xff0000) # red outline 6 im.rectangle([(120,10),(150,40)], 0xff0000) # no code for this square 7 # check hot spot whether active 8 box = Image.new((30,30), 'L') # gray scale 9 box.blit(im, (10,10,40,40)) 10 data = getdata(box, 8) 11 # check difference for motion 12 pixdiff = 0 13 for i in range(len(data)): 14 if abs(ord(data[i])-ord(last1[i])) > 15: # pix threshold 15/256 15 pixdiff += 1 16 if pixdiff > 90: # img threshold 90/900 17 im.rectangle([(10,10),(40,40)], fill=0xff0000) # fill 18 break # motion detected 19 last1 = data 20 c.blit(im, (0,0), (8,12)) # show camera 21 #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.