系列文章目录
人脸采集
数据训练
代码思路
一、pandas是什么?
示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。
二、使用步骤
1.引入代码库
import cv2
- 获取人脸识别对象
# 获取人脸识别对象
recognizer = cv2.face.LBPHFaceRecognizer_create()
- 读取在上一博客程序中获取的训练数据
recognizer.read('yujinlong232.yml')
- 加载分类器
face_detector = cv2.CascadeClassifier(r'C:\Users\HONOR\AppData\Local\Programs\Python\Python37\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')
- 设置字体
font = cv2.FONT_HERSHEY_SIMPLEX
- 设置变量
统计 id数量
idnum = 0
- 姓名列表
names = ['jhy', 'yjl']
- 开启摄像头
cappatu = cv2.VideoCapture(0)
while True:ret, frame = cappatu.read()
- 将图像转换为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_detector.detectMultiScale(gray)
- 画框
for x, y, w, h in faces:cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), thickness=2)cv2.circle(frame, (x + w // 2, y + h // 2), radius=w // 2, thickness=2, color=(0, 0, 255))
- 对人脸进行识别并输出置信度:
id, confidence = recognizer.predict(gray[y:y + h, x:x + w])if confidence < 80:name = names[id]else:name = "unknown"cv2.putText(frame, str(name), (x + 5, y - 5), font, 1, (230, 250, 100), 1)cv2.putText(frame, str(confidence), (x + 5, y + h - 5), font, 1, (255, 0, 0), 1)print('标签id:', id, '置信评分:', confidence)cv2.imshow("c", frame)
完整带代码示
import cv2# 获取人脸识别对象
recognizer = cv2.face.LBPHFaceRecognizer_create()
# 读取训练数据
recognizer.read('yujinlong232.yml')
face_detector = cv2.CascadeClassifier(r'C:\Users\HONOR\AppData\Local\Programs\Python\Python37\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')
font = cv2.FONT_HERSHEY_SIMPLEX
idnum = 0
names = ['jhy', 'yjl']
# 开启摄像头
cappatu = cv2.VideoCapture(0)
def Face():print('请正对着摄像头...')while True:ret, frame = cappatu.read()## 将图片灰度gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)# 加载特征数据# 参数: scaleFactor(比例因子):图片缩放多少,minNeighbors:至少检测多少次,# minSize maxSize:当前检测区域的最小面积faces = face_detector.detectMultiScale(gray) # scaleFactor=1.01, minNeighbors=3,# maxSize=(33, 33), minSize=(28, 28)# 获取脸部特征值for x, y, w, h in faces:cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), thickness=2)cv2.circle(frame, (x + w // 2, y + h // 2), radius=w // 2, thickness=2, color=(0, 0, 255))# 人脸识别id, confidence = recognizer.predict(gray[y:y + h, x:x + w])if confidence < 80:name = names[id]else:name = "unknown"cv2.putText(frame, str(name), (x + 5, y - 5), font, 1, (230, 250, 100), 1)cv2.putText(frame, str(confidence), (x + 5, y + h - 5), font, 1, (255, 0, 0), 1)print('标签id:', id, '置信评分:', confidence)cv2.imshow("c", frame)if confidence<1:print("识别成功")exit()key = cv2.waitKey(25) # 一直显示if (key & 0xFF == ord("q")) :breakcv2.destroyAllWindows() # 释放资源
if __name__ == '__main__':Face()
到现在为止人民脸识的程序就完成了,
下面是识别别程序以及我的训练数据的的下载地址:
识别程序文件以及训练数据