public void GetDefaultName() { using (var model = SVM.Create()) { Assert.Equal("opencv_ml_svm", model.GetDefaultName()); } }
public void RunTest() { float[,] trainFeaturesData = { { 0, 0 }, { 0, 100 }, { 100, 0 }, { 100, 100 }, }; var trainFeatures = new Mat(4, 2, MatType.CV_32F, trainFeaturesData); int[] trainLabelsData = { +1, -1, +1, -1 }; var trainLabels = new Mat(4, 1, MatType.CV_32S, trainLabelsData); var model = SVM.Create(); model.Type = SVM.Types.CSvc; model.KernelType = SVM.KernelTypes.Linear; model.TermCriteria = new TermCriteria(CriteriaType.MaxIter, 100, 1e-6); model.Train(trainFeatures, SampleTypes.RowSample, trainLabels); float[] testFeatureData = { 90, 90 }; var testFeature = new Mat(1, 2, MatType.CV_32F, testFeatureData); var detectedClass = (int)model.Predict(testFeature); Assert.AreEqual(-1, detectedClass); }
public void SaveLoadTest() { float[,] trainFeaturesData = { { 0, 0 }, { 0, 100 }, { 100, 0 }, { 100, 100 }, }; var trainFeatures = new Mat(4, 2, MatType.CV_32F, trainFeaturesData); int[] trainLabelsData = { +1, -1, +1, -1 }; var trainLabels = new Mat(4, 1, MatType.CV_32S, trainLabelsData); const string fileName = "svm.yml"; if (File.Exists(fileName)) { File.Delete(fileName); } using (var model = SVM.Create()) { model.Type = SVM.Types.CSvc; model.KernelType = SVM.KernelTypes.Linear; model.TermCriteria = new TermCriteria(CriteriaTypes.MaxIter, 100, 1e-6); model.Train(trainFeatures, SampleTypes.RowSample, trainLabels); model.Save(fileName); } Assert.True(File.Exists(fileName)); string content = File.ReadAllText(fileName); //Console.WriteLine(content); //Assert.DoesNotThrow using (var model2 = SVM.Load(fileName)) { GC.KeepAlive(model2); } using (var model2 = SVM.LoadFromString(content)) { GC.KeepAlive(model2); } using (var fs = new FileStorage(fileName, FileStorage.Modes.Read)) using (var model2 = SVM.Create()) { var node = fs["opencv_ml_svm"]; Assert.NotNull(node); #pragma warning disable CS8604 model2.Read(node); #pragma warning restore CS8604 } }
//设置SVM对图片进行训练 public static bool Train(Mat samples, Mat responses) { svm = SVM.Create(); svm.Type = SVM.Types.CSvc; svm.KernelType = SVM.KernelTypes.Linear; svm.TermCriteria = new TermCriteria(CriteriaType.MaxIter, 10000, 1e-10); IsReady = true; return(svm.Train(samples, SampleTypes.RowSample, responses)); }
public static SVMClassifier Create(List <ImageFeatures> trainingData) { var svm = SVM.Create(); svm.Type = SVM.Types.CSvc; svm.KernelType = SVM.KernelTypes.Rbf; svm.TermCriteria = TermCriteria.Both(maxCount: 1000, epsilon: 0.000001); svm.Gamma = 100.0; svm.C = 1.0; svm.Train(trainingData.ToTrainingMat(), SampleTypes.RowSample, trainingData.ToResponseMat()); return(new SVMClassifier(svm)); }
//分类文件与标签,参数为文件列表与标签结构体 public static bool Train(List <SVMFileInfo> file) { svm = SVM.Create(); svm.Type = SVM.Types.CSvc; svm.KernelType = SVM.KernelTypes.Linear; svm.TermCriteria = new TermCriteria(CriteriaType.MaxIter, 1000, 1e-10); CharCategorySVM.IsReady = true; Mat samples = new Mat(); //特征矩阵 Mat responses = new Mat(); //标签矩阵 foreach (SVMFileInfo fi in file) { List <string> fileNames = FileIO.OpenFile(fi.FilePath); //读到需要的文件路径列表 if (fileNames == null || fileNames.Count <= 0) //如果文件夹中一个图片都没有就返回 { return(false); } //处理每个文件 foreach (string s in fileNames) { Mat matImg = new Mat(s, ImreadModes.Grayscale); //get image Cv2.Threshold(matImg, matImg, 0, 255, ThresholdTypes.Otsu); //二值化 float[] feature = ComputeHogDescriptors(matImg); //提取图片HOG特征 samples.PushBack(TypeConvert.Float2Mat(feature)); //向特征矩阵中添加一行特征向量 responses.PushBack(TypeConvert.Int2Mat(fi.Label)); //向标签矩阵中添加一行标签 } } samples.ConvertTo(samples, MatType.CV_32FC1); //训练数据的格式必须是32位浮点型 if (svm.Train(samples, SampleTypes.RowSample, responses)) { return(true); } return(false); }
public static void Run() { Console.WriteLine("NuSVMDemo"); var class1 = DemoHelper.GenerateClass(0, 0.1, 0.1, 50); var class2 = DemoHelper.GenerateClass(1, 0.8, 0.8, 50); var trainData = class1.Concat(class2); var trainer = SVM.Create(new NuSupportVectorClassification(0.1), new RbfKernel(0.5)); var model = trainer.Train(trainData.Select(p => Tuple.Create(p.ToArray(), p.Label))); var x = new Point(0.9, 0.9).ToArray(); var resx = model.Predict(x); Console.WriteLine(resx); var y = new Point(0.0, 0.0).ToArray(); var resy = model.Predict(y); Console.WriteLine(resy); }
public static void Run() { Console.WriteLine("EpsSVRDemo"); var rnd = new Random(); var trainData = DemoHelper.Range(-10.0, 10.01, 0.1).Select(val => new { X = val, Y = DemoHelper.Sinc(val) + (rnd.NextDouble() - 0.5) / 4 }); var trainer = SVM.Create(new EpsilonSupportVectorRegression(1.0, 0.1), new RbfKernel(0.5)); var model = trainer.Train(trainData.Select(p => Tuple.Create(p.X.ToArray(), p.Y))); foreach (var item in DemoHelper.Range(-1.0, 1.01, 0.1)) { var x = item.ToArray(); var yPred = model.Predict(x); var yReal = DemoHelper.Sinc(item); Console.WriteLine("x: {0}", item); Console.WriteLine("y_real: {0}", yReal); Console.WriteLine("y_pred: {0}", yPred); Console.WriteLine(); } }
public static void Run() { Console.WriteLine("OneClassDemo"); var trainData = DemoHelper.GenerateClass(0, 0.5, 0.5, 100); var trainer = SVM.Create(new OneClass(0.5), new RbfKernel(0.5)); var model = trainer.Train(trainData.Select(p => p.ToArray())); var x = new Point(0.9, 0.9).ToArray(); var resx = model.Predict(x); Console.WriteLine(resx); var y = new Point(0.5, 0.5).ToArray(); var resy = model.Predict(y); Console.WriteLine(resy); var z = new Point(0.45, 0.45).ToArray(); var resz = model.Predict(z); Console.WriteLine(resz); }
public override void RunTest() { // Training data var points = new Point2f[500]; var responses = new int[points.Length]; var rand = new Random(); for (int i = 0; i < responses.Length; i++) { float x = rand.Next(0, 300); float y = rand.Next(0, 300); points[i] = new Point2f(x, y); responses[i] = (y > Function(x)) ? 1 : 2; } // Show training data and f(x) using (Mat pointsPlot = Mat.Zeros(300, 300, MatType.CV_8UC3)) { for (int i = 0; i < points.Length; i++) { int x = (int)points[i].X; int y = (int)(300 - points[i].Y); int res = responses[i]; Scalar color = (res == 1) ? Scalar.Red : Scalar.GreenYellow; pointsPlot.Circle(x, y, 2, color, -1); } // f(x) for (int x = 1; x < 300; x++) { int y1 = (int)(300 - Function(x - 1)); int y2 = (int)(300 - Function(x)); pointsPlot.Line(x - 1, y1, x, y2, Scalar.LightBlue, 1); } Window.ShowImages(pointsPlot); } // Train var dataMat = new Mat(points.Length, 2, MatType.CV_32FC1, points); var resMat = new Mat(responses.Length, 1, MatType.CV_32SC1, responses); using var svm = SVM.Create(); // normalize data dataMat /= 300.0; // SVM parameters svm.Type = SVM.Types.CSvc; svm.KernelType = SVM.KernelTypes.Rbf; svm.TermCriteria = TermCriteria.Both(1000, 0.000001); svm.Degree = 100.0; svm.Gamma = 100.0; svm.Coef0 = 1.0; svm.C = 1.0; svm.Nu = 0.5; svm.P = 0.1; svm.Train(dataMat, SampleTypes.RowSample, resMat); // Predict for each 300x300 pixel using Mat retPlot = Mat.Zeros(300, 300, MatType.CV_8UC3); for (int x = 0; x < 300; x++) { for (int y = 0; y < 300; y++) { float[] sample = { x / 300f, y / 300f }; var sampleMat = new Mat(1, 2, MatType.CV_32FC1, sample); int ret = (int)svm.Predict(sampleMat); var plotRect = new Rect(x, 300 - y, 1, 1); if (ret == 1) { retPlot.Rectangle(plotRect, Scalar.Red); } else if (ret == 2) { retPlot.Rectangle(plotRect, Scalar.GreenYellow); } } } Window.ShowImages(retPlot); }
static Plate_SVM() { svm = SVM.Create(); svm.Type = SVM.Types.CSvc; svm.KernelType = SVM.KernelTypes.Linear; }
/// <summary> /// train model /// </summary> static void Train() { //load catalog var paras = File.ReadAllLines("JPEGImages\\SVM_Train.txt"); var imgPath = new List <string>(); var imgCatg = new List <int>(); var nImgCnt = paras.Length; foreach (var i in paras) { var temp = i.Split(':'); imgPath.Add(temp[1]); imgCatg.Add(Convert.ToInt32(temp[0])); } //create HOG var hog = new HOGDescriptor(new Size(64, 64), new Size(16, 16), new Size(8, 8), new Size(8, 8)); Mat data = Mat.Zeros(nImgCnt, hog.GetDescriptorSize(), MatType.CV_32FC1); Mat res = Mat.Zeros(nImgCnt, 1, MatType.CV_32SC1); for (var z = 0; z < nImgCnt; z++) { //load img Mat src = Cv2.ImRead(imgPath[z], ImreadModes.GrayScale); Console.WriteLine($"Processing: {Path.GetFileNameWithoutExtension(imgPath[z])}"); //resize to 64*64 Cv2.Resize(src, src, new Size(64, 64)); //threshold src = src.Threshold(200, 255, ThresholdTypes.Binary); //center image MoveToCenter(src); //computer descriptors var descriptors = hog.Compute(src, new Size(1, 1), new Size(0, 0)); for (var i = 0; i < descriptors.Length; i++) { data.Set(z, i, descriptors[i]); } res.Set(z, 0, imgCatg[z]); src.Release(); } Console.WriteLine("Start training"); //create svm var svm = SVM.Create(); svm.TermCriteria = new TermCriteria(CriteriaType.Eps, 1000, float.Epsilon); svm.Type = SVM.Types.CSvc; svm.KernelType = SVM.KernelTypes.Rbf; svm.Degree = 10; svm.Gamma = 0.09; svm.Coef0 = 1; svm.C = 10; svm.Nu = 0.5; svm.P = 1; //training svm.Train(data, SampleTypes.RowSample, res); //save result svm.Save("SVM_RESULT.xml"); }