Example #1
0
      public void TestRTreesLetterRecognition()
      {
         Matrix<float> data, response;
         ReadLetterRecognitionData(out data, out response);

         int trainingSampleCount = (int) (data.Rows * 0.8);

         Matrix<Byte> varType = new Matrix<byte>(data.Cols + 1, 1);
         varType.SetValue((byte) MlEnum.VarType.Numerical); //the data is numerical
         varType[data.Cols, 0] = (byte) MlEnum.VarType.Categorical; //the response is catagorical

         Matrix<byte> sampleIdx = new Matrix<byte>(data.Rows, 1);
         using (Matrix<byte> sampleRows = sampleIdx.GetRows(0, trainingSampleCount, 1))
            sampleRows.SetValue(255);

         using (RTrees forest = new RTrees())
         using (TrainData td = new TrainData(data, MlEnum.DataLayoutType.RowSample, response, null, sampleIdx, null, varType))
         {
            forest.MaxDepth = 10;
            forest.MinSampleCount = 10;
            forest.RegressionAccuracy = 0.0f;
            forest.UseSurrogates = false;
            forest.MaxCategories = 15;
            forest.CalculateVarImportance = true;
            forest.ActiveVarCount = 4;
            forest.TermCriteria = new MCvTermCriteria(100, 0.01f);
            bool success = forest.Train(td);

            if (!success)
               return;
            
            double trainDataCorrectRatio = 0;
            double testDataCorrectRatio = 0;
            for (int i = 0; i < data.Rows; i++)
            {
               using (Matrix<float> sample = data.GetRow(i))
               {
                  double r = forest.Predict(sample, null);
                  r = Math.Abs(r - response[i, 0]);
                  if (r < 1.0e-5)
                  {
                     if (i < trainingSampleCount)
                        trainDataCorrectRatio++;
                     else
                        testDataCorrectRatio++;
                  }
               }
            }

            trainDataCorrectRatio /= trainingSampleCount;
            testDataCorrectRatio /= (data.Rows - trainingSampleCount);

            StringBuilder builder = new StringBuilder("Variable Importance: ");
            /*
            using (Matrix<float> varImportance = forest.VarImportance)
            {
               for (int i = 0; i < varImportance.Cols; i++)
               {
                  builder.AppendFormat("{0} ", varImportance[0, i]);
               }
            }*/

            EmguAssert.WriteLine(String.Format("Prediction accuracy for training data :{0}%", trainDataCorrectRatio * 100));
            EmguAssert.WriteLine(String.Format("Prediction accuracy for test data :{0}%", testDataCorrectRatio * 100));
            EmguAssert.WriteLine(builder.ToString());
         }
      }
