Face detection using OpenCV

Face detection using OpenCV

5 mins read714 Views Comment
Updated on Dec 28, 2022 10:56 IST

Face detection means Identifying the face in image or video. This article covers applications and importance of Face detection.Along with that it also covers the implementation of face detection using python.


Face detection is a computer vision technique that helps us identify people and other objects in images. It is a key component in many applications, including surveillance, face mapping, and Galilean image navigation. OpenCV is an open-source computer vision library developed by the Intel Corporation for real-time image acquisition and processing. It supports both 2D and 3D computer vision and contains advanced face detection algorithms. 

OpenCV is an open-source technology that can identify objects based on their faces. The library contains support for face detection and tracking, skin detection, eye detection, and gaze detection. These features are implemented via the following classifiers: features, gaze, eyes, skin, and skin gaze. Using all of these capabilities at once can provide very intuitive facial analytics for your apps. When we see any image, we can easily detect faces, but if we want our computer to detect faces in an image. We have to implement face detection. In this article, we will detect faces in an image by using python code.

Table of contents

What is face detection?


Facial recognition is a method of finding human faces in a given image. These classifiers are basically models trained on many images, with and without faces. These models typically start by scanning the human eye, which is one of her easiest features to detect, and then try to detect other features such as the iris, eyebrows, mouth, and nose. Once a face region is detected, additional tests are typically performed to ensure that the region is a face. The number of images you use to train your model affects accuracy. This is because training a model with 1000 images is less accurate than training it with 100,000 images.

Face recognition is the first step towards many face-related applications, such as facial and facial recognition. But facial recognition has very useful applications. One of the most successful applications of facial recognition is taking pictures.

For example, when you click on a friend’s photo, a camera with a built-in facial recognition algorithm recognizes the position of the face and adjusts the focus accordingly.

Note: Face detection can be such a problem when human faces may have slight differences, but it’s safe to say that all human faces have unique features. 

OpenCV python: Beginner’s guide
OpenCV python: Beginner’s guide
OpenCV is a huge open-source for computer vision, machine learning, and image processing that currently plays a big role in real-time operations. This article will tell you about OpenCV. Then...read more
10 Computer Vision Projects Ideas For Beginners
10 Computer Vision Projects Ideas For Beginners
Computer vision is a branch of artificial intelligence that enables and trains computers to understand the visual world. This article brings for you exciting computer vision projects.This article will tell...read more
Top 10 Machine Learning Projects for Beginners
Top 10 Machine Learning Projects for Beginners
If you are an aspiring Data Scientist, working on machine learning projects is the best and most effective way to get a hands-on experience that will help you break into...read more

Must Read: Top 10 Powerful Python Libraries for Data Science

Must Check: Top Python Online Courses and Certifications

Must Read: What is Python

Why is Facial detection required?

A good face detector is important because face detection is necessary as a starting point for many face-related tasks such as Facial feature detection, gender classification, face tracking, and of course, facial recognition.

Face detection application

Face detection is used in many areas, such as security, marketing, healthcare, entertainment, law enforcement, surveillance, photography, gaming, and videoconferencing. Let’s look at some concrete use cases.

1. Face detection

The first task is to detect faces in an image (photo) or video stream. Now that we know the exact coordinates/location of the face let’s extract this face for further processing.

2. Feature extraction

Now that we know we’ve cropped the face from the image let’s extract certain features from it. We will now see how facial embeddings are used to extract these facial features. As you know, a neural network takes an image of a person’s face as input and outputs a vector representing the main features of the face. In machine learning, we call this vector a face embedding because we don’t call it anything other than an embedding. So how does this help us recognize the faces of different people?

As you train your neural network, it learns to output similar vectors for faces that look alike. The vectors associated with faces are similar or very close to each other in vector space. So far, we’ve learned how this network works. We pass all the images in our data to this pre-trained network, get the embeddings for each, and save those embeddings to a file for the next step.

3. Face comparison

The data stored in the file has face embeddings for each face. The next step is to detect new images that are not in the data. So the first step is to compute the face embedding of the image using the same network we used before and compare that embedding with the rest of the embeddings. Recognize a face if the generated embedding is close or similar to another embedding.

Also read: Deep Learning and Neural Networks Online Courses & Certifications

Also read: NLP and Text Mining Online Courses & Certifications

Also read: Artificial Intelligence

Face detection using OpenCV python

OpenCV has many pre-trained classifiers for faces, eyes, smiles, etc. Today we will use a face classifier. You can also try other classifiers.

You will need to download the pre-trained classifier XML file (haarcascade_frontalface_default.xml) available on google. So you don’t have to collect any data to train on it. So first download it. Please keep it at your place of work.

1. Importing libraries

import cv2 as cv # used for computer vision tasks
from google.colab.patches import cv2_imshow
Copy code

2. Loading the cascade and reading the image

# Load the cascade
face_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
# Read the input image
img = cv.imread('image1.jpg')
Copy code

Use Haar Cascade for face. A Haar cascade is basically a classifier used to recognize objects trained from a source.

3. Converting into a grayscale image

# Convert into grayscale
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
Copy code

4. Detecting faces

# Detect faces
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
Copy code

To detect faces, use the detectMultiScale function. It takes three arguments: input image, scaleFactor, and minNeighbors. scaleFactor specifies how much to reduce the image size for each scaling. minNeighbors specifies how many neighbors each candidate rectangle must have to hold it. 

5. Draw rectangles around the faces

# Draw rectangle around the faces

# Draw rectangle around the faces
for (x, y, w, h) in faces:
cv.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 4)
Copy code

rectangle() is used to draw the rectangle box around face.

6. Showing the results

# Display the output
Copy code

cv2.waitKey() is a keyboard-bound function. Its argument is the time in milliseconds. This function waits for keyboard events for the specified number of milliseconds. Pressing any button during this time will continue the program. The second condition concerns pressing the escape key on the keyboard. So if 1-millisecond passes and the escape key is pressed, the loop is broken, and the program stops. 


OpenCV is a fantastic library for manipulating images and videos. So please make use of it and have fun manipulating your images. It contributes to many applications as well. If this article contributed to your knowledge, then do like it and share it with your friends, as knowledge increases on sharing.



About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio