我正在实现自己的 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() 加载模型文件。希望这可以帮助。