Nerdegutta's logo

nerdegutta.no

Python: Face recognition and compare with images from a folder

14.12.23

Programming

This program compares the image from the WEB camera, with images from a folder.

# Import the neccessary libraries
import cv2
import face_recognition
import os

# Load images from the folder
known_images_path = "/home/jens/Bilder/face_rec/"
known_images = []

# Load known faces
for filename in os.listdir(known_images_path):
    img_path = os.path.join(known_images_path, filename)
    image = face_recognition.load_image_file(img_path)
    encoding = face_recognition.face_encodings(image)[0]
    known_images.append(encoding)

# Initialize the webcam
video_capture = cv2.VideoCapture(0)

while True:
    # Capture each frame from the webcam
    ret, frame = video_capture.read()

    # Find all face locations and encodings in the current frame
    face_locations = face_recognition.face_locations(frame)
    face_encodings = face_recognition.face_encodings(frame, face_locations)

    # Loop through each face in the current frame
    for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
        # Compare the current face with known faces
        matches = face_recognition.compare_faces(known_images, face_encoding)
        name = "Unknown"

        # If a match is found, use the name of the known face
        if True in matches:
            first_match_index = matches.index(True)
            name = os.listdir(known_images_path)[first_match_index].split(".")[0]
            print ("Match")

        # Draw a rectangle around the face and display the name
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
        font = cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame, name, (left + 6, bottom - 6), font, 0.5, (255, 255, 255), 1)

    # Display the resulting frame
    cv2.imshow('Video', frame)

    # Break the loop if 'q' key isq pressed
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the webcam and close all windows
video_capture.release()
cv2.destroyAllWindows()