This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python.
You also need to download the Family dataset on the book's website. (http://ipython-books.github.io).
import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib as mpl %matplotlib inline
img = cv2.imread('data/pic3.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier('data/haarcascade_frontalface_default.xml')
detectMultiScalemethod of the classifier detects the objects on a grayscale image, and returns a list of rectangles around these objects.
for x, y, w, h in face_cascade.detectMultiScale(gray, 1.3): cv2.rectangle(gray, (x,y), (x+w,y+h), (255,0,0), 2) plt.figure(figsize=(6,4)); plt.imshow(gray, cmap=plt.cm.gray); plt.axis('off');
We see that, although all detected objects are indeed faces, one face out of four is not detected. This is probably due to the fact that this face is not perfectly facing the camera, whereas the faces in the training set were. This shows that the efficacy of this method is limited by the quality and generality of the training set.