马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import os
import cv2
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)]
#加载分类器
face_detector = cv2.CascadeClassifier('D:/OPENCV/opencv/sources/data/haarcascade/haarcascade_frontalface_alt2.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')
#获取图片人脸特征
[u] face = face_detector.detectMultiScale(img_numpy)[/u] //报错原因Traceback (most recent call last):File "C:\Users\程\Desktop\opencv\9训练数据.py", line 39, in <module>faces,ids=getImageAndLabels(path)
#获取每张图片的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('id:',id)
print('fs:',facesSamples)
return facesSamples,ids
if __name__ == '__main__':
#图片路径
path='D:/OPENCV/opencv/data/jm/'
#获取图像数组和ID标签数组和姓名
[u] faces,ids=getImageAndLabels(path)[/u] //报错原因File "C:\Users\程\Desktop\opencv\9训练数据.py", line 23, in getImageAndLabels face = face_detector.detectMultiScale(img_numpy) cv2.error: OpenCV(4.5.5) D:\a\opencv-python\opencv-python\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'
#加载识别器
recognizer=cv2.face.LBPHFfaceRecoginizer_create()
#训练
recognizer.train(faces,np.array(ids))
#保存
recognizer.write('D:/OPENCV/opencv/data/trainer/trainer.yml')
|