I am somewhat new to SVMs and object recognition, and am currently attempting to train an SVM using Emgu CV 3.0, save it to a file, and then load it (for use in HOGDescriptor.SetSVMDetector).
However, among other problems, I cannot find a way to load the SVM after I have saved it.
So far, my code basically does the following:
SVM myFirstSVM = new SVM();
// do some stuff, set some parameters...
myFirstSVM.Train(someParameters);
myFirstSVM.Save("filePath");
From here, the problem lies with reloading the SVM after being saved. I have checked several help topics and pages, and the only related things I could find pertained to OpenCV, which used the following method:
SVM mySecondSVM;
mySecondSVM.load("filePath");
However, I could find no method ".load()" in Emgu 3.0, although it appeared to be present in previous versions. Is there an equivalent of this OpenCV method in Emgu 3.0? I would assume there is, and I am sure it is fairly simple, but I cannot for the life of me find it.
For EmguCV 3.0.0, the Save/Load
functionality doesn't seem to be supported (Load
doesn't exist), you could use Write/Read
instead.
A function to save an SVM model:
public static void SaveSVMToFile(SVM model, String path) {
if (File.Exists(path)) File.Delete(path);
FileStorage fs = new FileStorage(path, FileStorage.Mode.Write);
model.Write(fs);
fs.ReleaseAndGetString();
}
A function to load the SVM model provided the correct path:
public static SVM LoadSVMFromFile(String path) {
SVM svm = new SVM();
FileStorage fs = new FileStorage(path, FileStorage.Mode.Read);
svm.Read(fs.GetRoot());
fs.ReleaseAndGetString();
return svm;
}
I have saved and read the SVM model using the specified functions. But I am working with 3.1.0 version and hope it works for you as well:
I have saved the model in an XML file because the read function works on xml file as far as I know:
Emgu.CV.ML.SVM model = new Emgu.CV.ML.SVM();
model.SetKernel(Emgu.CV.ML.SVM.SvmKernelType.Linear);
model.Type = Emgu.CV.ML.SVM.SvmType.CSvc;
model.C = 1;
model.TermCriteria = new MCvTermCriteria(100, 0.00001);
bool trained = model.TrainAuto(my_trainData, 5);
model.Save("SVM_Model.xml");
and I read the model as follows:
Emgu.CV.ML.SVM model_loaded = new Emgu.CV.ML.SVM();
FileStorage fsr = new FileStorage("SVM_Model.xml", FileStorage.Mode.Read);
model_loaded.Read(fsr.GetFirstTopLevelNode());
and it works correctly.
I hope it works for you so.
For EmguCV 1.5.0:
Load Method (fileName):
Inherited from StatModel
Load the statistic model from file
fileName (String)
The file to load the model from
For EmguCV 3.0+:
Load()
is not available, as you can see in the source code: https://sourceforge.net/p/emgucv/code/ci/master/tree/Emgu.CV.ML/StatModel.cs