我尝试运行SVM example project of the official OpenCV documentation但似乎代码已过时,因为openCV版本3.0.0。
所以我在this stackoverflow entry的帮助下调整了代码,并提出了以下代码:
// Data for visual representation
int width = 512, height = 512;
Mat image = Mat::zeros(height, width, CV_8UC3);
// Set up training data
int labels[4] = { 1.0, -1.0, -1.0, -1.0 };
Mat labelsMat(4, 1, CV_32S, labels);
int trainingData[4][2] = { { 501, 10 },{ 255, 10 }, { 501, 255 }, { 10, 501 } };
Mat trainingDataMat(4, 2, CV_32F, trainingData);
// Set up SVM's parameters
Ptr<SVM> svm = SVM::create();
svm->setType(SVM::C_SVC);
svm->setKernel(SVM::LINEAR);
svm->setTermCriteria(TermCriteria(CV_TERMCRIT_ITER, 100, 1e-6));
Ptr<TrainData> trainData = TrainData::create(trainingDataMat, ml::ROW_SAMPLE, labelsMat);
// Train the SVM
//svm->trainAuto(trainData);
svm->train(trainingDataMat, ml::ROW_SAMPLE, labelsMat);
Vec3b green(0, 255, 0), blue(255, 0, 0), red(0, 0 ,255), yellow(0, 255, 255);
// Show the decision regions given by the SVM
for (int i = 0; i < image.rows; ++i)
for (int j = 0; j < image.cols; ++j)
{
Mat sampleMat = (Mat_<float>(1, 2) << i, j);
Mat result;
svm->predict(sampleMat, result);
float response = result.at<float>(0);
if (response == 1)
image.at<Vec3b>(i, j) = green;
else if (response == -1)
image.at<Vec3b>(i, j) = blue;
else if (response == 2)
image.at<Vec3b>(i, j) = red;
else if (response == -2)
image.at<Vec3b>(i, j) = yellow;
//else return 0;
}
现在代码至少在没有例外的情况下运行,但它仍无效。
将TrainingData::create
方法与svm->trainAuto(trainData)
结合使用时,我只会得到一张黑色图像(predict
始终返回0)。
如果我使用svm->train(trainingDataMat, ml::ROW_SAMPLE, labelsMat)
,我会得到一个图像,其中每个像素都具有相同的颜色(predict
始终返回相同的值)。如果标签设置如上,图像将全部为蓝色。
我真的不知道自己做错了什么。