static Tuple <bool, int, int> predict_color_and_size(Bgr rgb, Size sz)
        {
            bool retb     = false;
            int  color_id = -1;
            int  size_id  = -1;

            try
            {
                string dir = System.IO.Path.GetDirectoryName(Program.getCurrentExeFilename());
                using (SVM model = new SVM())
                {
                    model.Load(System.IO.Path.Combine(dir, "traindata", "iPhone_color.xml"));
                    Matrix <float> test = new Matrix <float>(1, 3);
                    test[0, 0] = (float)rgb.Red;
                    test[0, 1] = (float)rgb.Green;
                    test[0, 2] = (float)rgb.Blue;
                    color_id   = (int)model.Predict(test);
                    Program.logIt($"prodict: colorID={color_id}");
                }
                using (SVM model = new SVM())
                {
                    model.Load(System.IO.Path.Combine(dir, "traindata", "iPhone_size.xml"));
                    //model.Load(@"traindata/iPhone_size.xml");
                    Matrix <float> test = new Matrix <float>(1, 2);
                    test[0, 0] = (float)sz.Width;
                    test[0, 1] = (float)sz.Height;
                    size_id    = (int)model.Predict(test);
                    Program.logIt($"prodict: sizeID={size_id}");
                }
                retb = true;
            }
            catch (Exception) { }
            return(new Tuple <bool, int, int>(retb, color_id, size_id));
        }
Example #2
0
        static void test(string fn)
        {
            //string fn = @"C:\projects\local\GradeChecker\GradeChecker\bin\Debug\test.json";

            try
            {
                var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
                List <Dictionary <string, object> > datas = jss.Deserialize <List <Dictionary <string, object> > >(System.IO.File.ReadAllText(fn));
                string[]       keys = testMQ.Properties.Resources.keys.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                Matrix <float> data;
                Matrix <int>   response;
                load_data(datas.ToArray(), keys, out data, out response);
                using (SVM model = new SVM())
                {
                    model.Load("svm.xml");
                    for (int i = 0; i < data.Rows; i++)
                    {
                        float r = model.Predict(data.GetRow(i));
                        Dictionary <string, object> d = datas[i];
                        System.Console.WriteLine($"imei={d["imei"]}, VZW={d["VZW"]}, FD={grade_level[(int)r]}");
                    }
                }
            }
            catch (Exception) { }
        }
Example #3
0
        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
                }
        }
    public FaceEmotionsClassifier(string modelFilepath)
    {
        classifier = new SVM();
        classifier.Load(modelFilepath);

        classifier.C     = 2.67f;
        classifier.Gamma = 5.383f;
        classifier.Type  = SVM.SvmType.CSvc;
        classifier.SetKernel(SVM.SvmKernelType.Linear);
    }
Example #5
0
 //加载svm模型,也就是哪个xml文件
 public static void Load(string fileName)
 {
     try
     {
         svm     = SVM.Load(fileName);
         IsReady = true;
     }
     catch (Exception)
     {
         throw new Exception("ERROR:请检查路径是否正确");
     }
 }
Example #6
0
 //加载字符识别库
 public static void Load(string fileName)
 {
     try
     {
         svm     = SVM.Load(fileName);
         IsReady = true;
     }
     catch (Exception)
     {
         throw new Exception("字符识别库加载异常,请检查存放路路径");
     }
 }
