OpenCV 3 和 SVM 训练

OpenCV 3 and SVM training

我已经搜索过此类错误,但没有找到任何类似的错误...

我的问题与opencv3 和SVM 有关。基本上,我有这个:

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);

当我编译时,我得到这个错误:

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

我几乎尝试了所有方法,但没有发现错误。

你能帮帮我吗?

CV_64F表示double,但你需要float,即CV_32F。使用:

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

也不需要转换成整数类型,所以你可以删除行:

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

并且标签在分类时需要是整数类型,所以也去掉:

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

您可以查看 以获得完整示例。