2
我正在實現自己的SVM,而不是使用OpenCV的svm類。我希望我的SVM用於保存其輸出的XML文件,如果願意,可以在將來由OpenCV的SVM加載和使用。我應該爲此做些什麼?OpenCv SVM輸出文件格式
簡而言之:OpenCV用來存儲SVM輸出的格式是什麼?
我正在實現自己的SVM,而不是使用OpenCV的svm類。我希望我的SVM用於保存其輸出的XML文件,如果願意,可以在將來由OpenCV的SVM加載和使用。我應該爲此做些什麼?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()加載模型文件。希望這可以幫助。