Example #2
0
        private void btnTest_Click(object sender, EventArgs e)
        {
            Emgu.CV.ML.RTrees forest = new Emgu.CV.ML.RTrees();
            FileStorage       fsr    = new FileStorage(@"C:\Users\welah\Desktop\testing\forest.xml", FileStorage.Mode.Read);

            forest.Read(fsr.GetRoot());
            int total_pos = 0;
            int total_neg = 0;
            int ann       = 0;

            /*string[] images_paths_pos = Directory.GetFiles(@"D:\uOttawa\Winter 2018\INRIAPerson\INRIAPerson\test_64x128_H96\pos");
             * List<float> xspos = new List<float>();
             * foreach (var image_path in images_paths_pos)
             * {
             *  Image<Bgr, byte> img_original = new Image<Bgr, byte>(image_path);
             *  Image<Bgr, byte> ped = img_original;
             *  ped.ROI = new Rectangle(6,6,64,128);
             *  List<Image<Gray, UInt16>> channels = functionsGets.GetACF(ped);
             *  Matrix<float> s = functionsGets.getMatFromImageList(channels);
             *  float x = Emgu.CV.ML.StatModelExtensions.Predict(tree, s);
             *  xspos.Add(x);
             *  Console.WriteLine(x.ToString());
             *  if (Math.Round(x) == 1)
             *      total_pos++;
             * }
             * string[] images_paths_neg = Directory.GetFiles(@"D:\uOttawa\Winter 2018\INRIAPerson\INRIAPerson\Test\neg");
             * List<float> xsneg = new List<float>();
             * foreach (var image_path in images_paths_neg)
             * {
             *  Image<Bgr, byte> img_original = new Image<Bgr, byte>(image_path);
             *  List<Rectangle> list_bounding_boxes = coreFunctions.getBoundingBoxes(image_path, tbAnnotations.Text);
             *  foreach (var rectangle in list_bounding_boxes)
             *  {
             *      Image<Bgr, byte> neg = img_original;
             *      neg.ROI = rectangle;
             *      if (neg.Width > 64 || neg.Height > 128)
             *      {
             *          neg = neg.Resize(64, 128, Inter.Linear);
             *      }
             *      List<Image<Gray, UInt16>> channels = functionsGets.GetACF(neg);
             *      Matrix<float> s = functionsGets.getMatFromImageList(channels);
             *      float x = Emgu.CV.ML.StatModelExtensions.Predict(tree, s);
             *      xsneg.Add(x);
             *      if (Math.Round(x) == 2)
             *          total_neg++;
             *  }
             * }
             * float avpos = xspos.Average();
             * float maxpos = xspos.Max();
             * float minpos = xspos.Min();
             * float avneg = xsneg.Average();
             * float maxneg = xsneg.Max();
             * float minneg = xsneg.Min();
             *
             * TextWriter tw = new StreamWriter("xpos.txt");
             *
             * foreach (var x in xspos)
             *  tw.WriteLine(x.ToString());
             *
             * tw.Close();
             *
             * TextWriter tw1 = new StreamWriter("xneg.txt");
             *
             * foreach (var x in xsneg)
             *  tw1.WriteLine(x.ToString());
             *
             * tw1.Close();*/

            string[] image_paths = Directory.GetFiles(tbImagesTest.Text);

            foreach (var image_path in image_paths)
            {
                List <Rectangle>  list_rectangles_detected = new List <Rectangle>();
                Image <Bgr, byte> image_original           = new Image <Bgr, byte>(image_path);
                //image_original = image_original.SmoothGaussian(3);
                Image <Bgr, byte> image_temp = image_original.Copy();
                //List<Image<Gray, UInt16>> list_channels_original = functionsGets.GetACF(image_temp);
                float factor        = 1;
                int   total_windows = 0;
                while (true)
                {
                    if (factor * image_original.Width > 64 && factor * image_original.Height > 128)
                    {
                        image_temp = image_original.Copy().Resize(factor, Inter.Linear);
                        //List<Image<Gray, UInt16>> list_channels_original = functionsGets.GetACF(image_temp);
                        //image_temp.Save(tbOutputTest.Text + @"\" + Path.GetFileNameWithoutExtension(image_path) + " " + factor.ToString() + ".jpg");
                        for (int m = 0; m < image_temp.Height - 128; m += 8)
                        {
                            for (int n = 0; n < image_temp.Width - 64; n += 8)
                            {
                                total_windows++;
                                List <Image <Gray, UInt16> > list_channels_window = new List <Image <Gray, UInt16> >();
                                Rectangle         rect = new Rectangle(n, m, 64, 128);
                                Image <Bgr, byte> win  = image_temp.Copy();
                                win.ROI = rect;
                                win     = win.SmoothGaussian(3);
                                list_channels_window = functionsGets.GetACF(win);
                                int counter = 0;
                                //image_temp.Draw(rect, new Bgr(Color.Blue));

                                /*for (int i = 0; i < list_channels_original.Count(); i++)
                                 * {
                                 *  Image<Gray, UInt16> channel = list_channels_original[i];
                                 *  channel.ROI = rect;
                                 *  list_channels_window.Add(channel);
                                 * }*/
                                Matrix <float> s       = functionsGets.getMatFromImageList(list_channels_window);
                                float          x       = forest.Predict(s);
                                double         rounded = Math.Round(x, 2);
                                if (rounded <= 1.05)
                                {
                                    list_rectangles_detected.Add(functionsGets.ScaleRectangleToOriginalImage(rect, factor));
                                    //image_temp.Draw(rect, new Bgr(Color.Red));
                                    total_pos++;
                                }
                                else//if (Math.Round(x) == 2)
                                {
                                    //list_rectangles_detected.Add(functionsGets.ScaleRectangleToOriginalImage(rect, factor));
                                    total_neg++;
                                }
                            }
                        }
                        //image_temp.Save(tbOutputTest.Text + @"\" + Path.GetFileNameWithoutExtension(image_path) + " " + factor.ToString() + ".png");
                        //image_temp = image_original.Resize(factor, Inter.Linear);
                        //image_temp.Save(tbOutputTest.Text + @"\" + Path.GetFileNameWithoutExtension(image_path) + " " + (factor - 0.2).ToString() + ".jpg");
                        //image_temp = image_original.Resize(factor, Inter.Linear);
                        //image_temp = image_temp.Resize(factor, Inter.Linear);
                        //image_temp.Save(tbOutputTest.Text + @"\" + Path.GetFileNameWithoutExtension(image_path) + " " + (factor - 0.2).ToString() + ".jpg");
                    }
                    else
                    {
                        break;
                    }
                    factor = factor - (float)(0.2);
                }
                Emgu.CV.Util.VectorOfRect vec = new VectorOfRect();
                vec.Push(list_rectangles_detected.ToArray());
                CvInvoke.GroupRectangles(vec, 1, 0.2);
                vec = functionsGets.RemoveContainedRects(vec);
                for (int i = 0; i < vec.Size; i++)
                {
                    image_original.Draw(vec[i], new Bgr(Color.Red));
                }
                image_original.Save(tbOutputTest.Text + @"\" + Path.GetFileName(image_path));
            }
        }