Nerdegutta's logo

nerdegutta.no

Python: face recognition by comparing images in two folders.

03.03.24

Programming

To perform face recognition using Python, you can use a popular library called OpenCV along with a pre-trained deep learning model for face detection. In this example, I'll use the Dlib library for face recognition, which requires the `dlib` and `face_recognition` packages.

First, install the packages:

pip install dlib
pip install face_recognition

 

Now, you can create a Python script for face recognition from images in two folders. This script assumes that each folder contains images of individuals you want to recognize.

 

import os
import face_recognition

def load_images_from_folder(folder):
    images = []
    for filename in os.listdir(folder):
        if filename.endswith(('.jpg', '.jpeg', '.png')):
            img_path = os.path.join(folder, filename)
            images.append(face_recognition.load_image_file(img_path))
    return images

def recognize_faces(known_folder, unknown_folder):
    known_faces = []
    unknown_faces = []

    # Load known faces
    known_faces = load_images_from_folder(known_folder)
    known_face_encodings = [face_recognition.face_encodings(img)[0] for img in known_faces]

    # Load unknown faces
    unknown_faces = load_images_from_folder(unknown_folder)

    for unknown_face in unknown_faces:
        unknown_face_encoding = face_recognition.face_encodings(unknown_face)

        if not unknown_face_encoding:
            print("No face found in image.")
            continue

        # Compare the unknown face with known faces
        results = face_recognition.compare_faces(known_face_encodings, unknown_face_encoding[0])

        name = "Unknown"
        if True in results:
            first_match_index = results.index(True)
            name = os.listdir(known_folder)[first_match_index].split('.')[0]

        print(f"Found {name} in the image.")

if __name__ == "__main__":
    # Specify the paths to the folders containing known and unknown faces
    known_folder_path = "path/to/known/folder"
    unknown_folder_path = "path/to/unknown/folder"

    recognize_faces(known_folder_path, unknown_folder_path)

 

Replace `"path/to/known/folder"` and `"path/to/unknown/folder"` with the actual paths to your known and unknown face image folders. The script will load the known faces, encode them, and then compare the unknown faces with the known ones to perform face recognition. The recognized names or "Unknown" will be printed for each face found in the unknown folder.