pythonopencvsvm

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.


Solution

  • 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')