opencv学习笔记-openCV2与opencv3机器学习库MLL

来源:互联网 发布:win10优化版 编辑:程序博客网 时间:2024/05/21 08:42

参考:http://www.aiuxian.com/article/p-620963.html

           http://blog.csdn.net/lifeitengup/article/details/8866078

opencv2机器学习库MLL

  1. #include <iostream>  
  2. #include <opencv2/core/core.hpp>  
  3. #include <opencv2/highgui/highgui.hpp>  
  4. #include <opencv2/ml/ml.hpp>  
  5.   
  6. #define NTRAINING_SAMPLES   100         // Number of training samples per class  
  7. #define FRAC_LINEAR_SEP     0.9f        // Fraction of samples which compose the linear separable part  
  8.   
  9. using namespace cv;  
  10. using namespace std;  
  11.   
  12. void help()  
  13. {  
  14.     cout<< "\n--------------------------------------------------------------------------" << endl  
  15.         << "This program shows Support Vector Machines for Non-Linearly Separable Data. " << endl  
  16.         << "Usage:"                                                               << endl  
  17.         << "./non_linear_svms" << endl  
  18.         << "--------------------------------------------------------------------------"   << endl  
  19.         << endl;  
  20. }  
  21.   
  22. int main()  
  23. {  
  24.     help();  
  25.   
  26.     // Data for visual representation  
  27.     const int WIDTH = 512, HEIGHT = 512;  
  28.     Mat I = Mat::zeros(HEIGHT, WIDTH, CV_8UC3);  
  29.   
  30.     //--------------------- 1. Set up training data randomly ---------------------------------------  
  31.     Mat trainData(2*NTRAINING_SAMPLES, 2, CV_32FC1);  
  32.     Mat labels   (2*NTRAINING_SAMPLES, 1, CV_32FC1);  
  33.       
  34.     RNG rng(100); // Random value generation class  
  35.   
  36.     // Set up the linearly separable part of the training data  
  37.     int nLinearSamples = (int) (FRAC_LINEAR_SEP * NTRAINING_SAMPLES);  
  38.   
  39.     // Generate random points for the class 1  
  40.     Mat trainClass = trainData.rowRange(0, nLinearSamples);  
  41.     // The x coordinate of the points is in [0, 0.4)  
  42.     Mat c = trainClass.colRange(0, 1);  
  43.     rng.fill(c, RNG::UNIFORM, Scalar(1), Scalar(0.4 * WIDTH));  
  44.     // The y coordinate of the points is in [0, 1)  
  45.     c = trainClass.colRange(1,2);  
  46.     rng.fill(c, RNG::UNIFORM, Scalar(1), Scalar(HEIGHT));  
  47.   
  48.     // Generate random points for the class 2  
  49.     trainClass = trainData.rowRange(2*NTRAINING_SAMPLES-nLinearSamples, 2*NTRAINING_SAMPLES);  
  50.     // The x coordinate of the points is in [0.6, 1]  
  51.     c = trainClass.colRange(0 , 1);   
  52.     rng.fill(c, RNG::UNIFORM, Scalar(0.6*WIDTH), Scalar(WIDTH));  
  53.     // The y coordinate of the points is in [0, 1)  
  54.     c = trainClass.colRange(1,2);  
  55.     rng.fill(c, RNG::UNIFORM, Scalar(1), Scalar(HEIGHT));  
  56.   
  57.     //------------------ Set up the non-linearly separable part of the training data ---------------  
  58.   
  59.     // Generate random points for the classes 1 and 2  
  60.     trainClass = trainData.rowRange(  nLinearSamples, 2*NTRAINING_SAMPLES-nLinearSamples);  
  61.     // The x coordinate of the points is in [0.4, 0.6)  
  62.     c = trainClass.colRange(0,1);  
  63.     rng.fill(c, RNG::UNIFORM, Scalar(0.4*WIDTH), Scalar(0.6*WIDTH));   
  64.     // The y coordinate of the points is in [0, 1)  
  65.     c = trainClass.colRange(1,2);  
  66.     rng.fill(c, RNG::UNIFORM, Scalar(1), Scalar(HEIGHT));  
  67.       
  68.     //------------------------- Set up the labels for the classes ---------------------------------  
  69.     labels.rowRange(                0,   NTRAINING_SAMPLES).setTo(1);  // Class 1  
  70.     labels.rowRange(NTRAINING_SAMPLES, 2*NTRAINING_SAMPLES).setTo(2);  // Class 2  
  71.   
  72.     //------------------------ 2. Set up the support vector machines parameters --------------------  
  73.     CvSVMParams params;  
  74.     params.svm_type    = SVM::C_SVC;  
  75.     params.C           = 0.1;  
  76.     params.kernel_type = SVM::LINEAR;  
  77.     params.term_crit   = TermCriteria(CV_TERMCRIT_ITER, (int)1e7, 1e-6);  
  78.   
  79.     //------------------------ 3. Train the svm ----------------------------------------------------  
  80.     cout << "Starting training process" << endl;  
  81.     CvSVM svm;  
  82.     svm.train(trainData, labels, Mat(), Mat(), params);  
  83.     cout << "Finished training process" << endl;  
  84.       
  85.     //------------------------ 4. Show the decision regions ----------------------------------------  
  86.     Vec3b green(0,100,0), blue (100,0,0);  
  87.     for (int i = 0; i < I.rows; ++i)  
  88.         for (int j = 0; j < I.cols; ++j)  
  89.         {  
  90.             Mat sampleMat = (Mat_<float>(1,2) << i, j);  
  91.             float response = svm.predict(sampleMat);  
  92.   
  93.             if      (response == 1)    I.at<Vec3b>(j, i)  = green;  
  94.             else if (response == 2)    I.at<Vec3b>(j, i)  = blue;  
  95.         }  
  96.   
  97.     //----------------------- 5. Show the training data --------------------------------------------  
  98.     int thick = -1;  
  99.     int lineType = 8;  
  100.     float px, py;  
  101.     // Class 1  
  102.     for (int i = 0; i < NTRAINING_SAMPLES; ++i)  
  103.     {  
  104.         px = trainData.at<float>(i,0);  
  105.         py = trainData.at<float>(i,1);  
  106.         circle(I, Point( (int) px,  (int) py ), 3, Scalar(0, 255, 0), thick, lineType);  
  107.     }  
  108.     // Class 2  
  109.     for (int i = NTRAINING_SAMPLES; i <2*NTRAINING_SAMPLES; ++i)  
  110.     {  
  111.         px = trainData.at<float>(i,0);  
  112.         py = trainData.at<float>(i,1);  
  113.         circle(I, Point( (int) px, (int) py ), 3, Scalar(255, 0, 0), thick, lineType);  
  114.     }  
  115.   
  116.     //------------------------- 6. Show support vectors --------------------------------------------  
  117.     thick = 2;  
  118.     lineType  = 8;  
  119.     int x     = svm.get_support_vector_count();  
  120.   
  121.     for (int i = 0; i < x; ++i)  
  122.     {  
  123.         const float* v = svm.get_support_vector(i);  
  124.         circle( I,  Point( (int) v[0], (int) v[1]), 6, Scalar(128, 128, 128), thick, lineType);  
  125.     }  
  126.   
  127.     imwrite("result.png", I);                      // save the Image  
  128.     imshow("SVM for Non-Linear Training Data", I); // show it to the user  
  129.     waitKey(0);  
  130. }  

