SVM培训出错(样本类型的断言失败)

时间:2015-11-10 17:54:30

标签: c++ opencv image-processing svm

我正在尝试使用SVM将查询图像与其相应的类匹配。现在这些类只有1或0.我从.txt文件中提取类并将其存储到Mat中。我使用BoW为训练集中的每个图像计算直方图,并将其存储到Mat中。

Mat response_hist;
Mat histograms;
Mat classes;
ifstream ifs("train.txt");
int total_samples_in_file = 0;
vector<string> classes_names;
vector<string> lines;


for (int i = 1; i <= trainingSetSize; i++){
    cout << "in for loop iteration"<< i << endl;
    _snprintf_s(filepath, 100, "C:/Users/Randal/Desktop/TestCase1Training/train/%d.bmp", i);
    Mat temp = imread(filepath, CV_LOAD_IMAGE_GRAYSCALE);
    Mat tempBW;
    adaptiveThreshold(temp, tempBW, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 11, 2);
    detector->detect(tempBW, keypoints1);
    BOW.compute(tempBW, keypoints1, response_hist);
    response_hist.convertTo(response_hist, CV_32F);
    histograms.push_back(response_hist);
}

    //read from the file - ifs and put into a vector
    std::string line;
    float class_num;
    string imgfilepath;
    for (int j = 1; getline(ifs, line); j++)
        {
            istringstream ss(line);             
            ss >> imgfilepath >> class_num;
            classes.push_back(class_num);

        }

Mats class_num和直方图用于训练SVM。 “直方图”中的每一行代表一个样本(训练集中图像的直方图)。 “class_num”是一行,每列是训练集中相应图像的类(1或0)。

Ptr<ml::SVM> svm = ml::SVM::create();

svm->setType(ml::SVM::C_SVC);
svm->setKernel(ml::SVM::POLY);
svm->setGamma(3);

Mat trainingDataMat(histograms);
Mat trainingDataClass(classes);

trainingDataMat.convertTo(trainingDataMat, CV_32F);
trainingDataMat = trainingDataMat.reshape(trainingDataMat.cols, 1);
trainingDataClass.convertTo(classes, CV_32F);
svm->train(trainingDataMat, ml::ROW_SAMPLE, trainingDataClass); //incorrect types? I think it is a problem with ROW_SAMPLE
Mat res;   // output
svm->predict(output, res);

当我运行这个时,我在cv :: ml :: TrainDataImpl :: setData“中收到错误”Assertion failed(samples.type()== CV_32F || samples.type()== CV_32S)。但是,我已经放置了代码行来将我的Mat类和直方图Mat转换为CV_32F类型。是我的输入问题还是与svm-&gt;火车中的ROW_SAMPLE有关?非常感谢任何帮助。

由于

1 个答案:

答案 0 :(得分:0)

错误是由于输入错误导致的。我在其声明中将Mat classesMat的类型更改为CV_32S。我也改变了

  

trainingDataMat_32.reshape(trainingDataMat_32.cols,1);

拥有正确数量的通道和行。

  

trainingDataMat_32.reshape(1,trainingDataMat_32.rows);

TrainingDataMat.cols根本不是正确的值。它需要1个通道(第一个参数)和与直方图输入相同的行数。

这导致了我正在使用的内核的新错误(SVM参数“POLY”)。我不得不在内核参数正下方添加另一行:

  

svm-&GT; setDegree(3);

这解决了错误。我的输出不正确,但这解决了断言失败。