Python人脸识别界面设计代码
时间: 2024-10-17 10:12:49 浏览: 37
Python的人脸识别通常涉及到深度学习库如OpenCV、dlib或face_recognition等。下面是一个简单的例子,展示了如何使用OpenCV创建一个基本的人脸识别界面:
```python
import cv2
import face_recognition
# 加载人脸数据库
known_faces = []
known_names = []
# 添加已知的人脸数据
# 这里只是一个示例,你需要替换为你自己的图片路径
for i in range(5):
image_path = f"known_face_{i}.jpg"
img = face_recognition.load_image_file(image_path)
known_faces.append(img)
known_names.append("Person " + str(i+1))
# 加载摄像头视频流
cap = cv2.VideoCapture(0)
while True:
# 读取摄像头帧
ret, frame = cap.read()
# 转换为灰度图像以便于处理
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces_locations = face_recognition.face_locations(gray)
for (top, right, bottom, left) in faces_locations:
# 提取人脸区域
face_image = frame[top:bottom, left:right]
# 将人脸转为RGB格式
face_image_rgb = cv2.cvtColor(face_image, cv2.COLOR_BGR2RGB)
# 对提取到的人脸进行编码
face_encoding = face_recognition.face_encodings(face_image_rgb)[0]
# 在匹配之前将编码归一化
face_encoding_normalized = face_encoding / np.linalg.norm(face_encoding)
# 使用欧氏距离查找最相似的脸
results = face_recognition.compare_faces(known_faces, face_encoding_normalized)
name = "Unknown"
if True in results:
# 如果找到了匹配,获取相应的名字
index = results.index(True)
name = known_names[index]
# 绘制矩形框并显示姓名
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.putText(frame, name, (left + 6, top - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 255), 2)
# 显示结果
cv2.imshow('Face Recognition', frame)
# 按 'q' 键退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 清理资源
cap.release()
cv2.destroyAllWindows()
```
这个程序会在摄像头中实时检测人脸,并尝试将其与已知的人脸进行比较。当找到匹配时,会显示相应的名字。
阅读全文