python基于opencv的人脸识别代码
时间: 2023-10-16 19:08:30 浏览: 135
基于Python+OpenCV人脸识别设计与实现源码.zip
5星 · 资源好评率100%
以下是基于OpenCV的人脸识别的Python代码示例:
```python
import cv2
# 加载Haar级联分类器
faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
# 加载训练数据集
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read("trainer.yml")
# 加载标签
labels = {"person_name": 1}
with open("labels.pickle", 'rb') as f:
labels = pickle.load(f)
labels = {v:k for k,v in labels.items()}
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取视频帧
ret, frame = cap.read()
# 转换为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces = faceCascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=5)
# 对每个检测到的人脸进行识别
for (x, y, w, h) in faces:
roi_gray = gray[y:y+h, x:x+w]
id_, confidence = recognizer.predict(roi_gray)
if confidence >= 45 and confidence <= 85:
font = cv2.FONT_HERSHEY_SIMPLEX
name = labels[id_]
cv2.putText(frame, name, (x,y), font, 1, (255,255,255), 2, cv2.LINE_AA)
# 画出人脸检测框
color = (255, 0, 0)
stroke = 2
end_cord_x = x + w
end_cord_y = y + h
cv2.rectangle(frame, (x, y), (end_cord_x, end_cord_y), color, stroke)
# 显示视频帧
cv2.imshow('frame',frame)
if cv2.waitKey(20) & 0xFF == ord('q'):
break
# 释放摄像头资源
cap.release()
cv2.destroyAllWindows()
```
这个代码示例中,我们首先加载了Haar级联分类器和训练数据集,然后打开摄像头,并对每个检测到的人脸进行识别。如果置信度(confidence)在45到85之间,就将人脸识别结果绘制在视频帧上。最后,我们通过cv2.imshow()函数显示视频帧,并使用cv2.waitKey()函数等待用户按下“q”键退出循环。
阅读全文