OpenCv SVM输出文件格式



我正在实现我自己的SVM,而不是使用OpenCV的SVM类。我想要我的SVM用来保存其输出的XML文件,如果我愿意的话,将来可以由OpenCV的SVM加载和使用。我该怎么办?

简而言之:OpenCV用于存储其SVM输出的格式是什么?

您可以使用OpenCV的CvSVM::write函数。

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 );

以下是如何创建CvFileStorage并将其保存到磁盘:

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);

通过这种方式,您可以选择将模型保存为XML或YAML格式,并使用CvSVM::read()加载模型文件。希望这能有所帮助。

相关内容

  • 没有找到相关文章

最新更新