简体   繁体   中英

C++ OpenCV svm train crashes

I have two vectors:

vector<int> features;
vector<int> labels;

And in some point into my program I fill them with some values. (both vectors same size) Then, when I want to train the svm I copy the vectors into 2 new cv::Mat like this:

Mat trainMat(features.size(), 1, CV_32FC1);
Mat labelsMat(labels.size(), 1, CV_32FC1);
for (int i = 0; i < features.size(); i++) {
    trainMat.at<int>(i, 1) = features.at(i);
    labelsMat.at<int>(i, 1) = labels.at(i);
}

Then I create the svm and it's params :

cv::SVMParams params;
params.svm_type = cv::SVM::C_SVC;
params.kernel_type = cv::SVM::POLY;
params.gamma = 3;
cv::SVM svm;

And finally I train it:

svm.train(trainMat, labelsMat, Mat(), Mat(), params);

But, the program crashes and gives this error:

Unhandled exception at 0x7484D928 in cvtest.exe: Microsoft C++ exception: cv::Exception at memory location 0x0017F04.

At first, I thought the problem was the size of the data(because I compile it at 32bit). So, I used only 20, even 4 samples just to test it. But, still crashing. What else could result a memory error?

Finally, I found the problem. svm.train() accepts only float type features and not int . I just changed vector<int> features; to vector<float> features; and it works.

You are creating trainMat and labelsMat as float matrices with CV_32FC1 but setting the values with trainMat.at<int> which is wrong. It has to be trainMat.at<float> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM