How to import a trained SVM detector in OpenCV 2.4

2020-08-01 03:43发布

问题:

So I have followed this guide to train my own pedestrian HOG detector. https://github.com/DaHoC/trainHOG/wiki/trainHOG-Tutorial

And it was successful with 4 files generated.

  • cvHOGClassifier.yaml
  • descriptorvector.dat
  • features.dat
  • svmlightmodel.dat

Does anyone know how to load the descriptorvector.dat file as a vector? I've tried this but failed.

    vector<float> detector;
    std::ifstream file;
    file.open("descriptorvector.dat");
    file >> detector;
    file.close();

This is something I would like to use eventually.

    gpu::HOGDescriptor hog(Size(64, 128), Size(16, 16), Size(8, 8), Size(8, 8),9);
    hog.setSVMDetector(detector);

Thank you in advance!

回答1:

If you have already trained your SVM, you could just save the weights and the intercept in a TXT file and then load it in an array/vector. You would then use it as follows:

std::vector<float> descriptorsValues;   //A vector to store the computed HoG values
std::vector<cv::Point> locations;
hog.compute(image, descriptorsValues, cv::Size(0, 0), cv::Size(0, 0), locations);
double res = 0;
for (int i = 0; i < svmDimension - 1; i++)
{
    res += w[i] * descriptorsValues.at(i);
}
res = res + w[svmDimension - 1];            
return res;

where svmDimension is the array/vector which contains the SVM weights followed by the SVM intercept, and res is the SVM response



回答2:

You can read the file and push every value back to an array of float, so first declare it:

vector<float> myDescriptorVector;

Then push every value:

ifstream infile ("yourFile.dat".c_str());

float number;

while (infile >> number)
    myDescriptorVector.push_back(number);


return myDescriptorVector;

Finally use the standard initialization for the HOG and pass the vector to the SVM detector as you already guessed:

hog.setSVMDetector(myDescriptorVector);


标签: c++ opencv gpu svm