在SVM OpenCV 3.0

时间:2017-03-14 06:15:57

标签: c++ opencv classification svm

我已经能够训练我的SVM了。程序可以运行直到预测。我通过测试图像得到SVM预测错误。

我在代码中遗漏了什么?有人能帮助我吗?

OpenCV Error: Assertion failed (samples.cols == var_count && samples.type() == CV_32F) in cv::ml::SVMImpl::predict, file C:\buildslave64\win64_amdocl\master_PackSlave-win64-vc14-shared\opencv\modules\ml\src\svm.cpp, line 1930

我的预测代码如下:

#include <opencv2/core.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc.hpp>
#include "opencv2/imgcodecs.hpp"
#include <opencv2/highgui.hpp>
#include <opencv2/ml.hpp>
#include <iostream>
#include <fstream>
#include<string.h>


using namespace std;
using namespace cv;
using namespace cv::ml;

int main(int, char**)
{

    HOGDescriptor hog(cv::Size(64, 128), cv::Size(16, 16), cv::Size(8, 8), cv::Size(8, 8), 9, 1, -1, 0, 0.2, true, HOGDescriptor::DEFAULT_NLEVELS);
    vector<cv::Point> locations;
    std::vector<float> extractedFeature;
    vector<vector< float>> features;
    vector<Mat> testingImages;

    vector<int> testingLabels;
    int numFiles = 11; //no. of rows in matrix
    int img_area = 320 * 240; //no. of columns - area of image 76800

    FileStorage myfile("features.xml", FileStorage::READ);

    const char* path = "C:/Testing Set/Extracted_Frames/image";

    //set up labels for each training image
    float label = 1.0; //positive image +1

    Mat testingMat(img_area, numFiles, CV_32FC1);// 1D training matrix
    cout << testingMat.rows << endl;
    cout << testingMat.cols << endl;
    Mat res;   // output
    //set up labels for each training image
    Mat labels(testingMat.rows, 1, CV_32SC1, label); //flatten 1D label matrix
    Ptr<ml::SVM> svm = Algorithm::load<ml::SVM>("test.xml");
    std::cout << "Model Loaded" << std::endl;

    for (int i = 0; i < labels.rows; i++) {
        labels.at<int>(i, 0) = labels.at<int>(i, 0);
    }

    for (int file_num = 0; file_num < numFiles; file_num++)
    {
        stringstream ss(stringstream::in | stringstream::out);
        ss << path << file_num << ".jpg";
        cout << "read path = " << ss.str() << endl;

        myfile["Descriptors" + ss.str()] >> extractedFeature;
        Mat img = imread(ss.str());

        int ii = 0; // Current column in training_mat
        for (int i = 0; i < img.rows; i++) {
            for (int j = 0; j < img.cols; j++) {
                testingMat.at<float>(ii++, file_num) = img.at<uchar>(i, j);
                Mat sampleMat = (Mat_<float>(1, 2) << i, j);
                float response = svm->predict(sampleMat);//error here 
            }
        }


        features.push_back(extractedFeature);
        testingImages.push_back(img);
        testingLabels.push_back(1);
        testingLabels.push_back(file_num);
        myfile.release();
    }

    labels.at<int>(1, 0) = -1;

}

0 个答案:

没有答案