DEV Community

Cover image for Get Started with Face Detection with Python
Ochwada Linda
Ochwada Linda

Posted on

Get Started with Face Detection with Python

NOTE: Used a pre-trained model
Face detection in photos can be performed using the classical feature-based cascade classifier using the OpenCV library (cv2).

Used packages

import cv2
import time
import os
Enter fullscreen mode Exit fullscreen mode

OpenCV provides the CascadeClassifier class that creates a cascade classifier for face detection. The constructor can take a filename as an argument that specifies the XML file for a pre-trained model.

Download a pre-trained model (file here) for frontal face detection from the OpenCV GitHub project - to be placed in your working directory.

Setup the image directory

# function to get images from folder 
def get_images(dir_name):
    list_images = os.listdir(dir_name)
    all_images =list()

    for entry in list_images:
        full_path =os.path.join(dir_name, entry)
        if os.path.isdir(full_path):
            all_images.all_images + get_images(full_path)
        else: all_images.append(full_path)
    return all_images
Enter fullscreen mode Exit fullscreen mode

Load the model that will perform face detection on photographs by calling the detectMultiScale() function.

# Face Detection

def  main():
    dir_name = 'images' # directory for images
    list_images = get_images(dir_name)

    for i in range(20): #20 images
        image_path = list_images[i]


        # load the pre-trained model
        case_path = "haarcascade_frontalface_default.xml" # define the model used for recognition detection
        faceCascade= cv2.CascadeClassifier(case_path)
        gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # make the picture to gray from color

        # face detection 
        faces = faceCascade.detectMultiScale(gray,
                                            scaleFactor = 1.1,
                                            minSize = (30, 30))

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

        #Load the detected faces
        cv2.imshow("Face Found", image)

if __name__ == '__main__':
Enter fullscreen mode Exit fullscreen mode

Running the model loads the images and configures the cascade classifier; faces are detected, and each bounding box gets printed.

The model only works for faces directly at the camera (in front).

Face detection 1

Face detection 2

Top comments (0)