def train_files(model,label):
files = os.listdir(label)
for f in files:
img = cv2.imread(f,0)
model.train(img, np.array(label))
model = cv2.face.LBPHFaceRecognizer_create()
train_files(model, 'test')
I have cropped face images in the directory, and I call a image and train function. But I meet a following error in the train() function.
I don’t know what is problem. Could you help me?
Traceback (most recent call last):
File "C:/face/face_reg.py", line 118, in
train_files(model,label)
File "C:/face/face_reg.py", line 83, in train_files
model.train(img, np.array(label))
cv2.error: OpenCV(4.5.4-dev) :-1: error: (-5:Bad argument) in function 'train'
> Overload resolution failed:
> - labels data type = 19 is not supported
> - Expected Ptr for argument 'labels'
label is the second parameter of train function of face recognizer. label can be file name or name of the person to recognize.
Yes, if the type of second parameter is not array it makes error. label is not numpy array.
this is entirely wrong, you cannot call train() for a single image,
also labels are ints, not strings
instead, you need to collect all training images into an array,
and make a numpy array of integer ids for the labels. then you can call
I fixed 3 errors. One is as your advice that the arguments for train function are changed to arrays, and type of second parameter of train funtion was integer not string. And I found a serious problem in my code that image files did not read because of file path. Arrays, type and file path caused errors. Thank you for your help.
My fixed code is following. If something is weird, please let me know.
def train_files(label):
p = 'c:\\face\\' # absolute path of source code
files = os.listdir(label) # sub-directory of training images
train_faces = [] # cropped face image
train_labels = [] # labels
for f in files:
fname = os.path.join(p,label,f) # make absolute path of a training image
img = cv2.imread(fname,0) # read gray-scale image
img = cv2.resize(img, (100,100), interpolation=cv2.INTER_CUBIC)
train_faces.append(img)
train_labels.append(getDigit(f)) # getDigit is to get number of file name
return np.array(train_faces), np.array(train_labels)
faces, labels = train_files(label)
model = cv2.face.LBPHFaceRecognizer_create()
model.train(faces, labels)