Example #7
0
        private static float GetOutline_LoadConfig(Image <Bgr, byte> src)
        {
            SVM svm = new SVM();

            svm.Load("4.xml");
            //////////////////////////////////////////////////////////////////参数设定
            Rectangle rc = new Rectangle();

            rc.Width  = 28;
            rc.Height = 28;//tuxaing daxiao

            Rectangle rc1 = new Rectangle();

            rc1.Width  = 14;
            rc1.Height = 14;//bloke

            Rectangle rc2 = new Rectangle();

            rc2.Width  = 7;
            rc2.Height = 7;

            Rectangle rc3 = new Rectangle();

            rc3.Width  = 7;
            rc3.Height = 7;

            ///////////////设置参数//////////////////////////////////////////////
            Size r1 = new Size();

            r1.Width  = 1;
            r1.Height = 1;
            Size r2 = new Size();

            r2.Width  = 0;
            r2.Height = 0;

            HOGDescriptor hog = new HOGDescriptor(rc.Size, rc1.Size, rc2.Size, rc3.Size, 9, 1, -1, 0.2, false);

            float[]   yy = new float[1000000];
            Rectangle bb = new Rectangle();

            bb.Width  = 28;
            bb.Height = 28;
            Image <Bgr, byte> yyy = new Image <Bgr, byte>(bb.Size);

            CvInvoke.cvResize(src, yyy, INTER.CV_INTER_LINEAR);
            yy = hog.Compute(yyy, r1, r2, null);
            Matrix <float> match  = new Matrix <float>(yy);
            float          result = svm.Predict(match);

            return(result);
        }
Example #8
0
        static void Main(string[] args)
        {
            //training
            Train();


            //predict:
            Console.WriteLine("Load svm model");

            var svm = SVM.Load("SVM_RESULT.xml");
            var cnt = 0;

            Console.WriteLine("Start prediction process");
            var starttime = DateTime.Now;

            //predict videos:

            //foreach (var i in Directory.GetFiles("Videos", "*.mp4"))
            //{
            //    cnt++;
            //    var start = DateTime.Now;
            //    var res = PredictV(svm, i);
            //    Console.WriteLine($"{Path.GetFileName(i)} - Time cost: {(DateTime.Now - start).TotalMilliseconds} ms");
            //    Console.WriteLine("Results:");
            //    for (var j = 1; j < 10; j++)
            //    {
            //        Console.WriteLine($"{j} - confidence: {res.Count(k => k == j) * 100f / res.Count} %");
            //    }
            //}

            //predict imgs
            foreach (var i in Directory.GetFiles("JPEGImages", "*- Copy.jpg")) //test cases
            {
                cnt++;
                var start = DateTime.Now;
                Console.WriteLine($"{Path.GetFileName(i)} - Result: {Predict(svm, Cv2.ImRead(i, ImreadModes.GrayScale))}, time cost: {(DateTime.Now - start).TotalMilliseconds} ms");
            }
            Console.WriteLine($"Average speed: {cnt / (DateTime.Now - starttime).TotalSeconds} per second");


            //extract video to images:

            //foreach (var i in Directory.GetFiles("Videos"))
            //{
            //    Console.WriteLine($"Processing: {Path.GetFileName(i)}");
            //    ExportToJpg(i);
            //}

            Console.WriteLine("Finished");
            Console.ReadKey();
            return;
        }
Example #9
0
        public static int predict_test(double height, double width)
        {
            int ret = 0;

            using (SVM model = new SVM())
            {
                model.Load(@"data\iphone_size_svm.xml");
                Matrix <float> data = new Matrix <float>(1, 2);
                data[0, 0] = (float)height;
                data[0, 1] = (float)width;
                float r = model.Predict(data);
                ret = (int)r;
            }
            return(ret);
        }
