用python写一个人脸识别的代码
时间: 2023-12-17 10:48:31 浏览: 64
python实现人脸识别代码
5星 · 资源好评率100%
当然可以!要实现人脸识别,你需要用到OpenCV和face_recognition这两个库,具体代码可参考以下示例:
```
import cv2
import face_recognition
video_capture = cv2.VideoCapture(0)
# 加载参考照片
obama_image = face_recognition.load_image_file("obama.jpg")
# 获取参考照片特征
obama_face_encoding = face_recognition.face_encodings(obama_image)[0]
known_face_encodings = [
obama_face_encoding
]
known_face_names = [
"Barack Obama"
]
while True:
# 读取视频帧
ret, frame = video_capture.read()
# 转换为RGB格式
rgb_frame = frame[:, :, ::-1]
# 识别人脸
face_locations = face_recognition.face_locations(rgb_frame)
face_encodings = face_recognition.face_encodings(rgb_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"
# 如果匹配,则显示姓名
if True in matches:
first_match_index = matches.index(True)
name = known_face_names[first_match_index]
# 在画面中标出人脸位置及姓名
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.putText(frame, name, (left + 6, bottom - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)
# 显示结果
cv2.imshow("Video", frame)
# 按q键退出程序
if cv2.waitKey(1) & 0xFF == ord("q"):
break
# 释放资源
video_capture.release()
cv2.destroyAllWindows()
```
希望对你有所帮助!
阅读全文