pip install opencv-contrib-python
第一步 级联分类器训练 opencv官网下载完整版 opencv-python
安装到当前目录下
创建文件夹:trainer
准备放入 人脸特征文件
创建文件夹:img
将人像图片放入里面
import osimport cv2import numpy as npdef getImageAndLabels(path): facesSamples = [] ids = [] imagePaths = [os.path.join(path, f) for f in os.listdir(path)] # 检测人脸 face_detector = cv2.CascadeClassifier('./sources/data/haarcascades/haarcascade_frontalface_alt2.xml') # 打印数组imagePaths # print('数据排列:', imagePaths) # 遍历列表中的图片 for imagePath in imagePaths: img_numpy = cv2.imread(imagePath) img_numpy = cv2.cvtColor(img_numpy, cv2.COLOR_BGR2GRAY) # 获取图片人脸特征 faces = face_detector.detectMultiScale(img_numpy) # 获取每张图片的id和姓名 id = int(os.path.split(imagePath)[1].split('.')[0]) # 预防无面容照片 for x, y, w, h in faces: ids.append(id) facesSamples.append(img_numpy[y:y + h, x:x + w]) # 打印脸部特征和id # print('fs:', facesSamples) # print('id:', id) # print('fs:', facesSamples[id]) # print('fs:', facesSamples) # print('脸部例子:',facesSamples[0]) # print('身份信息:',ids[0]) return facesSamples, idsif __name__ == '__main__': # 图片路径 path = './img' # 获取图像数组和id标签数组和姓名 faces, ids = getImageAndLabels(path) # 获取训练对象 recognizer = cv2.face.LBPHFaceRecognizer_create() # recognizer.train(faces,names)#np.array(ids) recognizer.train(np.array(faces), np.array(ids)) # 保存文件 recognizer.write('trainer/trainer.yml') # save_to_file('names.txt',names)
第二步 实时人脸识别import cv2# 加载训练数据集文件recogizer = cv2.face.LBPHFaceRecognizer_create()recogizer.read('trainer/trainer.yml')warningtime = 0# 准备识别的图片def face_detect_demo(img): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 转换为灰度 face_detector = cv2.CascadeClassifier('./sources/data/haarcascades/haarcascade_frontalface_alt2.xml') face = face_detector.detectMultiScale(gray, 1.1, 5, cv2.CASCADE_SCALE_IMAGE, (100, 100), (300, 300)) # face=face_detector.detectMultiScale(gray) for x, y, w, h in face: cv2.rectangle(img, (x, y), (x + w, y + h), color=(0, 0, 255), thickness=2) cv2.circle(img, center=(x + w // 2, y + h // 2), radius=w // 2, color=(0, 255, 0), thickness=1) # 人脸识别 ids, confidence = recogizer.predict(gray[y:y + h, x:x + w]) # print('标签id:',ids,'置信评分:', confidence) 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, '0', (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1) cv2.imshow('result', img) # print('bug:',ids)cap = cv2.VideoCapture(0)while True: flag, frame = cap.read() if not flag: break face_detect_demo(frame) if ord(' ') == cv2.waitKey(10): breakcv2.destroyAllWindows()cap.release()# print(names)