Face detection using Python and OpenCV

keshav
2 min readDec 19, 2020

A modern implementation of the Classifier Cascade face detection algorithm is provided in the OpenCV library. This is a C++ computer vision library that provides a python interface. The benefit of this implementation is that it provides pre-trained face detection models, and provides an interface to train a model on your own dataset.

OpenCV can be installed by the package management system

sudo pip install opencv-python

OpenCV provides the CascadeClassifier class that can be used to create a cascade classifier for face detection. The constructor can take a filename as an argument that specifies the XML file for a pre-trained model.

We can load the pre-trained model for frontal face detection


classifier = CascadeClassifier('haarcascade_frontalface_default.xml')

Once loaded, the model can be used to perform face detection on a photograph by calling the detectMultiScale() function.

boundary_boxes= classifier.detectMultiScale(pixels)
for box in boundary_boxes:
print(box)

The photo can be loaded using OpenCV via the imread() function.

pixels = imread('img1.jpg')

Complete example

Running the example first loads the photograph, then loads and configures the cascade classifier; faces are detected and each bounding box is printed.

Drawing the rectangle can be achieved by drawing a rectangle for each box directly over the pixels of the loaded image using the rectangle() function that takes two points. Then plotting the photograph.

Running the function the output looks like

Thank you!.

Also, check out the post on Instagram.

--

--