Python OpenCV Facial Detection On OSX

By | March 6, 2014

Just a code snippet to demo Python script using OpenCV

import cv2, time

cap = cv2.VideoCapture(0)
time.sleep(1)
cascade = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")

def detect(image):
    #faces = cascade.detectMultiScale(img, 1.1, 2, cv2.cv.CV_HAAR_SCALE_IMAGE, (20,20), (200,200))
    faces = cascade.detectMultiScale(image)
    for _face in faces:
        cv2.rectangle(image, (_face[0], _face[1]), (_face[0]+_face[2], _face[1]+_face[3]), (255,255,255))

def repeat():
    ret, image = cap.read()
    detect(image)
    cv2.imshow("w1", image)
    cv2.waitKey(1)

while True:
    repeat()

Installation:

  1. pip install numpy (sometimes you might need to run as sudo)
  2. brew tap homebrew/science
  3. brew install opencv
  4. export PYTHONPATH=/usr/local/Cellar/opencv/2.4.7.1/lib/python2.7/site-packages/
  5. download the xml file https://warai.googlecode.com/files/haarcascade_frontalface_alt.xml and place it in the same folder.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.