OpenCv SVM output file format

天涯浪子 提交于 2019-12-24 00:14:07

问题


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 ?


回答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.



来源:https://stackoverflow.com/questions/14806448/opencv-svm-output-file-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!