煤矸石分类项目,提取的煤矸石灰度均值和灰度方差作为特征进行分类,代码如下,使用的二次封装的opencv库,在其他机器上运行将头文件和条件编译宏替换成opencv自己的就可以了
#include "sv.h" #ifdef _DEBUG #pragma comment(lib,"BoxCV100d.lib") #pragma comment(lib,"SvRunTimed.lib") #else #pragma comment(lib,"BoxCV100.lib") #pragma comment(lib,"SvRunTime.lib") #endif using namespace cv; using namespace cv::ml; int main(int argc, char** argv) { int width = 720, height = 720; //三通道可视化窗口 Mat image = Mat::zeros(height, width, CV_8UC3); int labels[11] = { 1,1,1,1,1,1, -1,-1,-1,-1,-1 }; Mat LabelsMat(10, 1, CV_32SC1, labels); float TrainingData[11][2]= { {291.4,252},{115.3,185},{277.7,695},{367.562},{352.4,645},{117.2,203}, {117.2,129},{122.8,112},{116.4,175},{132.5,78},{106.3,125} }; Mat TrainMat(10, 2, CV_32FC1, TrainingData); //创建分类器设置参数 Ptr<SVM> model = SVM::create(); model->setType(SVM::C_SVC); model->setKernel(SVM::LINEAR); //设置训练参数 Ptr<TrainData> tData = TrainData::create(TrainMat, ROW_SAMPLE, LabelsMat); //训练分类器 model->train(tData); Vec3b ColorGreen(0, 255, 0), ColorBlue(255, 0, 0); //显示svm决策边界 for(int i=0;i<image.rows;++i) for (int j = 0; j < image.cols; ++j) { //生成测试数据 Mat SampleMat = (Mat_<float>(1, 2) << j, i); //predict float response = model->predict(SampleMat); if (1 == response) image.at<Vec3b>(i, j) = ColorGreen; else if (-1 == response) image.at<Vec3b>(i, j) = ColorBlue; } //绘图 //显示结果 int thickness = -1; int lineType = 8; //两类结果一个黑色一个白色 Scalar c1 = Scalar::all(0); Scalar c2 = Scalar::all(255); for (int i = 0; i < LabelsMat.rows; ++i) { //取出每行指针 const float* v = TrainMat.ptr<float>(i); Point pt = Point((int)v[0], (int)v[1]); if (1 == labels[i]) circle(image, pt, 5, c1, thickness, lineType); else circle(image, pt, 5, c2, thickness, lineType); } imshow("SVM Simple Example", image); waitKey(); }
结果图
原文:https://www.cnblogs.com/wangtianning1223/p/13552438.html