Motion detection code
From MoDe
The code is adapted from this snippet (http://bigbold.com/snippets/posts/show/636).
from appuifw import * from graphics import Image import camera, e32 from audio import *
- import miso # don't dim the light
app.body = c = Canvas()
running = 1 def quit():
global running running = 0
app.exit_key_handler=quit
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
last1 = '\x00' * 930 # can be anything box = Image.new((30,30), 'L') # gray scale
snd_file = [u'c:\\system\\apps\\python\\my\\note1.wav',
u'c:\\system\\apps\\python\\my\\note2.wav',
u'c:\\system\\apps\\python\\my\\note3.wav',
u'c:\\system\\apps\\python\\my\\note4.wav',
u'c:\\system\\apps\\python\\my\\note5.wav',
u'c:\\system\\apps\\python\\my\\note6.wav',
u'c:\\system\\apps\\python\\my\\note7.wav',
u'c:\\system\\apps\\python\\my\\note8.wav',
u'c:\\system\\apps\\python\\my\\note9.wav',
]
my_id = query(u'enter number between 0 and 8',u'number',0) try:
snd = Sound.open(snd_file[my_id])
except:
note(u'could not find '+snd_file[my_id],u'info') quit()
while running:
im = camera.take_photo('RGB12', (160,120))
im.rectangle( [ (65,45),(95,75) ], 0xff0000) # red outline
box.blit(im, (65,45,95,75))
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
snd.play()
im = camera.take_photo('RGB12', (160,120))
im.rectangle( [ (65,45),(95,75) ], 0xff0000) # red outline
box.blit(im, (65,45,95,75))
data = getdata(box, 8)
snd.stop()
break # motion detected
last1 = data
c.blit(im, (0,0), (8,12)) # show camera
#miso.reset_inactivity_time()
