alexmark
alexmark

Reputation: 391

OpenCV 3 and SVM training

I already searched for this type of error but I did not find anything similar...

My question is related to opencv3 and SVM. Basically, I have this:

int labels[2] = {1, -1};
Mat labelsMat(2, 1, CV_32S, labels);
float trainingData[2][2] = { { 501, 10 }, { 255, 10 } };
Mat training_samples(2, 2, CV_64FC1, trainingData);

...

training_samples.convertTo(training_samples, CV_32S);
labelsMat.convertTo(labelsMat, CV_32F);
Ptr<ml::SVM> svm = ml::SVM::create();
svm->setType(ml::SVM::C_SVC);
svm->setKernel(ml::SVM::LINEAR);
svm->setC(1); 
svm->train(training_samples, ml::SampleTypes::ROW_SAMPLE, labelsMat);

When I compile, I get this error:

OpenCV Error: Bad argument (in the case of classification problem the responses must be categorical; either specify varType when creating TrainData, or pass integer responses) in train, file /home/develop/_Morpheos/opencv/opencv/modules/ml/src/svm.cpp, line 1618 terminate called after throwing an instance of 'cv::Exception' what(): /home/develop/_Morpheos/opencv/opencv/modules/ml/src/svm.cpp:1618: error: (-5) in the case of classification problem the responses must be categorical; either specify varType when creating TrainData, or pass integer responses in function train

I tried almost everything but I do not catch the error.

Could you help me?

Upvotes: 1

Views: 1265

Answers (1)

Miki
Miki

Reputation: 41765

CV_64F means double, but you need float, i.e. CV_32F. Use:

// Change me!
Mat training_samples(2, 2, CV_32FC1, trainingData);

Also there's no need to convert to integer type, so you can remove the line:

// Remove me!
training_samples.convertTo(training_samples, CV_32S);

And labels should be of integer type in classification, so remove also:

// Remove me!
labelsMat.convertTo(labelsMat, CV_32F);

You can look here for a complete example.

Upvotes: 1

Related Questions