如何保存openCV分类器?

How to save openCV classifier?

我想保存一个已经在多个图像上训练过的分类器,以避免每次我 运行 程序时重新训练它所花费的时间。对于 sklearn 的分类器,我可以使用 pickle.load 简单地腌制它们,但是当我尝试这样做时,我得到以下错误:

TypeError: can't pickle cv2.face_LBPHFaceRecognizer objects

这是分类器本身:

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml')
clf = cv2.face.LBPHFaceRecognizer_create()

img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
# detecting face using haarcasade
face = face_cascade.detectMultiScale(img, minNeighbors = 3)
# detecting region of interest and appending it to a separate matrix
for x, y, w, h in face:
     roi = img[y:y+h, x:x+w]
     x_train.append(roi)
     y_train.append(label)
 clf.train(x_train, y_train)

有没有办法保存这样的分类器?

您可以将此类分类器保存为 .yml 文件。

例如:

clf.save('trainingData.yml')

您可以使用以下方式加载相同内容:

clf.load('trainingData.yml')