我目前正在使用 Pycharm 进行人脸识别项目。
我使用以下代码进行训练:
import os
import cv2
from PIL import Image
import numpy as np
import pickle
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
image_dir = os.path.join(BASE_DIR, "images")
face_cascade = cv2.CascadeClassifier('C:/Users/person/PycharmProjects/pythonProject/cascade/haarcascade_frontalface_default.xml')
recognizer = cv2.face.LBPHFaceRecognizer_create()
current_id = 0
label_ids = {}
y_labels = []
x_train = []
for root, dirs, files in os.walk(image_dir):
for file in files:
if file.endswith(".png") or file.endswith(".jpg"):
path = os.path.join(root, file)
label = os.path.basename(root).replace(" ", "-").lower()
# print(label, path)
if not label in label_ids:
label_ids[label] = current_id
current_id += 1
id_ = label_ids[label]
# print(label_ids)
#y_labels.append(label)
#x_train.append(path)
pil_image = Image.open(path).conver("L")
image_array = np.array(pil_image, "uint8")
#print(image_array)
faces = face_cascade.detectMultiScale(image_array, scaleFactor=1.5, minNeighbors=5)
for (x, y, w, h) in faces:
roi = image_array[y:y + h, x:x + w]
x_train.append(roi)
y_labels.append(id_)
#print(y_labels)
#print(x_train)
with open("labels.pickle", 'wb') as f:
pickle.dump(label_ids, f)
recognizer.train(x_train, np.array(y_labels))
recognizer.save("C:/Users/person/PycharmProjects/pythonProject/recognizerstraining.yml")
虽然我不断收到这个错误
Traceback (most recent call last):
File "C:/Users/person/PycharmProjects/pythonProject/Train.py", line 51, in <module>
recognizer.train(x_train, np.array(y_labels))
cv2.error: OpenCV(4.5.4-dev) D:\a\opencv-python\opencv-python\opencv_contrib\modules\face\src\lbph_faces.cpp:362: error: (-210:Unsupported format or combination of formats) Empty training data was given. You'll need more than one sample to learn a model. in function 'cv::face::LBPH::train
我创建了一个文件夹,在这个文件夹中是每个人的多个文件夹。每个人有 7 张图像。
那么错误的原因可能是什么?