Nerdegutta's logo

nerdegutta.no

Python: Simple face recognition

14.12.23

Programming

Before you can run this program, you'll need to install opencv-python and face_recognition.
import face_recognition
import cv2

# Load an image with faces
image_path = '/home/jens/Bilder/face_rec/1.jpg'
image = face_recognition.load_image_file(image_path)

# Find face locations and face encodings
face_locations = face_recognition.face_locations(image)
face_encodings = face_recognition.face_encodings(image, face_locations)

# Open a video capture
video_capture = cv2.VideoCapture(0)  # 0 represents the default camera (you can change it to a specific camera index)

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

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

    # Compare each face in the current frame with the known faces
    for face_location, face_encoding in zip(current_face_locations, current_face_encodings):
        matches = face_recognition.compare_faces(face_encodings, face_encoding)

        name = "Unknown"

        # If a match is found, use the name of the first matching known face
        if True in matches:
            first_match_index = matches.index(True)
            name = "Person " + str(first_match_index + 1)

        # Draw a rectangle around the face and display the name
        top, right, bottom, left = face_location
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 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 when the 'q' key is pressed
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the video capture object
video_capture.release()

# Close all windows
cv2.destroyAllWindows()