nerdegutta.no
Python: Simple face recognition
14.12.23
Programming
import face_recognitionimport cv2# Load an image with facesimage_path = '/home/jens/Bilder/face_rec/1.jpg'image = face_recognition.load_image_file(image_path)# Find face locations and face encodingsface_locations = face_recognition.face_locations(image)face_encodings = face_recognition.face_encodings(image, face_locations)# Open a video capturevideo_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 cameraret, frame = video_capture.read()# Find face locations and face encodings in the current framecurrent_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 facesfor 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 faceif 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 nametop, right, bottom, left = face_locationcv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)font = cv2.FONT_HERSHEY_DUPLEXcv2.putText(frame, name, (left + 6, bottom - 6), font, 0.5, (255, 255, 255), 1)# Display the resulting framecv2.imshow('Video', frame)# Break the loop when the 'q' key is pressedif cv2.waitKey(1) & 0xFF == ord('q'):break# Release the video capture objectvideo_capture.release()# Close all windowscv2.destroyAllWindows()