python实现人脸识别代码
时间: 2023-09-02 18:15:56 浏览: 356
实现人脸识别需要用到一些库,比如 OpenCV 和 face_recognition。以下是一个简单的 Python 人脸识别代码示例:
```python
import cv2
import face_recognition
# 加载图片和标记
known_image = face_recognition.load_image_file("known.jpg")
known_encoding = face_recognition.face_encodings(known_image)[0]
# 读取视频流
video_capture = cv2.VideoCapture(0)
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 face_encoding in face_encodings:
match = face_recognition.compare_faces([known_encoding], face_encoding)
if match[0]:
# 标记人脸
top, right, bottom, left = face_locations[0]
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
# 显示视频帧
cv2.imshow('Video', frame)
# 按下q键退出循环
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放资源
video_capture.release()
cv2.destroyAllWindows()
```
这个代码会从摄像头中读取视频流,并在视频中检测已知图片中的人脸。如果检测到匹配的人脸,就会在视频中标记出来。注意,这个代码只是一个简单的示例,实际应用中需要更复杂的算法和模型来提高识别准确率。
阅读全文