python人脸识别代码大全
时间: 2024-08-15 09:01:51 浏览: 48
基于Python的人脸识别源码
5星 · 资源好评率100%
Python中的人脸识别通常涉及到计算机视觉领域,常用库有OpenCV、Dlib和face_recognition等。下面是一个简单的基于OpenCV的面部检测和识别示例:
```python
import cv2
import face_recognition
# 加载人脸编码数据集
known_faces = []
known_names = []
# 加载图片文件并提取人脸特征
for filename in ['image1.jpg', 'image2.jpg']: # 替换为实际图片路径
img = face_recognition.load_image_file(filename)
encoding = face_recognition.face_encodings(img)[0]
known_faces.append(encoding)
known_names.append("Person A") # 假设这是对应的人名
# 从摄像头捕获实时视频流
video_capture = cv2.VideoCapture(0)
while True:
ret, frame = video_capture.read()
# 将帧转换为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 检测人脸
face_locations = face_recognition.face_locations(gray)
face_encodings = face_recognition.face_encodings(gray, face_locations)
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
matches = face_recognition.compare_faces(known_faces, face_encoding)
name = "Unknown" if not any(matches) else known_names[matches.index(True)]
# 绘制边界框并显示名字
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.putText(frame, name, (left, bottom - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
# 显示结果
cv2.imshow('Face Recognition', frame)
# 按q键退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 关闭窗口并释放资源
video_capture.release()
cv2.destroyAllWindows()
```
阅读全文