Face Detection with Location and Encoding using OpenCV and face_recognition

  • Share this:

Code introduction


This function uses OpenCV and the face_recognition library to detect faces in an image and outputs the location and encoding of all detected faces.


Technology Stack : OpenCV, face_recognition, numpy

Code Type : Image processing

Code Difficulty : Intermediate


                
                    
def face_recognition(image_path, model_path):
    import cv2
    import numpy as np
    import face_recognition

    # Load the input image using OpenCV
    image = cv2.imread(image_path)
    # Convert the image from BGR to RGB, as face_recognition expects RGB
    rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    # Load a pre-trained face recognition model
    face_encodings = face_recognition.load_model(model_path)

    # Find all face locations in the image
    face_locations = face_recognition.face_locations(rgb_image)

    # Find all face encodings in the image
    face_encodings = face_recognition.face_encodings(rgb_image, face_locations)

    # Print the locations and encodings of all detected faces
    for (top, right, bottom, left), encoding in zip(face_locations, face_encodings):
        print(f"Face detected at location: {top}, {right}, {bottom}, {left}")
        print(f"Face encoding: {encoding}")

    # Optionally, draw rectangles around the faces
    for (top, right, bottom, left), encoding in zip(face_locations, face_encodings):
        cv2.rectangle(image, (left, top), (right, bottom), (0, 255, 0), 2)

    # Show the image with the face rectangles
    cv2.imshow('Image with Faces', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()