SVM predict error error: (-215:Assertion failed) samples.cols == var_count && samples.type() == CV_32F in function 'predict' [closed]

asked 2019-12-21 22:34:30 -0600

HelloWorld gravatar image

I use load svm, FileStorage load vocabulary. it happend error,(-215:Assertion failed) samples.cols == var_count && samples.type() == CV_32F in function 'predict', how i to do?

code:

   onst std::string &svmPath = "svm.xml";
cv::Ptr<cv::FeatureDetector> detector = cv::xfeatures2d::SURF::create(
        minHessian);
cv::Mat vocabulary;
cv::Ptr<cv::ml::SVM> SVM;
FileStorage fs("result.yml", FileStorage::READ);
fs["vocabulary"] >> vocabulary;
fs["names"] >> names;
fs.release();
loadSVM(SVM, svmPath);
Mat trainingMat = imread("1.jpg", IMREAD_GRAYSCALE);
if (!trainingMat.empty()) {
    imshow("1", trainingMat);
    waitKey(0);
    scaleImage(trainingMat);
    cv::Ptr<cv::FeatureDetector> detector = cv::xfeatures2d::SURF::create(
                minHessian);
        cv::Ptr<cv::DescriptorExtractor> extractor = cv::xfeatures2d::SURF::create(
                minHessian);
        cv::Ptr<cv::DescriptorMatcher> matcher = cv::DescriptorMatcher::create(
                "BruteForce");
        cv::BOWImgDescriptorExtractor bowide(extractor, matcher);
        bowide.setVocabulary(vocabulary);
        std::vector<cv::KeyPoint> keypoints;
        detector->detect(trainingMat, keypoints);
        if (keypoints.size()<10) {
            return -1;
        }
        cv::Mat imgDescriptor;
        bowide.compute(trainingMat, keypoints, imgDescriptor);
        if (imgDescriptor.empty()) {
            return -1;
        }
        Mat testResponse;
        float res = SVM->predict(imgDescriptor, testResponse,
                cv::ml::StatModel::RAW_OUTPUT);
    //  float res2 = SVM->predict(imgDescriptor, testResponse,
    //          cv::ml::SVM::UPDATE_MODEL);
        int firstIndex = -1;
        cout << "testResponse: " << testResponse << endl;

        for (int i = 0; i < testResponse.rows; i++) {
            firstIndex = testResponse.at<float>(i, 0);
    }
}
edit retag flag offensive reopen merge delete

Closed for the following reason the question is answered, right answer was accepted by berak
close date 2019-12-22 05:08:48.373548

Comments

probably your svm isn't trained / loaded.

please check if trainingMat.cols == vocabulary.cols

and add the loadSVM() code

berak gravatar imageberak ( 2019-12-22 02:45:26 -0600 )edit
1

thank you very much , i searched it https://answers.opencv.org/question/9... , now it work.

HelloWorld gravatar imageHelloWorld ( 2019-12-22 04:08:16 -0600 )edit