Caleb Madrigal

Programming, Hacking, Math, and Art

 

Facial Detection with OpenCV and Python

I was able to get some basic facial detection working in OpenCV with Python. Here's what it looks like:

Facial recognition with OpenCV

And here is the 34-line python script to draw boxes around all detected faces in live video:

import cv

HAAR_CASCADE_PATH = "/opt/local/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)

        # Only run the Detection algorithm every 5 frames to improve performance
        if i%5==0:
            faces ...

Intro to OpenCV with Python

I have started my journey into the world of OpenCV using Python on my Mac. These are my first steps with it.

Installing OpenCV for Python on the Mac

# Install numpy as a prerequisite
sudo port install numpy

# Install OpenCV with the Python API
sudo port install opencv +python27

(The port command is part of Macports)

Capturing an images from a webcam

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#!/usr/bin/env python2.7
import cv

cv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE)

camera_index = 0
capture = cv.CaptureFromCAM(camera_index)

frame = cv.QueryFrame(capture)
cv.SaveImage("pic.jpg", frame)

(I tested this with the iSight camera on my Macbook Pro)

Displaying live video

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#!/usr/bin/env python2 ...