Although OpenCV provides a very efficient implementation of AdaBoost, it is hidden under the Haar cascade classifier. Haar cascade classifiers are a very popular tool for face detection, which we can illustrate through the example of the Lena image:
In [1]: img_bgr = cv2.imread('data/lena.jpg', cv2.IMREAD_COLOR)
... img_gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)
After loading the image in both color and grayscale, we load a pretrained Haar cascade:
In [2]: import cv2
... filename = 'data/haarcascade_frontalface_default.xml'
... face_cascade = cv2.CascadeClassifier(filename)
The classifier will then detect faces present in the image using the following function call:
In [3]: faces = face_cascade.detectMultiScale(img_gray, 1.1, 5)
Note that the algorithm operates only on grayscale images. That's why we saved two pictures of Lena, one to which we can apply the classifier (img_gray), and one on which we can draw the resulting bounding box (img_bgr):
In [4]: color = (255, 0, 0)
... thickness = 2
... for (x, y, w, h) in faces:
... cv2.rectangle(img_bgr, (x, y), (x + w, y + h),
... color, thickness)
Then, we can plot the image using the following code:
In [5]: import matplotlib.pyplot as plt
... %matplotlib inline
... plt.imshow(cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB));
This results in the following output, with the location of the face indicated by a blue bounding box:
Obviously, this screenshot contains only a single face. However, the preceding code will work even on images where multiple faces could be detected. Try it out!