DEV Community

Cover image for Face Detection in just 15 lines of Code! (ft. Python and OpenCV)
Saharsh Laud
Saharsh Laud

Posted on

Face Detection in just 15 lines of Code! (ft. Python and OpenCV)

Whether you have recently started exploring OpenCV or have been working with it for quite some time, in either scenario, you must have come across the term Face Detection. As machines continue to become more and more intelligent, their capability to mimic human behavior also seems to increase and Face Detection is one of these advancements in AI.

So today, we shall take a quick look at what Facial Detection is, why it is useful and how you can practically implement Face Detection on your system in just 15 lines of code!

Let's get started by understanding Facial Detection.

What is Facial Detection? (Explain Like I'm five)

Facial Detection Example

Facial detection is a computer technology based on Artificial Intelligence that is capable of identifying and locating the presence of human faces in digital photos and videos. In short, the capability of a machine to detect human faces in an image or a video.

Due to the significant advancements in AI, it is now possible to detect faces in an image or video, regardless of lighting conditions, skin color, head pose, and background.

Face Detection is the starting point of several face-related applications such as facial recognition or facial verification. Today, the cameras in most digital devices utilize face detection technology to detect where the faces are and adjust the focus accordingly.

So how does Face Detection work?

Glad you asked! The backbone of any face detection application is an algorithm (a simple step-by-step guide for the machine to follow) that assists in determining whether the images are positive images (images with faces) or negative images (images without faces).

In order to do this accurately, the algorithms are trained on massive datasets containing hundreds of thousands of face images and non-face images. This trained machine learning algorithm can then detect whether there is a face in the image or not and also place a bounding box if a face is detected.

Face Detection Process

Face Detection using OpenCV

Computer Vision is one of the most exciting and challenging tasks in Artificial Intelligence, and there are several packages available to solve problems related to computer vision. OpenCV is by far the most popular open-source library for tackling computer-vision-based problems.

The OpenCV library has more than 18 million downloads and an active user community of 47000 members. It has 2500 optimized algorithms, including a comprehensive set of classic and state-of-the-art computer vision and machine learning algorithms, making it one of the most important libraries in the machine learning field.

Face detection in an image is a simple 3-step process:

Step 1: Install and import the open-cv module:

pip install opencv-python
Enter fullscreen mode Exit fullscreen mode
import cv2
import matplotlib.pyplot as plt # for plotting the image
Enter fullscreen mode Exit fullscreen mode

Step 2: Download the Haar-cascade Classifier XML file and load it into the system:

Haar-cascade Classifier is a machine learning algorithm where we train a cascade function with tons of images. There are different types of cascade classifiers according to different target objects and here we will use a classifier that considers the human face to recognize it as the target object.

You can find the the trained classifier XML file for face detection here

# Load the cascade
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
Enter fullscreen mode Exit fullscreen mode

Step 3: Use the detectMultiScale() function in the Haar-cascade classifier to detect faces and draw bounding boxes around them:

# Read the input image
img = cv2.imread('test.png')

# Detect faces
faces = face_cascade.detectMultiScale(image = img, scaleFactor = 1.1, minNeighbors = 5)

# Draw bounding box around the faces
for (x, y, w, h) in faces:
      cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)

# Showing number of faces detected in the image
print(len(faces),"faces detected!")

# Plotting the image with face detected
finalimg = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
plt.figure(figsize=(12,12))
plt.imshow(finalimg) 
plt.axis("off")
plt.show()
Enter fullscreen mode Exit fullscreen mode

detectMultiScale() Parameters :

  • image: Matrix of the type CV_8U containing an image where objects are detected.
  • scaleFactor: Parameter specifying how much the image size is reduced at each image scale.
  • minNeighbors: Parameter specifying how many neighbors each candidate rectangle should have to retain it.

You might need to tweak these values to get the best results.

Face Detected Image

Voila! Just like that, you can implement one of the most unique applications of Computer Vision.

You can find a detailed code template for the entire Face Detection implementation here.

Note: This tutorial is only meant for face detection in an image file and not a live camera feed or videos.

Before you go....

Aren't you feeling great? You just learned how to implement one of the most fascinating applications of Artificial Intelligence and Machine Learning. Don't stop here! Go ahead and explore other amazing features that OpenCV offers and keep sharing your knowledge.

Hope you enjoyed my blog. Thanks for reading!

Feel free to comment, share and reach out to me on Dev.to , Twitter , or LinkedIn .

Top comments (0)