Face detection in OpenCV

Face detection in OpenCV is locating visual patterns and features present in an image to determine the presence and location of human faces.

OpenCV provides a robust framework for face detection, offering pre-trained models and algorithms that can accurately detect faces in real-time.

Procedure

Following are the key steps involved in face detection with OpenCV. We are using the haar cascade classifier, which already has a pre-trained model for face recognition. You can get their pre-trained face annotation from the haar cascade's repository.

  1. Loading the model: We can feed any pre-trained (or our trained) model to the OpenCV library cv2. How we load our model will depend upon the model we use. In the case of the haar cascade model, we can use CascadeClassifier() function from the cv2 library.

  2. Preprocessing the image: It is a common practice to perform preprocessing to enhance image quality and improve detection accuracy. Typically, for detection purposes, the images are converted to grayscale using the cvtColor() method of cv2 library.

  3. Detecting faces: Now, we apply the model over our preprocessed images. In this step, OpenCV scans the image at multiple scales, applying the model to each region of interest. You can return a list of rectangles representing the detected faces' bounding boxes.

  4. Displaying the results: Finally, we can display the resulting image with the drawn rectangles using the function cv2.imshow(). Additionally, we can save the modified image using the cv2.imwrite() function.

Example code

The following code detects the face from an image and draws a green box around it.

import cv2

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

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

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

# Perform face detection
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))

# Draw rectangles around the detected faces
for (x, y, w, h) in faces:
    cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)

# Display the result
cv2.imshow('Face Detection', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Python code to detect face in an image

Code explanation

  • Line 1: Imports cv2 library.

  • Line 4: Feeds the pre-trained dataset (stored in haarcascade_frontalface_default.xml) to the CascadeClassifier() method of the haar detection algorithm. The final product is then saved in the face_cascade variable.

  • Line 7: Loads test image using imread() method of the cv2 library and stores it in the original_image variable.

  • Line 10: Grayscales the test image under preprocessing using cvtColor() method of the cv2 library.

  • Line 13: Uses the detectMultiScale() method to recognize human faces of different sizes, where gray is the image over which the human face will be detected. scaleFactor specifies the rate at which the image size is reduced during the process. minNeighbors specifies the minimum number of neighbors a detected region needs to be considered a human face. minSize sets the minimum size of the detected face.

  • Lines 16–17: face is a list containing the faces detected in the given test image. The loop will continue running until rectangular boxes surround each detected face.

  • Line 20: Displays the image on the screen with the label "Face Detection". You can click on the "Run" button to display the output.

  • Line 21: Waits for the user to press any key if they want to quit the window.

  • Line 22: Closes all the opened windows.

Conclusion

By utilizing OpenCV's face detection capabilities, we can automate face detection tasks in various applications such as video surveillance, augmented reality, etc.

It is important to note that our method in this shot utilizes a pre-trained model with annotations stored in the .xml file. We can also use deep learning models to train our datasets.

Note: Learn how to:

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved