Instagram
youtube
Facebook
Twitter

Face Detection with OpenCV

  • ​In OpenCV, Face detection is the commonly used feature.

  • Face detection is very useful in biometrics, face recognition, and surveillance.

  • In simple words it is the process of locating faces in an image or video and extracting their features.

  • We can detect faces using a pre-trained cascade classifier that is based on the Haar-like features algorithm.

In this tutorial, we’ll learn about detecting faces in images using OpenCV.


What is cv2.CascadeClassifier in OpenCV?

  • cv2.CascadeClassifier is a library in OpenCV used for object detection.

  • It uses the Haar feature-based cascade classifier algorithm.

  • It is a powerful feature in computer vision and has many applications, including face detection, object recognition, and biometrics.

Input:

Code:

import cv2

facecascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
image = cv2.imread('cricket2.jpg')

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

faces = facecascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=2, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)

for (x, y, w, h) in faces:
    img = cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)

cv2.imshow('Detected Faces', image)
cv2.waitKey(0)
  • First we imported cv2 and used cv2.imread function to read the image.

  • The second line loads the pre-trained face detection classifier from the Haar Cascade file 'haarcascade_frontalface_default.xml' located in the OpenCV data folder.

  • Then, we used cv2.imread() function to read the image and cv2.cvtColor() to convert input image into grayscale.

  • facecascade.detectMultiScale() detects the faces in the grayscale image using the pre-trained face detection classifier loaded earlier. It takes parameters like - image path, scale factor(it specifies how much the image size is reduced at each image scale), minNeighbour, minSize(minimum size of detected objects), and flag.

  • Then, we used a for loop to draw a rectangle around the detected faces.

  • At last, we used imshow() function to display the final result.

Result:

For better results, you can use a different pre-trained face detection classifier according to the image.