2

I am implementing my own SVM rather than using OpenCV's svm class. I want the XML file that my SVM uses to save its output, can be loaded and used by OpenCV's SVM in future, if I wish. What should I need to do for that ?

In short : what is the format that OpenCV uses to store its SVM output ?

phoxis
  • 60,131
  • 14
  • 81
  • 117
Barshan Das
  • 3,677
  • 4
  • 32
  • 46

1 Answers1

1

You can follow OpenCV's CvSVM::write function.

int i, var_count = get_var_count(), df_count, class_count;
const CvSVMDecisionFunc* df = decision_func;

cvStartWriteStruct( fs, name, CV_NODE_MAP, CV_TYPE_NAME_ML_SVM );

write_params( fs );

cvWriteInt( fs, "var_all", var_all );
cvWriteInt( fs, "var_count", var_count );

class_count = class_labels ? class_labels->cols :
              params.svm_type == CvSVM::ONE_CLASS ? 1 : 0;

if( class_count )
{
    cvWriteInt( fs, "class_count", class_count );

    if( class_labels )
        cvWrite( fs, "class_labels", class_labels );

    if( class_weights )
        cvWrite( fs, "class_weights", class_weights );
}

if( var_idx )
    cvWrite( fs, "var_idx", var_idx );

// write the joint collection of support vectors
cvWriteInt( fs, "sv_total", sv_total );
cvStartWriteStruct( fs, "support_vectors", CV_NODE_SEQ );
for( i = 0; i < sv_total; i++ )
{
    cvStartWriteStruct( fs, 0, CV_NODE_SEQ + CV_NODE_FLOW );
    cvWriteRawData( fs, sv[i], var_count, "f" );
    cvEndWriteStruct( fs );
}

cvEndWriteStruct( fs );

// write decision functions
df_count = class_count > 1 ? class_count*(class_count-1)/2 : 1;
df = decision_func;

cvStartWriteStruct( fs, "decision_functions", CV_NODE_SEQ );
for( i = 0; i < df_count; i++ )
{
    int sv_count = df[i].sv_count;
    cvStartWriteStruct( fs, 0, CV_NODE_MAP );
    cvWriteInt( fs, "sv_count", sv_count );
    cvWriteReal( fs, "rho", df[i].rho );
    cvStartWriteStruct( fs, "alpha", CV_NODE_SEQ+CV_NODE_FLOW );
    cvWriteRawData( fs, df[i].alpha, df[i].sv_count, "d" );
    cvEndWriteStruct( fs );
    if( class_count > 1 )
    {
        cvStartWriteStruct( fs, "index", CV_NODE_SEQ+CV_NODE_FLOW );
        cvWriteRawData( fs, df[i].sv_index, df[i].sv_count, "i" );
        cvEndWriteStruct( fs );
    }
    else
        CV_ASSERT( sv_count == sv_total );
    cvEndWriteStruct( fs );
}
cvEndWriteStruct( fs );
cvEndWriteStruct( fs );

And here is how you can create a CvFileStorage and save it to the disk:

const char* filename = "/xxx/yyy/zzz";
const char* modelname = "svm";
CvFileStorage* fs = cvOpenFileStorage(filename, 0, CV_STORAGE_WRITE);
if (fs) {
  write(fs, modelname);
}
cvReleaseFileStorage(&fs);

By doing this way, you can choose to save the model into XML or YAML format, and use CvSVM::read() to load the model file. Hope this helps.

cxyzs7
  • 1,227
  • 8
  • 15