Coders Packet

Count number of faces from an image using OpenCV in Python language

By Nitish Kumar Singh

OpenCV is a popular computer vision library used for image and video processing tasks in various applications.

Face detection is also known as Facial detection. It is a computer vision technology that is used to find and identify human faces in digital images.

OpenCV is a real-time Computer Vision framework. It is used in many image processing and computer vision tasks.

To count the number of faces in an image using OpenCV in Python, you can utilize a pre-trained face detection model such as Haar cascades or a deep learning-based model like the OpenCV DNN module with a pre-trained face detection model like the Single Shot MultiBox Detector (SSD).

Here's an example using the Haar cascades method: 

import cv2

# Load the pre-trained face cascade
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

# Load the image
image = cv2.imread('your_image.jpg')

# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Detect faces in the image
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))

# Print the number of faces found
print(f"Number of faces detected: {len(faces)}")

 

Make sure to replace 'your_image.jpg' with the actual path to your image.

This code uses the detectMultiScale method of the face cascade classifier to detect faces in the image. The scaleFactor, minNeighbors, and minSize parameters can be adjusted to improve the accuracy of face detection based on your specific requirements.

Remember to have OpenCV installed (pip install opencv-python) and have the Haar cascade XML file available in the cv2.data.haarcascades directory.

If you prefer using a deep learning-based approach, you can use the OpenCV DNN module with a pre-trained face detection model like SSD. However, this method usually requires more computational resources and may not be as fast as Haar cascades.

 

The output of the project is:-

Download Complete Code

Comments

No comments yet

Download Packet

Reviews Report

Submitted by Nitish Kumar Singh (Nitish0909)

Download packets of source code on Coders Packet