训练数据

 1 import os #遍历路径
 2 import cv2
 3 import sys
 4 import numpy as np
 5 from PIL import Image 
 6 def getImageAndLabels(path):
 7     facesSamples = [] 
 8     ids = []
 9     imagePaths = [os.path.join(path,f) for f in os.listdir(path)]
10     # print(imagePaths)
11     # ------>>>如:'D:/百度云下载/train_data/data/jm\\10.pgm'
12     # 检测人脸特征函数
13     face_detector = cv2.CascadeClassifier(
14         'D:/Opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml')
15     # 遍历列表中的图片
16     for imagePath in imagePaths:
17         # 打开图片
18         PIL_img = Image.open(imagePath).convert('L')
19         # 将整张图像转换为数组
20         img_numpy = np.array(PIL_img,'uint8')
21         # print(img_numpy)
22         # 获取人脸
23         faces = face_detector.detectMultiScale(img_numpy)
24         # 获取每张图片的id
25         id = int(os.path.split(imagePath)[1].split('.')[0])
26         # print(os.path.split(imagePath))  
27         # --->('D:/百度云下载/train_data/data/jm', '1.pgm')
28         # 人脸区域提取
29         for x,y,w,h in faces:
30             # 获得图像数组
31             facesSamples.append(img_numpy[y:y+h,x:x+w])
32             # 获取标签数组
33             ids.append(id)    
34     return facesSamples,ids
35 
36 if __name__ == '__main__':
37     # 图片的路径 
38     path = 'D:/百度云下载/train_data/data/jm'
39     # 获取图像数组和id标签数组
40     faces,ids = getImageAndLabels(path)
41     # 获取循环对象
42     recognizer = cv2.face.LBPHFaceRecognizer_create()
43     recognizer.train(faces,np.array(ids))
44     # 保存文件
45     recognizer.write('D:/trainer/trainer.yml')
46     

 

posted @ 2020-05-21 14:22  小他_W  阅读(339)  评论(0编辑  收藏  举报