Skip to content

Instantly share code, notes, and snippets.

@senyoltw
Created October 15, 2018 03:31
Show Gist options
  • Save senyoltw/e6a2eea1f2c667c6ff9a4b20ab01d8d4 to your computer and use it in GitHub Desktop.
Save senyoltw/e6a2eea1f2c667c6ff9a4b20ab01d8d4 to your computer and use it in GitHub Desktop.
フレーム差分により動体検知をする
import cv2
import sys
import os
import subprocess
def detect_motion(cap):
avg = None
while(cap.isOpened()):
ret, frame = cap.read()
frame = cv2.flip(frame, -1) #カメラ上下左右反転
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))
thresh = cv2.threshold(frameDelta, 3, 255, cv2.THRESH_BINARY)[1]
image, contours, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
max_area = 0
target = contours[0]
for cnt in contours:
#輪郭の面積を求めてくれるcontourArea
area = cv2.contourArea(cnt)
if max_area < area and area < 10000 and area > 1000:
max_area = area;
target = cnt
if max_area > 1000:
break
else:
cap.release()
#sys.exit(1)
def main():
while(True):
cap = cv2.VideoCapture(0)
cap.set(3,640) # set Width
cap.set(4,480) # set Height
detect_motion(cap)
print('hit! motion!')
cap.release()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment