0

我一直在尝试将 cv2.knearest 训练模型保存到文件中。对于下面的代码(python 2)

import numpy as np 
import cv2
from sklearn.datasets import load_digits
import pickle
from sklearn.externals import joblib
samples = np.float32(np.loadtxt('feature_vector_pixels.data'))
responses = np.float32(np.loadtxt('samples_pixels.data'))
model = cv2.KNearest()
model.train(samples, responses)
# save the model to disk
filename = 'init_model.sav'
pickle.dump(model, open(filename, 'wb'))

我明白了

Traceback (most recent call last):
File "picklemake.py", line 14, in <module>
pickle.dump(model, open(filename, 'wb'))
File "C:\Users\Karthik\Anaconda3\envs\py27\lib\pickle.py", line 1376, in  dump
Pickler(file, protocol).dump(obj)
File "C:\Users\Karthik\Anaconda3\envs\py27\lib\pickle.py", line 224, in dump
self.save(obj)
File "C:\Users\Karthik\Anaconda3\envs\py27\lib\pickle.py", line 306, in save
rv = reduce(self.proto)
File "C:\Users\Karthik\Anaconda3\envs\py27\lib\copy_reg.py", line 70, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle KNearest objects

是否有任何替代方法可以将此模型保存到文件中。

同样在使用model.save时,我得到OpenCV Error: The function/feature is not implemented () in CvStatModel::write, file ..\..\..\modules\ml\src\inner_functions.cpp

4

1 回答 1

1

最接近的扩展CvStatModel。后者有两个重载的save(...)方法,可以完全满足您的需要。

我不完全知道为什么,但经验法则是,如果你在 C(++) 库上使用 python 包装器,它的类通常不会是 pickle'able。

于 2017-04-03T11:48:33.880 回答