Skip to content

Instantly share code, notes, and snippets.

@rubdos
Created August 27, 2014 12:00
Show Gist options
  • Save rubdos/16f0c5b8037e918bfa3a to your computer and use it in GitHub Desktop.
Save rubdos/16f0c5b8037e918bfa3a to your computer and use it in GitHub Desktop.
Simple pythonscript to detect motion using a webcam
#!/bin/python
import numpy as np
import cv2
def diffImg(i0,i1,i2):
d1 = cv2.absdiff(i2, i1)
d2 = cv2.absdiff(i1, i0)
return cv2.bitwise_and(d1, d2)
cap = cv2.VideoCapture(0)
def getImg():
return cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2GRAY)
t1 = getImg()
t2 = getImg()
t3 = getImg()
motionlevel = 0
while True:
diff = diffImg(t1, t2, t3)
ret, diff = cv2.threshold(diff, 20, 255, cv2.THRESH_BINARY)
nz = cv2.countNonZero(diff) * 1.
height, width = diff.shape
if motionlevel < 40:
motionlevel+=nz/(height * width) * 2000
if motionlevel > 0:
motionlevel-=1;
if motionlevel > 3:
print "Motion:", motionlevel
cv2.imshow('frame', diff)
# count pixels
t1 = t2
t2 = t3
t3 = getImg()
if cv2.waitKey(1) & 0xFF == ord('q'):
break;
cap.release()
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment