OpenCV has really good and stable bindings for Python. This makes things easier to develop image processing programs without leaving the comfort of Python or going to alternate solutions like SimpleCV. For past week, I have been tinkering with OpenCV in quite detail and it has been super fun. In this post, I will show how to run a simple face detection script using Python.
The prerequisites are OpenCV (I use 2.4.9 with Python binding) and Python 2.7+.
Latest OpenCV can be easily installed using:
We will run the face detection using Haar feature based cascade classifiers.
OpenCV installation already comes with pre-trained classifiers for many facial
keypoints such as eye, nose, mouth and the face itself. We will use the file
haarcascade_frontalface_alt.xml which is available in OpenCV
installation directory in
/usr/local/Cellar/opencv/2.4.9/share/OpenCV/haarcascades. The path
might vary based on the installation, but it should be inside the directory
where OpenCV was installed. The XML file needs to be copied into the local
directory where the Python face detection script will be present.
Following is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Let us find out how this works out for us. I have used the following image on the left, cast from The Avengers movie. On the right is the face detected image.
Well, that was easy!