Skip to content

Instantly share code, notes, and snippets.

@tfeldmann
Last active December 11, 2015 15:49
Show Gist options
  • Save tfeldmann/4623850 to your computer and use it in GitHub Desktop.
Save tfeldmann/4623850 to your computer and use it in GitHub Desktop.
Face recognition in Python + OpenCV. I used Homebrew to install OpenCV, change your path to the haarcascade if needed.
import cv
HAAR_CASCADE_PATH = "/usr/local/Cellar/opencv/2.4.3/share/OpenCV/" \
"haarcascades/haarcascade_frontalface_default.xml"
CAMERA_INDEX = 0
def detect_faces(image):
faces = []
detected = cv.HaarDetectObjects(image, cascade, storage, 1.2, 2,
cv.CV_HAAR_DO_CANNY_PRUNING, (100,100))
if detected:
for (x,y,w,h),n in detected:
faces.append((x,y,w,h))
return faces
if __name__ == "__main__":
cv.NamedWindow("Video", cv.CV_WINDOW_AUTOSIZE)
capture = cv.CaptureFromCAM(CAMERA_INDEX)
storage = cv.CreateMemStorage()
cascade = cv.Load(HAAR_CASCADE_PATH)
faces = []
i = 0
while True:
image = cv.QueryFrame(capture)
# run the Detection algorithm every 5 frames to improve performance
if i % 5 == 0:
faces = detect_faces(image)
for (x,y,w,h) in faces:
cv.Rectangle(image, (x,y), (x+w,y+h), 255)
cv.ShowImage("w1", image)
i += 1
if cv.WaitKey(33) == 27:
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment