Over a million developers have joined DZone.

Motion Detection As Input

DZone's Guide to

Motion Detection As Input

Free Resource
Inspired from the PIL version here

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

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'
        f.read(4)   # CRC
    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

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.


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}