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
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
f.read(4)
chunk.append(f.read(n))
f.read(4)
f.close()
return zlib.decompress(''.join(chunk))
Lastly, the real code follows.
last1 = '\x00' * 930
while running:
im = camera.take_photo('RGB', (160,120))
im.rectangle([(10,10),(40,40)], 0xff0000)
im.rectangle([(120,10),(150,40)], 0xff0000)
box = Image.new((30,30), 'L')
box.blit(im, (10,10,40,40))
data = getdata(box, 8)
pixdiff = 0
for i in range(len(data)):
if abs(ord(data[i])-ord(last1[i])) > 15:
pixdiff += 1
if pixdiff > 90:
im.rectangle([(10,10),(40,40)], fill=0xff0000)
break
last1 = data
c.blit(im, (0,0), (8,12))
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.