Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load SVM data from file in OpenCV 3.1?

I have a problem with load trained SVM from file. I use Python and OpenCv 3.1.0. I create svm object by:

svm = cv2.ml.SVM_create()

Next, I train svm and save to file by:

svm.save('data.xml')

Now i want to load this file in other Python script. In docs i can't find any methods to do it.

Is there a trick to load svm from file? Thanks for any responses.

like image 564
grochu121 Avatar asked Jul 04 '16 10:07

grochu121


People also ask

How do I use SVM in OpenCV?

Use the OpenCV functions cv::ml::SVM::train to build a classifier based on SVMs and cv::ml::SVM::predict to test its performance. What is a SVM? A Support Vector Machine (SVM) is a discriminative classifier formally defined by a separating hyperplane.

Are kernel type and supportvectors the same as in the SVM file?

After searching for a while I found out that if I have loaded the SVMs and I print the SVM type, kernel type and supportvectors that they are the same as in the SVM .xml file. So I think that the problem is that the prediction is not executed in the right way. I also don't know if I save my SVMs and load them in the appropriate way.

Is there a SVM_load (filepath) method?

I think it's a litte bit confusing that there is no svm.load (filepath) method as a counterpart of svm.save (filepath), but when I read the module help it makes sense to me that SVM_load is a child of cv2.ml (sibling of SVM_create). Be sure that your opencv master branch is up-to-date (currently version 3.1.0-dev) SVM_create (...)

What is a support vector machine (SVM)?

A Support Vector Machine (SVM) is a discriminative classifier formally defined by a separating hyperplane. In other words, given labeled training data ( supervised learning ), the algorithm outputs an optimal hyperplane which categorizes new examples.


1 Answers

I think it's a litte bit confusing that there is no svm.load(filepath) method as a counterpart of svm.save(filepath), but when I read the module help it makes sense to me that SVM_load is a child of cv2.ml (sibling of SVM_create).

Be sure that your opencv master branch is up-to-date (currently version 3.1.0-dev)

>>> import cv2
>>> cv2.__version__
'3.1.0-dev'
>>> help(cv2.ml)

returns

SVM_create(...)
    SVM_create() -> retval

SVM_load(...)
    SVM_load(filepath) -> retval

so you can simply use something like:

if not os.path.isfile('svm.dat'):
    svm = cv2.ml.SVM_create()
    ...
    svm.save('svm.dat')
else:
    svm = cv2.ml.SVM_load('svm.dat')
like image 168
Fabian Avatar answered Oct 03 '22 05:10

Fabian