OpenCV: Face Detection using Haar Cascades

Alex Egg,

I had the privilege to take Dr. Freund last year for a grad class – he is one of the principle innovators behind boosting. I remember he was going over one particularly interesting case study of Adaboost: the Haar faces. It was a tree-based model that used a convolutional trick to learn the face features of a human.

Incidentally I found a cool openCV script w/ a pre-trained Haar model that runs on your laptop webcam:

import cv2
import numpy as np

c = cv2.VideoCapture(0)

# get the xmls from https://github.com/Itseez/opencv/tree/master/data/haarcascades
face_cascade = cv2.CascadeClassifier('/usr/local/Cellar/opencv/2.4.13.2/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml')
eye_cascade = cv2.CascadeClassifier('/usr/local/Cellar/opencv/2.4.13.2/share/OpenCV/haarcascades/haarcascade_eye.xml')

while(1):
    _,img = c.read()

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(gray)
    for (x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = img[y:y+h, x:x+w]
        eyes = eye_cascade.detectMultiScale(roi_gray)
        for (ex,ey,ew,eh) in eyes:
            cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)

    cv2.imshow('img',img)
    if cv2.waitKey(5)==27:
        break
cv2.destroyAllWindows()

https://s3.amazonaws.com/eggie5_production/static/haaralex.png

Permalink: opencv-face-fetection-using-haar-cascades

Tags:

Last edited by Alex Egg, 2017-02-18 22:43:41
View Revision History