Skip to content

Instantly share code, notes, and snippets.

@GideonPARANOID
Created November 22, 2014 18:28
Show Gist options
  • Save GideonPARANOID/9fe7e016e73a2c9e7025 to your computer and use it in GitHub Desktop.
Save GideonPARANOID/9fe7e016e73a2c9e7025 to your computer and use it in GitHub Desktop.
Viola-Jones face detection from webcam
#!/usr/bin/env python
import cv2
import sys
import video
if __name__ == '__main__':
try : fn = sys.argv[1]
except : fn = 0
cv2.namedWindow('cam')
cap = video.create_capture(fn)
flag, img = cap.read()
cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
fourcc = cv2.cv.CV_FOURCC(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))
total = 0.0
frames = 0.0
while True:
flag, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
n = 0
# image, reject level, level weights
for (x, y, w, h) in cascade.detectMultiScale(gray):
cv2.rectangle(img, (x, y) ,(x + w,y + h), (255, 0, 0), 2)
roi_color = img[y : y + h, x : x + w]
n += 1
cv2.putText(img, "%d" % n, (0, 470), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, 16)
out.write(img)
cv2.imshow('cam', img)
total += n
frames += 1
ch = cv2.waitKey(5)
if ch == 27:
break
cap.release()
out.release()
cv2.destroyAllWindows()
print "frames : %d\nfaces : %d\naverage : %f" % (frames, total, (total / frames))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment