aidiary
4/17/2017 - 7:14 AM

背景差分

背景差分

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# 初期背景を設定するため画像取得
ret, frame = cap.read()
background = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

while True:
    ret, frame = cap.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    diff = cv2.absdiff(gray, background)

    cv2.imshow('Capture', frame)
    cv2.imshow('Difference', diff)

    key = cv2.waitKey(10)
    if key == ord('q'):
        break
    elif key == ord('b'):
        # bを押したらその時点でのキャプチャを背景とする
        ret, frame = cap.read()
        background = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

cap.release()
cv2.destroyAllWindows()