OpenCV Tutorial

Image Processing

Feature Detection and Description

Drawing Functions

Video Processing

Applications and Projects

Count number of Faces using Python - OpenCV

Counting the number of faces in an image or video feed using Python and OpenCV can be accomplished using a pre-trained model called a Haar cascade classifier. OpenCV provides a Haar cascade classifier trained for detecting faces. Here's a step-by-step guide on how to do this:

Counting Faces in an Image using OpenCV

  1. Setup: If you haven't installed OpenCV yet, you can do so with pip:

    pip install opencv-python
    
  2. Load the Haar Cascade Classifier: OpenCV provides XML files containing the trained classifiers for different objects, including faces. You'll need to download the required XML for face detection.

    import cv2
    
    # Load the Haar cascade xml file
    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
    
  3. Read the Image:

    img = cv2.imread('path_to_image.jpg')
    
  4. Convert Image to Grayscale: Face detection often performs better on grayscale images.

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
  5. Detect Faces: Use the detectMultiScale method on the face_cascade object. This method returns the coordinates (x, y, width, height) of the detected faces.

    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
    
  6. Count and Display the Number of Detected Faces:

    print(f"Number of faces detected: {len(faces)}")
    
  7. Optionally, Draw Rectangles Around Detected Faces and Display the Image:

    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
    
    cv2.imshow('Faces Detected', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

When you run the code, the image will be displayed with rectangles around detected faces. The number of faces detected will also be printed in the console.

Notes:

  • scaleFactor: This compensates for some faces appearing larger or smaller than others due to being closer or farther away from the camera.
  • minNeighbors: Higher values result in fewer detections but higher quality. This parameter specifies how many neighbors each candidate rectangle should have to retain it.
  • minSize: Objects below this size are ignored.

The parameters for detectMultiScale might need adjustment depending on the input image's conditions. You can experiment with these values to achieve better results.

Also, note that Haar cascades are basic face detectors. For more robust and accurate face detection, you might want to explore deep learning-based approaches like the Multi-task Cascaded Convolutional Networks (MTCNN) or the Single Shot Multibox Detector (SSD) trained on face datasets.

  1. Counting faces in an image with OpenCV and Python:

    • OpenCV provides tools for face detection and counting. Using these features, you can analyze images and count the number of faces present.
    import cv2
    
    # Load the pre-trained face detector
    face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    
    # Read the image
    img = cv2.imread('image.jpg')
    
    # Convert to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    # Detect faces in the image
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)
    
    # Count the number of faces
    num_faces = len(faces)
    print(f'Number of faces: {num_faces}')
    
  2. Real-time face counting using webcam with OpenCV in Python:

    • Extending face counting to real-time scenarios involves capturing frames from a webcam and continuously applying face detection.
    import cv2
    
    # Load the pre-trained face detector
    face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    
    # Open a connection to the webcam (0 represents the default camera)
    cap = cv2.VideoCapture(0)
    
    while True:
        # Read a frame from the webcam
        ret, frame = cap.read()
    
        # Convert to grayscale
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
        # Detect faces in the frame
        faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)
    
        # Count the number of faces
        num_faces = len(faces)
    
        # Draw rectangles around the faces
        for (x, y, w, h) in faces:
            cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
    
        # Display the frame with face count
        cv2.imshow('Face Count', frame)
    
        # Break the loop if 'q' key is pressed
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    # Release the webcam and close the window
    cap.release()
    cv2.destroyAllWindows()