フレームを直接操作した場合
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import cv2 ESC_KEY = 27 cap = cv2.VideoCapture(0) w = cap.get(cv2.CAP_PROP_FRAME_WIDTH) h = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) fps = cap.get(cv2.CAP_PROP_FPS) avg = None while True: ret, frame = cap.read() if frame is None: break gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if avg is None: avg = gray.copy().astype("float") continue cv2.accumulateWeighted(gray, avg, 0.5) frameDelta = cv2.absdiff(gray, cv2.convertScaleAbs(avg)) ret, thresh = cv2.threshold(frameDelta, 20, 255, cv2.THRESH_BINARY) cv2.imshow('frame', frame) cv2.imshow('thresh', thresh) keyboard = cv2.waitKey(30) if keyboard == ESC_KEY: break cap.release() cv2.destroyAllWindows() |
Numpy で書いてみた
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import numpy as np import cv2 THRESHOLD = 100000 cap = cv2.VideoCapture(0) w = cap.get(cv2.CAP_PROP_FRAME_WIDTH) h = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) fps = cap.get(cv2.CAP_PROP_FPS) if fps == 0: fps=30.0 old64 = np.zeros((int(h),int(w)), dtype=np.int64) while True: ret, frame = cap.read() if frame is None: break gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray64 = np.array(gray, np.int64) if old64 is not None: diff64 = abs(gray64-old64) old64 = gray64 cv2.imshow('npframe', gray) res64=np.where(diff64 > 50, 255, 0) motion = sum(sum(res64)) if motion > THRESHOLD: print("MOTION DETECTED:",str(motion)) cv2.imshow('Frame', np.array(res64, np.uint8)) keyboard = cv2.waitKey(30) if keyboard == ESC_KEY: break cap.release() out.release() cv2.destroyAllWindows() |
BackgroundSubtractorMOG でもっと簡単に書ける
背景差分
bgsegm は、Background-Foreground Segmentation Methods の略
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import numpy as np import cv2 cap = cv2.VideoCapture('out.mp4') fgbg = cv2.bgsegm.createBackgroundSubtractorMOG() while(1): ret, frame = cap.read() fgmask = fgbg.apply(frame) cv2.imshow('frame',frame) cv2.imshow('fgmask',fgmask) k = cv2.waitKey(30) if k == 27: break cap.release() cv2.destroyAllWindows() |