0

belong my actual problem with OpenCV 3.1 and Qt-Creator. According this report I tried to implement in my own project.

If I want to train my SVM I get the follwing error:

OpenCV Error: Assertion failed (samples.type() == CV_32F || samples.type() == CV_32S) in setData, file C:...\opencv-master\modules\ml\src\data.cpp, line 259

Parts of my code are listed below.

int num_files = 205;
int img_area = 55*66;
Mat training_mat(num_files,img_area, CV_32FC1);
vector<int> label;

//Labels: 1-138 == 1 | 139-205 == 0
for(int i = 0; i < 139; i++)
{
    label.push_back(1);
}
for(int i = 139; i < 206; i++)
{
    label.push_back(0);
}

Mat classes;
Mat(label).copyTo(classes);

// Imread Pictures

for(int c = 1; c < num_files; c++)
{
    ostringstream name;
    name << "../Name_" << c << ".png";
    img_mat = imread(name.str(),0);
    int ii = 0; 
    for (int i = 0; i < img_mat.rows; i++)
    {
        for (int j = 0; j < img_mat.cols; j++)
        {
            training_mat.at<float>(c,ii++) = (float)img_mat.at<uchar>(i,j);
        }
    }
}

training_mat.convertTo(training_mat, CV_32FC1);

I write the Data into an .xml-File with following Params:

FileStorage fs("train_SVM.xml", FileStorage::WRITE);
        fs << "ImagesCount" << num_files;
        time_t rawtime; time(&rawtime);
        fs << "createDate" << asctime(localtime(&rawtime));
        fs << "TrainingData" << training_mat;
        fs << "classes" << classes;
        fs.release();

Training the SVM with this code:

//Read file storage.
    FileStorage fs;
    fs.open("train_SVM.xml", FileStorage::READ);
    Mat SVM_TrainingData;
    Mat SVM_Classes;    
    fs["TrainingData"] >> SVM_TrainingData; 
    fs["classes"] >> SVM_Classes; 
    Ptr<ml::SVM> svm = ml::SVM::create();
    //Set SVM params
    svm->setType(ml::SVM::C_SVC);
    svm->setKernel(ml::SVM::LINEAR);
    svm->setDegree(0);
    svm->setGamma(1);
    svm->setCoef0(0);
    svm->setC(1);
    svm->setNu(0);
    svm->setP(0);
    svm->setTermCriteria(TermCriteria(CV_TERMCRIT_ITER, 1000, 0.01));
    //Train SVM
    svm->train( SVM_TrainingData, ml::ROW_SAMPLE , SVM_Classes );

Do you have a idea what the concrete problem is?

Community
  • 1
  • 1
  • What's the type of `SVM_TrainingData`? – Miki Mar 29 '17 at 19:53
  • I have updated my post with informations about the xml-file – Kabrüggen Mar 29 '17 at 20:09
  • So why are you saving `training_mat` as "TrainingData", but then you're loading "x" ? – Miki Mar 29 '17 at 20:21
  • Hello @Miki. Thank you for your answer. I corrected (possible copy-paste-issu) that. Now when I run the code I get the following error. OpenCV Error: Assertion failed ((layout == ROW_SAMPLE && responses.rows == nsamples) || (layout == COL_SAMPLE && responses.cols == nsamples)) in setData – Kabrüggen Mar 29 '17 at 20:29
  • `SVM_TrainingData` rows is not equal to `SVM_classes` number of elements – Miki Mar 29 '17 at 20:30

0 Answers0