我正在使用openCV训练用于面部识别的数据集。我有3张照片作为训练集。在执行代码进行训练之前,代码中的所有内容都可以正常工作。
cv2.error: OpenCV(3.4.1) C:\projects\opencv-python\opencv_contrib\modules\face\src\lbph_faces.cpp:359: error: (-210) Empty training data was given. You'll need more than one sample to learn a model. in function cv::face::LBPH::train
需要注意的是,错误所在的路径在我的机器上甚至不存在。
我有两个python文件,一个被创建为仅在网络摄像头上看到一个人的脸并将其保存在某个位置。下面是代码:-
import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier('data\haarcascade_frontalface_alt2.xml')
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=5)
for (x, y, w, h) in faces:
print(x, y, w, h)
roi_gray = gray[y:y+h, x:x+w]
roi_color = frame[y:y+h, x:x+w]
img_item = "amitesh2.png"
color = (255, 0, 0)
stroke = 2
width = x+w
height = y+h
rect = cv2.rectangle(frame, (x, y),(width, height), color, stroke)
cv2.imwrite(img_item, roi_gray)
cv2.imshow('test', frame)
if cv2.waitKey(20) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
上面的代码按要求工作。问题在于下面的代码可以训练和识别人脸。
import os
import numpy as np
import cv2
import pickle
from PIL import Image
face_cascade = cv2.CascadeClassifier('data\haarcascade_frontalface_alt2.xml')
print(face_cascade)
recog = cv2.face.LBPHFaceRecognizer_create()
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
img_dir = os.path.join(BASE_DIR, "images")
curr_id = 0
label_ids = {}
x_train = []
y_label = []
for root, dirs, files in os.walk(img_dir):
for fil in files:
if fil.endswith("png") or fil.endswith("jpg"):
path = os.path.join(root, fil)
label = os.path.basename(os.path.dirname(root)).lower()
#print(label, path)
if not label in label_ids:
label_ids[label] = curr_id
curr_id += 1
id_ = label_ids[label]
pil_image = Image.open(path).convert("L")
img_array = np.array(pil_image, "uint8")
#print(img_array)
faces = face_cascade.detectMultiScale(img_array, scaleFactor=1.5, minNeighbors=5)
for (x, y, w, h) in faces:
roi = img_array[y:y+h, x:x+w]
x_train.append(roi)
y_label.append(id_)
with open("labels.pkl", 'wb') as f:
pickle.dump(label_ids, f)
recog.train(x_train, np.array(y_label))
recog.save("trainer.yml")
我已经搜索了整个StackOverflow。我可以看到帖子,但找不到任何关于我的问题的信息。请给我一些指示。