画像の適当な観測点を予め決めておいて、その場所の輝度が変化したら動いているであろうとする。
USBカメラからの画像の取得にはPythonのライブラリのVideoCaptureを使っています。
# -*- coding: utf-8 -*-
# motion1.py 2011.2.1
import time
import random
import VideoCapture
class Motion1:
def __init__(self):
self.sample = [] # 観測点
self.old_val = []
def ginfo(self, buf, xy):
b = ord(buf[xy])
g = ord(buf[xy + 1])
r = ord(buf[xy + 2])
return (r * 299 + g * 587 + b * 114) / 1000 # 輝度の計算
def check(self, buf, noize = 30, limit = 12):
max_sample = 200 # 観測数
if not self.sample:
self.sample = random.sample(range(0, len(buf)-1, 3), max_sample)
new_val = []
for xy in self.sample:
new_val.append(self.ginfo(buf, xy))
t = 0
if self.old_val:
for i in range(max_sample):
if abs(self.old_val[i] - new_val[i]) > noize:
t += 1
self.old_val = new_val
return (t * 100 / max_sample) > limit
if __name__ == '__main__':
devnum = 1 # ManyCam
cam = VideoCapture.Device(devnum)
motion = Motion1()
while True:
(buf, x, y) = cam.getBuffer()
if motion.check(buf):
print VideoCapture.now(), u"動作を検出しました"
time.sleep(0.5)
0 件のコメント:
コメントを投稿