Example #10
0
 public static void Load(string fileName)
 {
     svm = SVM.Load(fileName);
 }
        static bool handle_motion_V2(Image <Bgr, Byte> frane, Image <Gray, Byte> bg, int idx)
        {
            bool device_in_place = false;
            //Rectangle r = new Rectangle(196, 665, 269, 628);
            Rectangle          r     = new Rectangle(334, 774, 452, 1016);
            Image <Bgr, Byte>  img1  = frane.Copy(r);
            Image <Gray, Byte> imgg  = frane.Mat.ToImage <Gray, Byte>().Copy(r);
            Image <Gray, Byte> imgbg = bg.Copy(r);

            imgg = imgg.AbsDiff(imgbg);
            Gray g = imgg.GetAverage();

            if (g.MCvScalar.V0 > 13)
            {
                Rectangle sz  = detect_size_old(imgg);
                Bgr       rgb = sample_color(img1);
                Program.logIt($"Device arrival. size: {sz.Size}, color: {rgb} ({g.MCvScalar.V0})");
                // report
                Console.WriteLine($"Raw Data: size={sz.Size}, color={rgb}");
                if (sz.Size.Width > 430)
                {
                    // it is plus mode
                    Console.WriteLine($"sizeID=2");
                }
                else if (sz.Size.Width < 400)
                {
                    // it is plus mode
                    Console.WriteLine($"sizeID=1");
                }
                else
                {
                    // error. unknown size
                    Console.WriteLine($"sizeID=-1");
                }

                // for color
                string[] color_note = new string[]
                {
                    "NA",
                    "Blue (iPhone XR)",
                    "Gray (iPhone 8 Plus)",
                    "Red (iPhone 8 Plus)",
                    "Silver (iPhone 8/iPhone 8 Plus)",
                };

                try
                {
                    Console.WriteLine($"r={rgb.Red}");
                    Console.WriteLine($"g={rgb.Green}");
                    Console.WriteLine($"b={rgb.Blue}");
                    using (SVM model = new SVM())
                    {
                        model.Load(@"traindata/iPhone_color.xml");
                        Matrix <float> test = new Matrix <float>(1, 3);
                        test[0, 0] = (float)rgb.Red;
                        test[0, 1] = (float)rgb.Green;
                        test[0, 2] = (float)rgb.Blue;
                        int l = (int)model.Predict(test);
                        Console.WriteLine($"colorID={l}");
                        if (l >= 0 && l < color_note.Length)
                        {
                            Console.WriteLine($"colorNote={color_note[l]}");
                        }
                    }
                }
                catch (Exception) { }
                //Console.WriteLine("Enter device model and color:");
                //string info = System.Console.ReadLine();
                //img1.Save($"temp_{info}_2.jpg");
                //imgbg.Save($"temp_{info}_1.jpg");
                //imgg.Save($"temp_{info}_3.jpg");
                //Console.WriteLine($"{info}: size={sz.Size}, color={rgb}");
                //Program.logIt($"{info}: size={sz.Size}, color={rgb}");
                device_in_place = true;
            }
            else
            {
                Program.logIt($"Device removal. ({g.MCvScalar.V0})");
                device_in_place = false;
            }
            return(device_in_place);
        }
        private void button3_Click(object sender, EventArgs e)
        {
            using (SVM model = new SVM())
            {
                float train_SVM_accuracy = 0;
                int   train_time         = 0;
                while (train_SVM_accuracy < 0.98 && train_time < 20)
                {
                    TrainSVM(train_time, ref train_SVM_accuracy);
                    train_time++;
                }

                model.Load("SVM_NOTE.txt");

                Matrix <float> test = new Matrix <float>(1, featureNum);

                float count = 0, count2 = 0;
                float[,] AC = new float[10, 10];
                for (int i = 0; i < testSampleCount; i++)
                {
                    for (int j = 0; j < featureNum; j++)
                    {
                        test.Data[0, j] = sample.Data[i, j];
                    }
                    float response = model.Predict(test);
                    float classSam = sampleClasses[i, 0];

                    /**********************10x10********************/
                    AC[(int)classSam - 1, (int)response - 1]++;
                    richTextBox6.AppendText("(" + i + ")" + "R=" + response + "  C=" + classSam + "\n");
                    if (response == classSam)
                    {
                        count2++;
                    }
                    if (response == 10)
                    {
                        if (classSam == 10)
                        {
                            count++;
                        }
                    }
                    else
                    {
                        if (classSam != 10)
                        {
                            count++;
                        }
                    }
                }

                for (int a = 0; a < 10; a++)
                {
                    for (int b = 0; b < 10; b++)
                    {
                        richTextBox7.AppendText(AC[a, b] + "\t");
                    }
                    richTextBox7.AppendText("\n");
                }

                // model.Save("SVM_NOTE.txt");

                float accuracy  = count / testSampleCount;
                float accuracy2 = count2 / testSampleCount;
                //richTextBox3.Text = "count=" + count;
                richTextBox3.Text = "分兩類準確率=" + accuracy + "   各類別準確率=" + accuracy2;
            }
        }