本文基于http://docs.opencv.org/3.0-beta/doc/tutorials/ml/introduction_to_svm/introduction_to_svm.html,这里面存在着opencv2版本的使用方法。尤其是3.0中不存在params了。而且opencv3.0的参考文章比较少,特地上传自己的代码,在链接中代码的基础上修改了,可以直接跑通,并且增加了测试的环节,希望对各位有所帮助。
下面就附上代码:
#include
#include
#include
#include
#include
#include "opencv2/imgcodecs.hpp"
#include
#include
using namespace std;
using namespace cv;
using namespace cv::ml;
int main(int, char**)
{
// 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, -1, -1, -1 };
Mat labelsMat(4, 1, CV_32SC1, labels);
float trainingData[4][2] = { { 501, 10 }, { 255, 10 }, { 501, 255 }, { 10, 501 } };
Mat trainingDataMat(4, 2, CV_32FC1, trainingData);
// // Set up SVM's parameters
// SVM::Params params;
// params.svmType = SVM::C_SVC;
// params.kernelType = SVM::LINEAR;
// params.termCrit = TermCriteria(TermCriteria::MAX_ITER, 100, 1e-6);
//
Ptr
svm->setType(ml::SVM::C_SVC);
svm->setKernel(ml::SVM::LINEAR);
cv::TermCriteria setTermCriteria(cv::TermCriteria::MAX_ITER,100,1e-6);
// Train the SVM
Ptr
svm->train(tData);
svm->write(cv::FileStorage("clouddetection.xml", cv::FileStorage::WRITE));
{
cv::FileStorage fs("clouddetection.xml", cv::FileStorage::WRITE);
fs << "format" << 3;
}
Vec3b green(0, 255, 0), blue(255, 0, 0);
// 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 response = svm->predict(sampleMat);
if (response == 1)
image.at
else if (response == -1)
image.at
}
// Show the training data
int thickness = -1;
int lineType = 8;
circle(image, Point(501, 10), 5, Scalar(0, 0, 0), thickness, lineType);
circle(image, Point(255, 10), 5, Scalar(255, 255, 255), thickness, lineType);
circle(image, Point(501, 255), 5, Scalar(255, 255, 255), thickness, lineType);
circle(image, Point(10, 501), 5, Scalar(255, 255, 255), thickness, lineType);
// Show support vectors
thickness = 2;
lineType = 8;
Mat sv = svm->getSupportVectors();
for (int i = 0; i < sv.rows; ++i)
{
const float* v = sv.ptr
circle(image, Point((int)v[0], (int)v[1]), 6, Scalar(128, 128, 128), thickness, lineType);
}
float testData[1][2] = { 501, 10 };
Mat testDataMat(1, 2, CV_32FC1, testData); Mat response;
cv::FileStorage read("clouddetection.xml", cv::FileStorage::READ);
auto rtrees2 = cv::ml::RTrees::create();
rtrees2->read(read.root());
svm->predict(testDataMat,response);
cout << response.col(0).row(0) << endl;
imwrite("result.png", image); // save the image
imshow("SVM Simple Example", image); // show it to the user
waitKey(0);
}
第一次写博客,轻拍。