帮我用python写一个能检测照片里面的人脸信息并且可以根据摄像头检测到的人脸照片进行比对,如果是同一个人则保存照片,如果不是则继续等待,用代码写出来
时间: 2023-04-12 17:01:43 浏览: 99
好的,以下是Python代码,使用OpenCV和face_recognition库来检测人脸信息并进行比对:
```python
import cv2
import face_recognition
# 加载已知人脸的图像和标签
known_face_encodings = []
known_face_labels = []
img_path = "known_faces/"
for filename in os.listdir(img_path):
img = face_recognition.load_image_file(img_path + filename)
face_encoding = face_recognition.face_encodings(img)[0]
known_face_encodings.append(face_encoding)
known_face_labels.append(os.path.splitext(filename)[0])
# 初始化摄像头
video_capture = cv2.VideoCapture(0)
while True:
# 读取摄像头图像
ret, frame = video_capture.read()
# 缩小图像以加快人脸检测速度
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
# 转换颜色空间以便于人脸检测
rgb_small_frame = small_frame[:, :, ::-1]
# 在图像中查找人脸
face_locations = face_recognition.face_locations(rgb_small_frame)
face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
# 遍历每个检测到的人脸
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
# 比对人脸
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
name = "Unknown"
# 找到最佳匹配的人脸
face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
best_match_index = np.argmin(face_distances)
if matches[best_match_index]:
name = known_face_labels[best_match_index]
# 显示标签和边框
cv2.rectangle(frame, (left * 4, top * 4), (right * 4, bottom * 4), (0, 255, 0), 2)
cv2.putText(frame, name, (left * 4, bottom * 4 + 20), cv2.FONT_HERSHEY_DUPLEX, 0.5, (0, 255, 0), 1)
# 保存照片
cv2.imwrite(name + ".jpg", frame)
# 显示图像
cv2.imshow('Video', frame)
# 按下q键退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放摄像头和窗口
video_capture.release()
cv2.destroyAllWindows()
```
这个程序会读取已知人脸的图像和标签,然后使用摄像头检测人脸并进行比对,如果检测到已知人脸,则保存照片并显示标签和边框。如果检测到未知人脸,则不保存照片并显示"Unknown"标签。
阅读全文