import cv2 import os import pickle import facerecognition def…
- User
import cv2 import os import pickle import face_recognition
def recognize_faces_from_webcam(db_path):
Load face embeddings from the database
db_dir = sorted(os.listdir(db_path)) embeddings_db = [] for file_name in db_dir: path = os.path.join(db_path, file_name) with open(path, ‘rb’) as file: embeddings = pickle.load(file) embeddings_db.append(embeddings)
Open the webcam
video_capture = cv2.VideoCapture(0)
while True:
Capture frame-by-frame
ret, frame = video_capture.read()
Convert the frame from BGR color (used by OpenCV) to RGB color (used by face_recognition)
rgb_frame = frame[:, :, ::-1]
Find all face locations and their encodings in the current frame
face_locations = face_recognition.face_locations(rgb_frame) face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
for face_encoding in face_encodings:
Compare the face encoding with the faces in the database
matches = face_recognition.compare_faces(embeddings_db, face_encoding)
Check if there is a match
if any(matches):
Get the index of the matched face in the database
matched_face_index = matches.index(True)
Get the name of the person from the database file name
matched_face_name = db_dir[matched_face_index][:-7]
Print the name of the matched person
print(“Matched person:”, matched_face_name)
Display the resulting image
cv2.imshow(‘Video’, frame)
Press ‘q’ to quit
if cv2.waitKey(1) & 0xFF == ord(‘q’): break
Release the video capture and close the window
video_capture.release() cv2.destroyAllWindows()
Replace ‘db_path’ with the path to your database directory
db_path = ‘D:\Borodin\opencv\code\known_people’
recognize_faces_from_webcam(db_path)
При запуске возникает ошибка Traceback (most recent call last): File “D:\Borodin\opencv\venv\main.py”, line 59, in recognize_faces_from_webcam(db_path) File “D:\Borodin\opencv\venv\main.py”, line 13, in recognize_faces_from_webcam embeddings = pickle.load(file) _pickle.UnpicklingError: invalid load key, ‘\xff’.
исправь программу чтобы все работало
- Assistant
Для исправления проблемы, вам необходимо изменить кодирование и декодирование при сохранении и загрузке файлов с помощью pickle. Вместо использования стандартных методов загрузки и сохранения, используйте для сохранения данных в файл, а затем для загрузки данных из файла. Вот исправленный код:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.