Skip to content

Instantly share code, notes, and snippets.

@mmitou
Created February 18, 2016 02:56
Show Gist options
  • Select an option

  • Save mmitou/9ab70513b1a6c7644db1 to your computer and use it in GitHub Desktop.

Select an option

Save mmitou/9ab70513b1a6c7644db1 to your computer and use it in GitHub Desktop.
# -*- coding:utf-8 -*-
from __future__ import print_function, division, unicode_literals
import cv2
import time
def mask_ratio(mask):
w, h = mask.shape
p = cv2.countNonZero(mask) / (w * h)
return int(p * 100)
def make_substractor(cap, history):
substractor = cv2.createBackgroundSubtractorMOG2(history=history)
# learn background
init_counter = 0
while(init_counter <= history):
hasSucceeded, frame = cap.read()
if not hasSucceeded:
continue
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
substractor.apply(gray)
init_counter = init_counter + 1
return substractor
def make_gaussian_substractor(cap, history):
substractor = cv2.createBackgroundSubtractorMOG2(history=history)
# learn background
init_counter = 0
while(init_counter <= history):
hasSucceeded, frame = cap.read()
if not hasSucceeded:
continue
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
img = cv2.GaussianBlur(gray, (5, 5), 0)
substractor.apply(img)
init_counter = init_counter + 1
return substractor
def main(ratio_threshold=10, counter_threshold=10, history=500):
cap = cv2.VideoCapture(0)
# gray_substractor = make_substractor(cap, history)
gaussian_substractor = make_gaussian_substractor(cap, history)
ratios = []
has_detected = False
while(True):
hasSucceeded, frame = cap.read()
if not hasSucceeded:
continue
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
# mask = gray_substractor.apply(gray)
mask_blur = gaussian_substractor.apply(blur)
# gray_ratio = mask_ratio(mask)
blur_ratio = mask_ratio(mask_blur)
cv2.imshow('frame', frame)
cv2.imshow('blur', blur)
# cv2.imshow('mask', mask)
cv2.imshow('mask_blur', mask_blur)
print('{x},{y}'.format(x=blur_ratio, y=10 if has_detected else 0))
if cv2.waitKey(1) & 0xFF == ord(' '):
break
if blur_ratio > ratio_threshold:
ratios.append(blur_ratio)
if len(ratios) > counter_threshold and all([x == ratios[-1] for x in ratios[-counter_threshold:]]):
has_detected = True
else:
ratios = []
has_detected = False
# time.sleep(1)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment