Ejemplo n.º 1
0
        public float ClassifyImage(Bitmap snapshot)
        {
            var hogMatrix = new Matrix <float>(1, (int)this.hogDescriptor.DescriptorSize);
            var img       = new Image <Bgr, Byte>(snapshot);
            var hog       = hogDescriptor.Compute(img);

            for (var i = 0; i < hogMatrix.Cols; i++)
            {
                hogMatrix[0, i] = hog[i];
            }

            return(svm.Predict(hogMatrix));
        }
Ejemplo n.º 2
0
        public static void compute_hog_test(List <Mat> img_lst, OpenCvSharp.Size size, int lables, string path)
        {
            HOGDescriptor hog = new HOGDescriptor();

            hog.WinSize = size;
            Mat gray = new Mat();

            float[]      descriptors;
            int          descriptors_size = 0;
            StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8);

            for (int i = 0; i < img_lst.Count; i++)// vong lap duyet tung anh
            {
                string line = lables.ToString();
                sw.Write(line);

                Cv2.CvtColor(img_lst[i], gray, ColorConversionCodes.RGB2GRAY);
                descriptors = hog.Compute(gray);

                descriptors_size = descriptors.Length;
                Mat Mat_descriptor = new Mat(descriptors_size, 1, MatType.CV_8UC1);

                for (int a = 0; a < descriptors.Length; a++)
                {
                    Mat_descriptor.Set <float>(a, 0, descriptors[a]);
                    float  value = Mat_descriptor.Get <float>(a, 0);
                    string lines = " " + (a + 1) + ":" + value;
                    sw.Write(lines);
                }
                sw.WriteLine();
            }
            sw.Close();
        }
Ejemplo n.º 3
0
        public float[] GetHog(Image <Bgr, Byte> image, int block_size = 16, int cell_size = 8)
        {
            HOGDescriptor hog = new HOGDescriptor(image.Size, new Size(block_size, block_size), new Size(cell_size, cell_size), new Size(cell_size, cell_size));

            float[] result = hog.Compute(image);
            return(result);
        }
Ejemplo n.º 4
0
        public float[] HOG(ref Image <Gray, Byte> modImg)
        {
            // Square-Root Normalization - compresses the input pixel less than Gamma. Increases accuracy of HOG
            //CvInvoke.Sqrt(newMatrix, newMatrix);
            // make the image 64x128 - recommended for HOG description
            int    h       = modImg.Height;
            double scaleBy = h / 256.0;
            int    width   = (int)((double)modImg.Width / scaleBy);
            int    height  = (int)((double)modImg.Height / scaleBy);

            modImg = modImg.Resize(width, height, Emgu.CV.CvEnum.Inter.Linear);

            /* Compute the Gradient Vector of every pixel, as well as magnitude and direction */
            // apply Sobel by x and y
            Image <Gray, float> sobel = modImg.Sobel(0, 1, 3).Add(modImg.Sobel(1, 0, 3)).AbsDiff(new Gray(0.0));

            modImg = sobel.Convert <Gray, Byte>();

            /* Compute descriptor values */
            HOGDescriptor hog       = new HOGDescriptor();
            Size          WinStride = new Size(18, 18);
            Size          Padding   = new Size(10, 10);

            Point[] locations        = null;
            float[] descriptorValues = hog.Compute(modImg, WinStride, Padding, locations);

            return(descriptorValues);
        }
Ejemplo n.º 5
0
 public float[] CalHog(Image<Bgr, byte> image)
 {
     if (image == null)
     {
         return null;
     }
     return Hog_Descriptor.Compute(image, new Size(1, 1), new Size(0, 0), null);
 }
Ejemplo n.º 6
0
        //HOGDescriptor
        public static float[] ComputeHogDescriptors(Mat image)
        {
            Mat matToHog = image.Resize(HOGWinSize);
            //初始化一个自定义的hog描述子
            HOGDescriptor hog = new HOGDescriptor(HOGWinSize, HOGBlockSize, HOGBlockStride, HOGCellSize, HOGNBits);

            return(hog.Compute(matToHog, new OpenCvSharp.Size(1, 1), new OpenCvSharp.Size(0, 0)));
        }
Ejemplo n.º 7
0
        private void btnTrain_Click(object sender, EventArgs e)
        {
            HOGDescriptor hog = new HOGDescriptor(new Size(36, 36), new Size(36, 36), new Size(6, 6), new Size(6, 6));

            fsPeg = Directory.GetFiles(txtPosPath.Text);
            for (int i = 0; i < fsPeg.Length; i++)
            {
                String             cFileName = txtPosPath.Text + fsPeg[i];
                Image <Bgr, byte>  vImage    = new Image <Bgr, byte>(cFileName);
                Image <Gray, byte> vGray     = vImage.Convert <Gray, byte>();
                float[]            fAttr     = hog.Compute(vGray);
                for (int j = 0; j < fAttr.Length; j++)
                {
                    DataMatrix[i, j] = fAttr[j];
                }
                AttrMatrix[i, 0] = 1;
            }

            fsNeg = Directory.GetFiles(txtNegPath.Text);
            for (int i = 0; i < fsNeg.Length; i++)
            {
                String             cFileName = txtNegPath.Text + fsNeg[i];
                Image <Bgr, byte>  vImage    = new Image <Bgr, byte>(cFileName);
                Image <Gray, byte> vGray     = vImage.Convert <Gray, byte>();
                float[]            fAttr     = hog.Compute(vGray);
                for (int j = 0; j < fAttr.Length; j++)
                {
                    DataMatrix[i, j] = fAttr[j];
                }
                AttrMatrix[i, 0] = 0;
            }

            Emgu.CV.ML.SVM vSVM = new Emgu.CV.ML.SVM();
            vSVM.Type = Emgu.CV.ML.SVM.SvmType.CSvc;
            vSVM.SetKernel(Emgu.CV.ML.SVM.SvmKernelType.Linear);
            vSVM.TermCriteria = new MCvTermCriteria(1000, 0.1);
            TrainData td = new TrainData(DataMatrix, Emgu.CV.ML.MlEnum.DataLayoutType.RowSample, AttrMatrix);
            String    cExportFileName = txtFileName.Text;

            vSVM.Save(cExportFileName);
        }
Ejemplo n.º 8
0
        public static void TrainApertureDetection()
        {
            HOGDescriptor hog = new HOGDescriptor(winSizeAperture, blockSize, blockStride, cellSize, nbins, derivAperture, winSigma, L2HysThreshold, gammaCorrection);

            //Postive samples
            List <float> pos_targets = new List <float>(); List <float[]> pos_features = new List <float[]>();
            {
                string[] files = Directory.EnumerateFiles(@"\users\jie\projects\Intel\data\PSM4-Tx\20160722\Aperture")
                                 .Where(file => file.ToLower().EndsWith(".bmp") || file.ToLower().EndsWith(".jpg"))
                                 .ToArray();

                for (int k = 0; k < files.Length; k++)
                {
                    Emgu.CV.Image <Gray, byte> image = new Emgu.CV.Image <Gray, byte>(files[k]);
                    float[] feature = hog.Compute(image);
                    pos_features.Add(feature);
                    pos_targets.Add(1.0f);
                }
            }

            //Negative samples
            List <float> neg_targets = new List <float>(); List <float[]> neg_features = new List <float[]>();
            {
                string[] files = Directory.EnumerateFiles(@"\users\jie\projects\Intel\data\PSM4-Tx\20160722\ApertureNegative")
                                 .Where(file => file.ToLower().EndsWith(".bmp") || file.ToLower().EndsWith(".jpg"))
                                 .ToArray();

                for (int k = 0; k < files.Length; k++)
                {
                    Emgu.CV.Image <Gray, byte> image = new Emgu.CV.Image <Gray, byte>(files[k]);
                    float[] feature = hog.Compute(image);
                    neg_features.Add(feature);
                    neg_targets.Add(-1.0f);
                }
            }
            List <float> targets = new List <float>(); List <float[]> features = new List <float[]>();

            targets.AddRange(pos_targets); targets.AddRange(neg_targets);
            features.AddRange(pos_features); features.AddRange(neg_features);
            LibSVM.SaveInLibSVMFormat("trainAperture.txt", targets.ToArray(), features.ToArray());
        }
Ejemplo n.º 9
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);
        }
Ejemplo n.º 10
0
        //通过HOG完成对图片特征的提取
        public static float[] ComputeHogDescriptors(Mat image)
        {
            //if(image.Channels()==3)
            //{
            //    image.CvtColor(ColorConversionCodes.BGR2GRAY);
            //}
            Mat           matToHog = image.Resize(HOGWinSize);
            HOGDescriptor hog      = new HOGDescriptor(HOGWinSize,
                                                       HOGBlockSize,
                                                       HOGBlockStride,
                                                       HOGCellSize,
                                                       HOGNBits);

            return(hog.Compute(matToHog, new OpenCvSharp.Size(1, 1), new OpenCvSharp.Size(0, 0)));
        }
Ejemplo n.º 11
0
        public override List <float> GetFeatureVector(TaggedImage data)
        {
            Mat image = data.GetMat();

            Size cellSize    = new Size(image.Cols / _cellCountX, image.Rows / _cellCountY);
            Size blockSize   = new Size(cellSize.Width, cellSize.Height);
            Size blockStride = new Size(cellSize.Width, cellSize.Height);
            Size winSize     = new Size(image.Cols - (image.Cols % cellSize.Width), image.Rows - (image.Rows % cellSize.Height));

            _hog = new HOGDescriptor(winSize, blockSize, blockStride, cellSize);

            float[] result = _hog.Compute(image);

            return(new List <float>(result));
        }
Ejemplo n.º 12
0
        private static Mat computeHogDes(Image <Gray, byte> img, int density = 4, int histSize = 9)
        {
            if (img.Height % density != 0 || img.Width % density != 0)
            {
                img = img.Resize(img.Width - img.Width % density, img.Height - img.Height % density, Emgu.CV.CvEnum.Inter.Linear);
            }
            HOGDescriptor hogd = new HOGDescriptor(img.Size, img.Size, new Size(1, 1),
                                                   new Size(img.Size.Width / density, img.Size.Height / density));

            float[] result = hogd.Compute(img);
            Mat     ret    = new Mat(result.Length, 1, Emgu.CV.CvEnum.DepthType.Cv32F, 1);

            ret.SetTo(result);
            return(ret);
        }
Ejemplo n.º 13
0
        private float classifyShape(Mat shape, CvSVM svm)
        {
            HOGDescriptor hog = new HOGDescriptor();

            hog.WinSize     = new OpenCvSharp.CPlusPlus.Size(32, 32); // Set hog features here: winSize; blockSize; cellSize
            hog.BlockSize   = new OpenCvSharp.CPlusPlus.Size(4, 4);
            hog.CellSize    = new OpenCvSharp.CPlusPlus.Size(4, 4);
            hog.BlockStride = new OpenCvSharp.CPlusPlus.Size(2, 2);
            float[] features = hog.Compute(shape, new OpenCvSharp.CPlusPlus.Size(16, 16), new OpenCvSharp.CPlusPlus.Size(0, 0), null);
            hog.Dispose();
            Mat   featureMat = new Mat(1, features.Length, MatType.CV_32FC1, features);
            float prediction = svm.Predict(featureMat.ToCvMat());

            featureMat.Dispose();
            return(prediction);
        }
Ejemplo n.º 14
0
        //HOG特征提取
        public static float[] ComputeHogDescriptors(Mat image)
        {
            Mat matToHog = image.Resize(HOGWinSize);

            /*  第一个参数:窗口大小          第二个参数:块大小
             *  第三个参数:块的滑动步长      第四个参数:细胞大小
             *  第五个参数:分箱个数n,即每次转动360/n度
             */
            HOGDescriptor hog = new HOGDescriptor(HOGWinSize,
                                                  HOGBlockSize,
                                                  HOGBlockStride,
                                                  HOGCellSize,
                                                  HOGNBits);

            return(hog.Compute(matToHog, new OpenCvSharp.Size(1, 1), new OpenCvSharp.Size(0, 0)));
        }
Ejemplo n.º 15
0
        private void btn_upload_Click(object sender, EventArgs e)
        {
            Image <Bgr, Byte>  img       = null;
            Image <Gray, Byte> newMatrix = null;

            OpenFileDialog fd = new OpenFileDialog();

            fd.Title  = "Select image";
            fd.Filter = "image files (*.jpg)|*.jpg";

            if (fd.ShowDialog() == DialogResult.OK)
            {
                img = new Image <Bgr, Byte>(fd.FileName);
                originalImage.Image = img;
            }

            /* PREPROCESS THE IMAGE - Resizing and Color Normalization */
            newMatrix = img.Convert <Gray, Byte>();
            // Square-Root Normalization - compresses the input pixel less than Gamma. Increases accuracy of HOG
            //CvInvoke.Sqrt(newMatrix, newMatrix);
            // make the image 64x128 - recommended for HOG description
            int    h       = img.Height;
            double scaleBy = h / 256.0;
            int    width   = (int)((double)newMatrix.Width / scaleBy);
            int    height  = (int)((double)newMatrix.Height / scaleBy);

            newMatrix = newMatrix.Resize(width, height, Emgu.CV.CvEnum.Inter.Linear);

            /* Compute the Gradient Vector of every pixel, as well as magnitude and direction */
            // apply Sobel by x and y
            Image <Gray, float> sobel = newMatrix.Sobel(0, 1, 3).Add(newMatrix.Sobel(1, 0, 3)).AbsDiff(new Gray(0.0));

            newMatrix = sobel.Convert <Gray, Byte>();

            /* Compute descriptor values */
            HOGDescriptor hog       = new HOGDescriptor();
            Size          WinStride = new Size(18, 18);
            Size          Padding   = new Size(10, 10);

            Point[] locations        = null;
            float[] descriptorValues = hog.Compute(newMatrix, WinStride, Padding, locations);
            grayImage.Image = newMatrix;

            Image <Gray, Byte> descMatrix = Visualize(newMatrix, descriptorValues);

            newImage.Image = descMatrix;
        }
Ejemplo n.º 16
0
        public static float[] GetHog(Mat matPlate)
        {
            Mat matTemp = matPlate.Resize(WIN_SIZE);

            HOGDescriptor hogDescriptor = new HOGDescriptor(
                WIN_SIZE,
                BLOCK_SIZE,
                BLOCK_STRIDE,
                CELL_SIZE);

            float[] hog = hogDescriptor.Compute(
                matTemp,
                new OpenCvSharp.Size(1, 1),
                new OpenCvSharp.Size(0, 0));

            return(hog);
        }
Ejemplo n.º 17
0
        public float[] Compute(Bitmap roi)
        {
            if (_hogDescriptor == null)
            {
                return(null);
            }

            Image <Bgr, Byte> imageOfInterest = new Image <Bgr, byte>(roi);

            //float[] handPalmVeinDescriptor = hog.Compute(imageOfInterest, new Size(170, 160), new Size(2, 2));
            float[] handPalmVeinDescriptor = _hogDescriptor.Compute(imageOfInterest, new Size(68, 64), new Size(2, 2));

            // min = handPalmVeinDescriptor.Min();
            // max = handPalmVeinDescriptor.Max();

            return(handPalmVeinDescriptor);
        }
        public float[] GetVector(Image <Bgr, Byte> imageOfInterest)
        {
            HOGDescriptor hog = new HOGDescriptor();    // with defaults values

            System.Drawing.Point[] p = new System.Drawing.Point[imageOfInterest.Width * imageOfInterest.Height];
            int k = 0;

            for (int i = 0; i < imageOfInterest.Width; i++)
            {
                for (int j = 0; j < imageOfInterest.Height; j++)
                {
                    System.Drawing.Point p1 = new System.Drawing.Point(i, j);
                    p[k++] = p1;
                }
            }
            float[] result = hog.Compute(imageOfInterest, new System.Drawing.Size(16, 16), new System.Drawing.Size(0, 0), p);
            return(result);
        }
Ejemplo n.º 19
0
        private float[] GetVector(Image <Bgr, Byte> im)
        {
            HOGDescriptor     hog             = new HOGDescriptor(); // with defaults values
            Image <Bgr, Byte> imageOfInterest = Resize(im);

            System.Drawing.Point[] p = new System.Drawing.Point[imageOfInterest.Width * imageOfInterest.Height];
            int k = 0;

            for (int i = 0; i < imageOfInterest.Width; i++)
            {
                for (int j = 0; j < imageOfInterest.Height; j++)
                {
                    System.Drawing.Point p1 = new System.Drawing.Point(i, j);
                    p[k++] = p1;
                }
            }

            return(hog.Compute(imageOfInterest, new Size(8, 8), new Size(0, 0), null));
        }
Ejemplo n.º 20
0
        /// <summary>
        /// predict
        /// </summary>
        /// <param name="svm"></param>
        /// <param name="src"></param>
        /// <returns></returns>
        static float Predict(SVM svm, Mat src)
        {
            var hog  = new HOGDescriptor(new Size(64, 64), new Size(16, 16), new Size(8, 8), new Size(8, 8));
            Mat data = Mat.Zeros(1, hog.GetDescriptorSize(), MatType.CV_32FC1);

            Cv2.Resize(src, src, new Size(64, 64));

            src = src.Threshold(200, 255, ThresholdTypes.Binary);

            MoveToCenter(src);

            var descriptors = hog.Compute(src, new Size(1, 1), new Size(0, 0));

            for (var i = 0; i < descriptors.Length; i++)
            {
                data.Set(0, i, descriptors[i]);
            }
            return(svm.Predict(data));
        }
Ejemplo n.º 21
0
    public float[] GetVector(Image <Bgr, Byte> im)
    {
        HOGDescriptor     hog             = new HOGDescriptor(); // with defaults values
        Image <Bgr, Byte> imageOfInterest = im.Resize(64, 128, Emgu.CV.CvEnum.INTER.CV_INTER_LINEAR);

        Point[] p = new Point[imageOfInterest.Width * imageOfInterest.Height];
        int     k = 0;

        for (int i = 0; i < imageOfInterest.Width; i++)
        {
            for (int j = 0; j < imageOfInterest.Height; j++)
            {
                Point p1 = new Point(i, j);
                p[k++] = p1;
            }
        }

        return(hog.Compute(imageOfInterest, new Size(8, 8), new Size(0, 0), p));
    }
Ejemplo n.º 22
0
        public double[] CalculateHog(Image <Bgr, byte> image)
        {
            Size imageSize = new Size(64, 16);

            Size blockSize = new Size(16, 16);
            // non overlapping rows
            Size blockStride = new Size(16, 8);
            Size cellSize    = new Size(8, 8);


            HOGDescriptor hog = new HOGDescriptor(imageSize, blockSize, blockStride, cellSize);

            float[] hogs = hog.Compute(image);

            double[] hogd = new double[hogs.Length];
            for (int i = 0; i < hogs.Length; i++)
            {
                hogd[i] = hogs[i];
            }

            return(hogd);
        }
Ejemplo n.º 23
0
        public void Recognize(Mat bin, Mat gray)
        {
            mTypes = new SignType[mRects.Count];

            int iRect = 0;

            foreach (Core.Rect rect in mRects)
            {
                // Crop
                Mat graySign = new Mat(gray, rect);
                Imgproc.Resize(graySign, graySign, new Size(SIGN_WIDTH, SIGN_HEIGHT));

                // Compute HOG descriptor
                MatOfFloat descriptors = new MatOfFloat();
                mHog.Compute(graySign, descriptors);

                Mat fm = new Mat(descriptors.Size(), CvType.Cv32f);
                // predict matrix transposition
                //mTypes[iRect] = (SignType)(int)(mSvm.Predict(fm.T()));
                iRect++;
            }
        }
Ejemplo n.º 24
0
        public static Image <Bgr, Byte> Find(Image <Bgr, Byte> image, out long processingTime)
        {
            Stopwatch watch;

            Rectangle[] regions;
            float[]     result;

            using (HOGDescriptor des = new HOGDescriptor())
            {
                watch  = Stopwatch.StartNew();
                result = des.Compute(image, new Size(16, 16), Size.Empty, null);
                watch.Stop();
                result = result.Where(x => x != 0).ToArray();
                //regions = des.DetectMultiScale(image);
            }


            processingTime = watch.ElapsedMilliseconds;


            return(image);
        }
Ejemplo n.º 25
0
        /// <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");
        }
        private void trainSVM(string[] shapeTypes)
        {
            string myPhotos   = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
            string folderPath = Path.Combine(myPhotos, "shape_samples");

            CvSVM svm = new CvSVM();

            CvSVMParams svmParams = new CvSVMParams();

            svmParams.SVMType    = CvSVM.C_SVC;
            svmParams.KernelType = CvSVM.LINEAR;
            svmParams.C          = 0.01;

            int numSamples  = Directory.GetFiles(folderPath, "*.png").Length;
            int numFeatures = 0;

            if (numSamples == 0)
            {
                return;
            }

            float[,] extractedFeatures = null;
            float[] labels = new float[numSamples];
            int     i      = 0;

            foreach (string file in Directory.EnumerateFiles(folderPath, "*.png"))
            {
                Bitmap bitmap = (Bitmap)Image.FromFile(file, true);
                Mat    mat    = BitmapConverter.ToMat(bitmap);

                HOGDescriptor hog = new HOGDescriptor();
                hog.WinSize     = new OpenCvSharp.CPlusPlus.Size(32, 32); // Set hog features here: winSize; blockSize; cellSize
                hog.BlockSize   = new OpenCvSharp.CPlusPlus.Size(4, 4);
                hog.CellSize    = new OpenCvSharp.CPlusPlus.Size(4, 4);
                hog.BlockStride = new OpenCvSharp.CPlusPlus.Size(2, 2);
                float[] features = hog.Compute(mat, new OpenCvSharp.CPlusPlus.Size(16, 16), new OpenCvSharp.CPlusPlus.Size(0, 0), null);
                if (extractedFeatures == null)
                {
                    numFeatures       = features.Length;
                    extractedFeatures = new float[numSamples, numFeatures];
                }
                for (int j = 0; j < numFeatures; j++)
                {
                    extractedFeatures[i, j] = features[j];
                }
                labels[i] = -1;
                for (int shape = 0; shape < shapeTypes.Length; shape++)
                {
                    if (file.ToLower().Contains(shapeTypes[shape].ToLower()))
                    {
                        labels[i] = shape;
                        break;
                    }
                }
                bitmap.Dispose();
                i++;
            }
            Mat labelsMat            = new Mat(numSamples, 1, MatType.CV_32FC1, labels);
            Mat extractedFeaturesMat = new Mat(numSamples, numFeatures, MatType.CV_32FC1, extractedFeatures);

            try {
                svm.Train(extractedFeaturesMat, labelsMat, null, null, svmParams);
                svm.Save(Path.Combine(folderPath, "trained_svm"));
            }
            catch (OpenCVException e)
            {
                //Only a single class present
            }
        }
Ejemplo n.º 27
0
 private float[] FeatureExtractionVerfication(IInputArray patch)
 {
     return(hog_verfication.Compute(patch, winStride, trainPadding, null));
 }
Ejemplo n.º 28
0
    /// <summary>
    /// for hog training
    /// </summary>
    /// <param name="positive_path"></param>
    /// <param name="negative_path"></param>
    /// <param name="svm_save_path"></param>
    /// <returns></returns>
    public bool Training(string root_path, string svm_save_path)
    {
        try {
            var computes      = new List <float[]>();
            var response      = new List <int>();
            var color_folders = Directory.GetDirectories(root_path);

            if (color_folders.Length == 0)
            {
                return(false);
            }

            foreach (var color in color_folders)
            {
                var positive_path = string.Format(color + "\\" + "positive");
                var negative_path = string.Format(color + "\\" + "negative");
                var positives     = Directory.GetFiles(positive_path);
                var negatives     = Directory.GetFiles(negative_path);

                foreach (var file in positives)
                {
                    computes.Add(hog.Compute(Cv2.ImRead(file, ImreadModes.GrayScale).Resize(hog.WinSize)));
                    response.Add(1);
                }

                foreach (var file in negatives)
                {
                    computes.Add(hog.Compute(Cv2.ImRead(file, ImreadModes.GrayScale).Resize(hog.WinSize)));
                    response.Add(-1);
                }
            }
            var respon_mat = new Mat(response.Count, 1, MatType.CV_32SC1, response.ToArray());
            var samples    = new float[computes[0].Length * computes.Count];
            var sample_mat = new Mat(computes.Count, computes[0].Length, MatType.CV_32FC1, samples);

            for (int idx = 0; idx < computes[0].Length * computes.Count; idx += computes[0].Length)
            {
                for (int col = 0; col < computes[0].Length; col++)
                {
                    samples[idx + col] = computes[idx / computes[0].Length][col];
                }
            }

            classifier.KernelType = OpenCvSharp.ML.SVM.KernelTypes.Linear;
            classifier.Type       = OpenCvSharp.ML.SVM.Types.EpsSvr;
            classifier.P          = 0.1;
            classifier.Nu         = 0.1;
            classifier.C          = 0.01;
            classifier.Gamma      = 0.1;
            classifier.Train(sample_mat, OpenCvSharp.ML.SampleTypes.RowSample, respon_mat);
            classifier.Save(svm_save_path);

            var support_vectors = classifier.GetSupportVectors();
            var vectors         = new float[support_vectors.Width * support_vectors.Height];
            Marshal.Copy(support_vectors.Data, vectors, 0, support_vectors.Width * support_vectors.Height);
            hog.SetSVMDetector(vectors);
            return(true);
        }
        catch (Exception e) {
            Trace.WriteLine(e.StackTrace + e.Message);
            return(false);
        }
    }