这是最后一步进行人脸识别操作
# -*- coding: utf-8 -*
import cv2
import os
# 加载训练数据集文件
recogizer = cv2.face.LBPHFaceRecognizer_create()
recogizer.read('train/trainer.yml') # 获取脸部特征数据文件
names = []
warningtime = 0
def face_detect_demo(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 转换为灰度图像
face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # 加载分类器
face = face_detector.detectMultiScale(gray, 1.3, 5, cv2.CASCADE_SCALE_IMAGE, (100, 100), (300, 300))
# 进行识别,把整张人脸部分框起来
for x, y, w, h in face:
cv2.rectangle(img, (x, y), (x + w, y + h), color=(0, 0, 255), thickness=2) # 矩形
ids, confidence = recogizer.predict(gray[y:y + h, x:x + w]) # 进行预测、评分
if confidence > 80:
global warningtime
warningtime += 1
if warningtime > 100: # 警报达到一定次数,说明不是这个人
warningtime = 0
cv2.putText(img, 'unkonw', (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
else:
cv2.putText(img, str(names[ids - 1]), (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
# 把姓名打到人脸的框图上
cv2.imshow('result', img)
# print('bug:',ids)
#找名字
def name():
path = './picture'
imagepaths = [os.path.join(path, f) for f in os.listdir(path)]
for imagePath in imagepaths:
name1 = str(os.path.split(imagePath)[1].split('.', 2)[1])
names.append(name1)
cap = cv2.VideoCapture(0)
name()
while True:
flag, frame = cap.read() # 获得摄像头读取到的数据(flag为返回值,frame为视频中的每一帧)
if not flag:
break
face_detect_demo(frame)
if ord(' ') == cv2.waitKey(10): # 按空格,退出
break
cv2.destroyAllWindows()
cap.release()
# print(names)