1 import cv2 2 import numpy as np 3 import os 4 # 加载训练数据集文件 5 recognizer = cv2.face.LBPHFaceRecognizer_create() 6 recognizer.read('D:/trainer/trainer.yml') 7 # 准备识别的图片 8 img = cv2.imread('D:/trainer_datas/orl_faces/s40/1.pgm') 9 # 将图片转化为灰度图片 10 gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 11 # 加载特征数据 12 face_detector = cv2.CascadeClassifier('D:/Opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml') 13 faces = face_detector.detectMultiScale(gray) 14 for x,y,w,h in faces: 15 cv2.rectangle(img,(x,y),(x+w,y+h),color=(0,255,0),thickness=2) 16 # 人脸识别 17 id,confidence = recognizer.predict(gray[y:y+h,x:x+w]) 18 print('标签id:',id,'置信评分:',confidence) 19 cv2.imshow('result',img) 20 cv2.waitKey(0) 21 cv2.destroyAllWindows()