import face_recognition
import cv2
def recognize_faces(people):
# Create arrays to store known face encodings and corresponding names
known_face_encodings = []
known_face_names = []
# Load face encodings and names for each person
for person in people:
# Load the image of the person
known_image = face_recognition.load_image_file(person["image_path"])
# Compute the face encoding for the person
face_encoding = face_recognition.face_encodings(known_image)[0]
# Append the face encoding and name to the lists
known_face_encodings.append(face_encoding)
known_face_names.append(person["name"])
# Open 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 face 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 found in the frame
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
# Check if the face matches any known faces
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
name = "Unknown"
# If a match is found, use the name of the known person
if True in matches:
first_match_index = matches.index(True)
name = known_face_names[first_match_index]
# 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 when 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release the webcam and close all windows
video_capture.release()
cv2.destroyAllWindows()
# List of people and their image paths
people_list = [
{"name": "Person 1", "image_path": "path/to/known_person_1.jpg"},
{"name": "Person 2", "image_path": "path/to/known_person_2.jpg"},
# Add more people as needed...
]
# Call the function to start face recognition
recognize_faces(people_list)