opencv3 svm非线性分类 


  1. #include "opencv2/opencv.hpp"  
  2. #include "opencv2/imgproc.hpp"  
  3. #include "opencv2/highgui.hpp"  
  4. #include "opencv2/ml.hpp"  
  5.   
  6. using namespace cv;  
  7. using namespace cv::ml;  
  8.   
  9. int main(intchar**)  
  10. {  
  11.     int width = 512, height = 512;  
  12.     Mat image = Mat::zeros(height, width, CV_8UC3);  //创建窗口可视化  
  13.   
  14.     // 设置训练数据  
  15.     int labels[10] = { 1, -1, 1, 1,-1,1,-1,1,-1,-1 };  
  16.     Mat labelsMat(10, 1, CV_32SC1, labels);  
  17.   
  18.     float trainingData[10][2] = { { 501, 150 }, { 255, 10 }, { 501, 255 }, { 10, 501 }, { 25, 80 },  
  19.     { 150, 300 }, { 77, 200 } , { 300, 300 } , { 45, 250 } , { 200, 200 } };  
  20.     Mat trainingDataMat(10, 2, CV_32FC1, trainingData);  
  21.   
  22.     // 创建分类器并设置参数  
  23.     Ptr<SVM> model =SVM::create();  
  24.     model->setType(SVM::C_SVC);  
  25.     model->setKernel(SVM::LINEAR);  //核函数  
  26.   
  27.     //设置训练数据  
  28.     Ptr<TrainData> tData =TrainData::create(trainingDataMat, ROW_SAMPLE, labelsMat);  
  29.   
  30.     // 训练分类器  
  31.     model->train(tData);  
  32.   
  33.     Vec3b green(0, 255, 0), blue(255, 0, 0);  
  34.     // Show the decision regions given by the SVM  
  35.     for (int i = 0; i < image.rows; ++i)  
  36.     for (int j = 0; j < image.cols; ++j)  
  37.     {  
  38.         Mat sampleMat = (Mat_<float>(1, 2) << j, i);  //生成测试数据  
  39.         float response = model->predict(sampleMat);  //进行预测,返回1或-1  
  40.   
  41.         if (response == 1)  
  42.             image.at<Vec3b>(i, j) = green;  
  43.         else if (response == -1)  
  44.             image.at<Vec3b>(i, j) = blue;  
  45.     }  
  46.   
  47.     // 显示训练数据  
  48.     int thickness = -1;  
  49.     int lineType = 8;  
  50.     Scalar c1 = Scalar::all(0); //标记为1的显示成黑点  
  51.     Scalar c2 = Scalar::all(255); //标记成-1的显示成白点  
  52.     //绘图时,先宽后高,对应先列后行  
  53.     for (int i = 0; i < labelsMat.rows; i++)  
  54.     {  
  55.         const float* v = trainingDataMat.ptr<float>(i); //取出每行的头指针  
  56.         Point pt = Point((int)v[0], (int)v[1]);  
  57.         if (labels[i] == 1)  
  58.             circle(image, pt, 5, c1, thickness, lineType);  
  59.         else  
  60.             circle(image, pt, 5, c2, thickness, lineType);  
  61.   
  62.     }  
  63.   
  64.     imshow("SVM Simple Example", image);  
  65.     waitKey(0);  
  66.   
  67. }  

最初,支持向量机(SVM)是构建最优二进制(2类)分类器的技术。 后来该技术扩展到回归和聚类问题。 SVM是基于内核的方法的一部分。 它使用内核函数将特征向量映射到更高维的空间,并在该空间中构建最佳线性鉴别函数或适合训练数据的最优超平面。 在SVM的情况下,内核没有明确定义。 相反,需要定义超空间中任何2个点之间的距离。


解决方案是最优的,这意味着分离超平面与两类的最近特征向量之间的边界(在2类分类器的情况下)是最大的。 最靠近超平面的特征向量称为支持向量,这意味着其他向量的位置不会影响超平面(决策函数)。 

OpenCV3 SVM是基于 [LibSVM]的。

[Burges98]
  1. Burges. A tutorial on support vector machines for pattern recognition, Knowledge Discovery and Data Mining 2(2), 1998 (available online at http://citeseer.ist.psu.edu/burges98tutorial.html)
[LibSVM](1, 2) C.-C. Chang and C.-J. Lin. LIBSVM: a library for support vector machines, ACM Transactions on Intelligent Systems and Technology, 2:27:1–27:27, 2011. (http://www.csie.ntu.edu.tw/~cjlin/papers/libsvm.pdf)


0 0