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("C:\\Python\\pythonkku\\data\\haarcascade_frontalface_alt.xml")
#遍历图片,进行对照
for imagePath in imagePaths:#把图片信息进行遍历将身份信息进行保存
#打开图片,灰度化,PIL有五种不同模式1,L,RGB,RGBA,CMYK,YCbCr,I,F
PIL_img=Image.open(imagePath).convert("L")#l方式打开,灰度图像
PIL_img= cv2.cvtColor(np.array(PIL_img), cv2.COLOR_RGBA2BGRA) # PIL转cv2
#将图片转化数组,以黑白深浅,灰度图片用数组来表示
img_numpy=np.array(PIL_img,"uint8")#现在是一个列表
#获取图片人脸特征提取特征
faces=face_detector.detectMultiScale(img_numpy)
#获取每张图片的姓名与id
id=str(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='C:\\Python\\Python38\\facerecord'
#获取图像的数组和标签ids 与姓名
faces,ids=getImageAndLabels(path)
#加载识别器,在进行训练整合
recognizer=cv2.face.LBPHFaceRecognizer_create()
#训练
recognizer.train(faces,np.array(ids))
#保存文件
recognizer.write("C:\\Python\\Python38\\trainer\\trainer.yml")
上述代码运行之后出现
这种提示bug:
Traceback (most recent call last):
File "C:\Users\午饭\Documents\Visual Studio 2022\练习\图像识别基本框架\图像识别基本框架.py", line 242, in
recognizer.train(faces,np.array(ids))
cv2.error: OpenCV(4.7.0) :-1: error: (-5:Bad argument) in function 'train'
Overload resolution failed:
- labels data type = 19 is not supported
- Expected Ptrcv::UMat for argument 'labels'