EmguCV中SVM的实现

关于SVM的介绍看这里http://blog.csdn.net/qq_22033759/article/details/48348251
最终的运行图如下:
EmguCV中SVM的实现_第1张图片

上代码吧;

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Image<Bgr, byte> img = new Image<Bgr, byte>(512, 512);
            SVM svm = new SVM();     
            svm.SetKernel(SVM.SvmKernelType.Linear);
            svm.Type = SVM.SvmType.CSvc;
            svm.TermCriteria = new MCvTermCriteria(1, 1e-6);

            Image<Gray, float> a = new Image<Gray, float>(2,4);

            Image<Gray, int> b = new Image<Gray, int>(4, 1);
            a[0, 0] = new Gray(400);
            a[0, 1] = new Gray(30);
            a[1, 0] = new Gray(255);
            a[1, 1] = new Gray(10);
            a[2, 0] = new Gray(350);
            a[2, 1] = new Gray(255);
            a[3, 0] = new Gray(10);
            a[3, 1] = new Gray(501);

            b[0, 0] = new Gray(1);
            b[0, 1] = new Gray(-1);
            b[0, 2] = new Gray(1);
            b[0, 3] = new Gray(-1);


            TrainData data = new TrainData(a, Emgu.CV.ML.MlEnum.DataLayoutType.RowSample, b);
            svm.Train(data);

            byte[] imgd = img.Bytes;
            for (int i = 0; i < img.Height; i++)
            {
                for (int j = 0; j < img.Width; j++)
                {
                    int k = i * img.Width + j;
                    Image<Gray, float> sample = new Image<Gray, float>(2, 1);
                    sample[0, 0] = new Gray(j);
                    sample[0, 1] = new Gray(i);
                    float res = svm.Predict(sample);
                    if(res==1)
                    {
                        imgd[k * 3] = 0;
                        imgd[k * 3 + 1] = 255;
                        imgd[k * 3 + 2] = 0;
                    }
                    else if(res==-1)
                    {
                        imgd[k * 3] = 255;
                        imgd[k * 3 + 1] = 0;
                        imgd[k * 3 + 2] = 0;
                    }
                }
            }
            img.Bytes = imgd;
            CvInvoke.Circle(img, new Point(400, 30), 2, new MCvScalar(0, 100, 0), 2);
            CvInvoke.Circle(img, new Point(255, 10), 2, new MCvScalar(100, 0, 0), 2);
            CvInvoke.Circle(img, new Point(350, 255), 2, new MCvScalar(0, 100, 0), 2);
            CvInvoke.Circle(img, new Point(10, 501), 2, new MCvScalar(100, 0, 0), 2);

            imageBox1.Image = img;
        }
    }

你可能感兴趣的:(SVM,EmguCV)