[人脸识别]09-人脸模型训练
1.程序代码
#导入CV模块 import cv2 as cv import os from PIL import Image import numpy as np def getImageAndLabels(path): #存储人脸数据 facesSamples=[] #存储姓名数据 ids=[] # 存储图片信息 imagePaths=[ os.path.join(path,f) for f in os.listdir(path)] print("files:",imagePaths) #加载分类器 face_detector=cv.CascadeClassifier(cv.data.haarcascades+"haarcascade_frontalface_default.xml") #遍历列表中的图片 for imagePath in imagePaths: #打开图片,灰度化,PIL有九种不同模式:1,l,p,rgb,rgba,cmyk,yCbCr,I,F PIL_img=Image.open(imagePath).convert('L') #将图片转换为数组,以黑白深浅 img_numpy=np.array(PIL_img,'uint8') #获取人脸特征 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]) print('id',id) print('fs',facesSamples) return facesSamples,ids if __name__ == '__main__': #图片路径 root = os.getcwd() path=root+"/jm/" print("path:", path) #获取图像数组,id faces,ids=getImageAndLabels(path) #获取训练对象 recognizer=cv.face.LBPHFaceRecognizer_create() #执行训练 recognizer.train(faces,np.array(ids)) #保存训练结果 print("write:", root+"/trainer/trainer.yml") recognizer.write(root+"/trainer/trainer.yml")
2结果
.