1.录入人脸,输入ID号
haarcascade_frontalface_default.xml
# 导入模块
import os
import numpy as np
import cv2 as cv
import cv2face_detector = cv2.CascadeClassifier(r'D:\Automation_All_Files\OCR\haarcascade_frontalface_default.xml') # 待更改# 为即将录入的脸标记一个idface_id = input(r'Userdatainput, Look at the camera and wait …')# sampleNum用来计数样本数目count = 0
while True:#从摄像头读取图片cap = cv2.VideoCapture(0)success,img = cap.read()print(f'success is:{success}')print(f'img is :{img}')#转为灰度图片,减少程序符合,提高识别度if success is True:gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)else:break#检测人脸,将每一帧摄像头记录的数据带入OpenCv中,让Classifier判断人脸#其中gray为要检测的灰度图像,1.3为每次图像尺寸减小的比例,5为minNeighborsfaces = face_detector.detectMultiScale(gray, 1.3, 5)#框选人脸,for循环保证一个能检测的实时动态视频流for (x, y, w, h) in faces:#xy为左上角的坐标,w为宽,h为高,用rectangle为人脸标记画框cv2.rectangle(img, (x, y), (x+w, y+w), (255, 0, 0))#成功框选则样本数增加count += 1#保存图像,把灰度图片看成二维数组来检测人脸区域qw#(这里是建立了data的文件夹,当然也可以设置为其他路径或者调用数据库)cv2.imwrite("data/User."+str(face_id)+'.'+str(count)+'.jpg',gray[y:y+h,x:x+w])#显示图片cv2.imshow('image',img)#保持画面的连续。waitkey方法可以绑定按键保证画面的收放,通过q键退出摄像k = cv2.waitKey(1)if k == '27':break#或者得到800个样本后退出摄像,这里可以根据实际情况修改数据量,实际测试后800张的效果是比较理想的elif count >= 10:break
2.训练:
#encoding=utf-8import osimport cv2import numpy as npfrom PIL import Image# 导入pillow库,用于处理图像# 设置之前收集好的数据文件路径path = r'D:\Automation_All_Files\OCR\data'# 初始化识别的方法recog = cv2.face.LBPHFaceRecognizer_create()# 调用熟悉的人脸分类器detector = cv2.CascadeClassifier(r'D:\Automation_All_Files\OCR\haarcascade_frontalface_default.xml')# 创建一个函数,用于从数据集文件夹中获取训练图片,并获取id# 注意图片的命名格式为User.id.sampleNumdef get_images_and_labels(path):image_paths = [os.path.join(path,f) for f in os.listdir(path)]print(image_paths)#新建连个list用于存放face_samples = []ids = []#遍历图片路径,导入图片和id添加到list中for image_path in image_paths:#通过图片路径将其转换为灰度图片img = Image.open(image_path).convert('L')#将图片转化为数组img_np = np.array(img,'uint8')print(f'os.path.split(image_path)[-1] is:{os.path.split(image_path)[-1]}')if os.path.split(image_path)[-1].split(".")[-1] != 'jpg':continue#为了获取id,将图片和路径分裂并获取id = int(os.path.split(image_path)[-1].split(".")[1])faces = detector.detectMultiScale(img_np)#将获取的图片和id添加到list中for(x,y,w,h) in faces:face_samples.append(img_np[y:y+h,x:x+w])ids.append(id)print( face_samples,ids)return face_samples,ids# 调用函数并将数据喂给识别器训练print(r'Training…')faces, ids = get_images_and_labels(path)# 训练模型recog.train(faces, np.array(ids))# 保存模型recog.save(r'trainner.yml')
3.根据曾经录入的人脸和训练模型,确定当前的camera前的是谁。
# -----检测、校验并输出结果-----import cv2# 准备好识别方法recognizer = cv2.face.LBPHFaceRecognizer_create()# 使用之前训练好的模型recognizer.read(r'trainner.yml')# 再次调用人脸分类器cascade_path = r'D:\Automation_All_Files\OCR\haarcascade_frontalface_default.xml'face_cascade = cv2.CascadeClassifier(cascade_path)# 加载一个字体,用于识别后,在图片上标注出对象的名字font = cv2.FONT_HERSHEY_SIMPLEXidnum = 0# 设置好与ID号码对应的用户名,如下,如0对应的就是初始names = ['original', 'girl', 'minglan', 'me', 'rulan']# 调用摄像头cam = cv2.VideoCapture(0)minW = 0.1 * cam.get(3)minH = 0.1 * cam.get(4)while True:ret, img = cam.read()gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# 识别人脸faces = face_cascade.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=5,minSize=(int(minW), int(minH)))# 进行校验for (x, y, w, h) in faces:cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)idnum, confidence = recognizer.predict(gray[y:y + h, x:x + w])# 计算出一个检验结果if confidence < 100:idum = names[idnum]confidence = "{0}%", format(round(100 - confidence))else:idum = "unknown"confidence = "{0}%", format(round(100 - confidence))# 输出检验结果以及用户名cv2.putText(img, str(idum), (x + 5, y - 5), font, 1, (0, 0, 255), 1)cv2.putText(img, str(confidence), (x + 5, y + h - 5), font, 1, (0, 0, 0), 1)# 展示结果cv2.imshow('camera', img)k = cv2.waitKey(20)if k == 27:break
完成后运行将在左上角显示人名(输入的ID号和)
参考:Python的人脸识别设计史上最全的教程,手把手教(附源代码)_人脸识别代码-CSDN博客