Face Detection in Python using OpenCV with Haar Cascade Classifiers

Object detection is a computer technology related to computer vision and image processing that deals with detecting instances of semantic objects of a certain class ( such as human faces, cars, fruits, etc. ) in digital images and videos.

Haar feature-based cascade classifiers is a machine learning based approach where a cascade function is trained from a lot of positive and negative images. It is then used to detect objects in other images.

The nice thing about haar feature-based cascade classifiers is that you can make a classifier of any object you want, OpenCV already provided some classifier parameters to you, so you don’t have to collect any data to train on it.

To get started, install the requirements:

pip3 install opencv-python

Alright, create a new Python file and follow along, let’s first import OpenCV:

import cv2

You gonna need a sample image to test with, make sure it has clear front faces in it, I will use this stock image that contains two nice lovely kids:

# loading the test image
image = cv2.imread("kids.jpg")

The function imread() loads an image from the specified file and returns it as a numpy N-dimensional array.

Before we detect faces in the image, we will first need to convert the image to grayscale, that is because the function we gonna use to detect faces expects a grayscale image:

# converting to grayscale
image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

The function cvtColor() converts an input image from one color space to another, we specified cv2.COLOR_BGR2GRAY code, which means converting from BGR ( Blue Green Red ) to grayscale.

Since this tutorial is about detecting human faces, go ahead and download the haar cascade for human face detection in this list. More precisely, “haarcascade_frontalface_default.xml”. Let’s put it in a folder called “cascades” (or whatever) and then load it:

# initialize the face recognizer (default face haar cascade)
face_cascade = cv2.CascadeClassifier("cascades/haarcascade_fontalface_default.xml")

Let’s now detect all the faces in the image:

# detect all the faces in the image
faces = face_cascade.detectMultiScale(image_gray)
# print the number of faces detected
print(f"{len(faces)} faces detected in the image.")

detectMultiScale() function takes an image as parameter and detects objects of different sizes as a list of rectangles, let’s draw these rectangles in the image:

# for every face, draw a blue rectangle
for x, y, width, height in faces:
    cv2.rectangle(image, (x, y), (x + width, y + height), color=(255, 0, 0), thickness=2)

Finally, let’s save the new image:

# save the image with rectangles
cv2.imwrite("kids_detected.jpg", image)

Here is my resulting image:

Face Detection in Python using OpenCV with Haar Cascade Classifiers

Pretty cool, right? Feel free to use other object classifiers, other images and even more interesting, use your webcam ! Here is the code for that:

import cv2

# create a new cam object
cap = cv2.VideoCapture(0)

# initialize the face recognizer (default face haar cascade)
face_cascade = cv2.CascadeClassifier("cascades/haarcascade_fontalface_default.xml")

while True:
    # read the image from the cam
    _, image = cap.read()
    # converting to grayscale
    image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # detect all the faces in the image
    faces = face_cascade.detectMultiScale(image_gray, 1.3, 5)

    # for every face, draw a blue rectangle
    for x, y, width, height in faces:
        cv2.rectangle(image, (x, y), (x + width, y + height), color=(255, 0, 0), thickness=2)

    cv2.imshow("image", image)

    if cv2.waitKey(1) == ord("q"):
        break

cap.release()
cv2.destroyAllWindows()

Once you execute that ( if you have a webcam of course ), it will open up your webcam and start drawing blue rectangles around all front faces in the image. The code isn’t that challenging, all I changed is, instead of reading the image from a file, I created a VideoCapture object that reads from it every time in a while loop, once you press the q button, the main loop will end.

Check the official OpenCV documentation for Face Detection.

Alright, this is it for this tutorial, you can get all tutorial materials ( including the testing image, the haar cascade, and the full code ) here.

Happy Coding ♥

#python #machine-learning #opencv #deep-learning #data-science

Face Detection in Python using OpenCV with Haar Cascade Classifiers
84.95 GEEK