Face Detection With OS X and Python

I’ve been messing about with face detection for a while, and was surprised how easy it is to get basic detection working out-of-the-box with open-source libraries.

Today we’ll look at a simple way to get started with face detection on OSX using python.

We’re going to be using the OpenCV computer vision library, originally developed by Intel but subsequently released under the BSD license.

We’re going to use Homebrew to install everything. I’ve also had success installing OpenCV from MacPorts, as well as compiling it from source, but Homebrew seems to be the easiest and cleanest option these days.

1

> brew install opencv

This ran for about 5 minutes trying to install cmake, at which point I ran into an error :

There was a note in the homebrew error message pointing to this GitHub issue (I wish more package managers did this!) which had a few comments suggesting that updating Homebrew and reinstalling cmake would fix the problem :

12

> brew update
> brew install -v cmake

With this update done, installing opencv proceeded without problems :

1

> brew install opencv

You probably also need to update your PYTHON_PATH (thanks Duncan for pointing this out) :

Here’s the result of running the script on some random creative-commons photos tagged with ‘family’ on Flickr :

As you can see, the results are mixed. Full-frontal faces work best (because we’re using haarcascade_frontalface_default.xml to do the detection), as do medium-resolution images. I’ve found that processing very high-res images can result in a lot of false positives, since the image has so much detail.

The example above can also process real-time video from the camera on your Mac - instead of using a filename as an argument, input the camera number you wish to use (zero for most Macs) :

1

> python facedetect.py 0

If you feel like digging in a little deeper, there’s various other training data sets in /usr/local/Cellar/opencv/2.2/share/opencv/haarcascades/ for detecting other shapes (such as full bodies, eyes, noses etc), which open up some cool possibilities.