private void btnCentro_Click(object sender, EventArgs e)
        {
            Emgu.CV.Util.VectorOfVectorOfPoint contours = new Emgu.CV.Util.VectorOfVectorOfPoint();
            Mat mat = new Mat();

            CvInvoke.FindContours(imgout, contours, mat, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);

            for (int i = 0; i < contours.Size; i++)
            {
                var area = CvInvoke.ContourArea(contours[i]);
                if (area > (int)numericSenCount.Value)
                {
                    Rectangle   rect     = CvInvoke.BoundingRectangle(contours[i]);
                    RotatedRect box      = CvInvoke.MinAreaRect(contours[i]);
                    PointF[]    Vertices = box.GetVertices();
                    PointF      point    = box.Center;
                    papel       = pictureBox1.CreateGraphics();
                    pluma.Width = 5;
                    pluma.Color = Color.DarkBlue;
                    papel.DrawRectangle(pluma, point.X, point.Y, 5, 5);
                }
            }

            /*PointF edge1 = new PointF(Vertices[1].X - Vertices[0].X,
             * Vertices[1].Y - Vertices[0].Y);
             * PointF edge2 = new PointF(Vertices[2].X - Vertices[1].X, Vertices[2].Y - Vertices[1].Y);
             * double edge1Magnitude = Math.Sqrt(Math.Pow(edge1.X, 2) + Math.Pow(edge1.Y, 2));
             * double edge2Magnitude = Math.Sqrt(Math.Pow(edge2.X, 2) + Math.Pow(edge2.Y, 2));
             * PointF primaryEdge = edge1Magnitude > edge2Magnitude ? edge1 : edge2;
             * PointF reference = new PointF(Vertices[1].X, Vertices[0].Y);
             * double thetaRads = Math.Acos(Math.Sqrt(Math.Pow((primaryEdge.X * reference.X),2) + Math.Pow((primaryEdge.Y * reference.Y),2))/ (Math.Sqrt(Math.Pow(primaryEdge.X,2)+Math.Pow(reference.X,2))* Math.Sqrt(Math.Pow(primaryEdge.Y, 2) + Math.Pow(reference.Y, 2))));
             * double thetaDeg = thetaRads * 180 / Math.PI;
             * MessageBox.Show(thetaDeg.ToString());*/
        }
Esempio n. 2
0
        private void DetectarTexto(Image <Bgr, byte> img)
        {
            Image <Gray, byte> sobel = img.Convert <Gray, byte>().Sobel(1, 0, 3).AbsDiff(new Gray(0.0)).Convert <Gray, byte>().ThresholdBinary(new Gray(100), new Gray(255));
            Mat SE = CvInvoke.GetStructuringElement(Emgu.CV.CvEnum.ElementShape.Rectangle, new Size(10, 1), new Point(-1, -1));

            sobel = sobel.MorphologyEx(Emgu.CV.CvEnum.MorphOp.Dilate, SE, new Point(-1, -1), 1, Emgu.CV.CvEnum.BorderType.Reflect, new MCvScalar(255));
            Emgu.CV.Util.VectorOfVectorOfPoint contours = new Emgu.CV.Util.VectorOfVectorOfPoint();
            Mat m = new Mat();

            CvInvoke.FindContours(sobel, contours, m, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
            List <Rectangle> list = new List <Rectangle>();

            for (int i = 0; i < contours.Size; i++)
            {
                Rectangle brect = CvInvoke.BoundingRectangle(contours[i]);

                double ar = brect.Width / brect.Height;

                if (brect.Width > 30 && brect.Height > 8 && brect.Height < 100)
                {
                    list.Add(brect);
                }
            }
            Image <Bgr, byte> imgout = img.CopyBlank();

            foreach (var r in list)
            {
                CvInvoke.Rectangle(img, r, new MCvScalar(0, 0, 255), 2);
                CvInvoke.Rectangle(imgout, r, new MCvScalar(0, 255, 255), -1);
                imgout._And(img);
                pictureBox1.Image = img.Bitmap;
                pictureBox2.Image = imgout.Bitmap;
            }
        }
Esempio n. 3
0
        public List <Rectangle> sort_contours(Emgu.CV.Util.VectorOfVectorOfPoint cnts, string method)
        {
            List <Rectangle> BoundingBoxes = new List <Rectangle>();

            //get the boxes into a list

            for (int i = 0; i < cnts.Size; i++)
            {
                Emgu.CV.Util.VectorOfPoint contour = cnts[i];
                Rectangle BoundingBox = CvInvoke.BoundingRectangle(contour);
                BoundingBoxes.Add(BoundingBox);
            }

            // if no method specified defaut to l to r top to bottom

            List <Rectangle> SortedBoxes = BoundingBoxes.OrderBy(Rectangle => Rectangle.X).ThenBy(Rectangle => Rectangle.Y).ToList();

            if (method == "right-to-left")
            {
                SortedBoxes = BoundingBoxes.OrderByDescending(Rectangle => Rectangle.X).ThenBy(Rectangle => Rectangle.Y).ToList();
            }
            else if (method == "top-to-bottom")
            {
                SortedBoxes = BoundingBoxes.OrderBy(Rectangle => Rectangle.Y).ThenBy(Rectangle => Rectangle.X).ToList();
            }
            else if (method == "bottom-to-top")
            {
                SortedBoxes = BoundingBoxes.OrderByDescending(Rectangle => Rectangle.Y).ThenBy(Rectangle => Rectangle.X).ToList();
            }



            return(SortedBoxes);
        }
Esempio n. 4
0
        private void BubbleDetectBtn_Click(object sender, EventArgs e)
        {
            //Applying Operations on transformed Image
            transformedImage = transformedImage.Resize(400, 400, Emgu.CV.CvEnum.Inter.Linear);
            Image <Bgr, byte> transCopy = transformedImage.Copy();

            Emgu.CV.Util.VectorOfVectorOfPoint qtnVect = new Emgu.CV.Util.VectorOfVectorOfPoint();
            Image <Gray, byte> qtnGray = transCopy.Convert <Gray, byte>();
            Image <Gray, byte> copyG   = qtnGray.Copy();

            CvInvoke.GaussianBlur(qtnGray, qtnGray, new Size(5, 5), 0);
            CvInvoke.AdaptiveThreshold(qtnGray, qtnGray, 255, Emgu.CV.CvEnum.AdaptiveThresholdType.GaussianC, Emgu.CV.CvEnum.ThresholdType.Binary, 55, 9);
            CvInvoke.BitwiseNot(qtnGray, qtnGray);
            CvInvoke.FindContours(qtnGray, qtnVect, null, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple, default);


            //CIRCLE METHOD
            List <CircleF> circList = new List <CircleF>();

            Emgu.CV.Util.VectorOfVectorOfPoint test      = new Emgu.CV.Util.VectorOfVectorOfPoint();
            Emgu.CV.Util.VectorOfPoint         qtnApprox = new Emgu.CV.Util.VectorOfPoint();
            Dictionary <int, double>           qtnDict   = new Dictionary <int, double>();

            if (qtnVect.Size > 0)
            {
                for (int i = 0; i < qtnVect.Size; i++)
                {
                    double area = CvInvoke.ContourArea(qtnVect[i]);
                    if (area > 70)
                    {
                        qtnDict.Add(i, area);
                    }
                }
                var item = qtnDict.OrderByDescending(v => v.Value);  //.Take(1);

                Emgu.CV.Util.VectorOfPoint approxList = new Emgu.CV.Util.VectorOfPoint();

                foreach (var it in item)
                {
                    int    key  = Convert.ToInt32(it.Key.ToString());
                    double peri = CvInvoke.ArcLength(qtnVect[key], true);
                    CvInvoke.ApproxPolyDP(qtnVect[key], qtnApprox, 0.02 * peri, true);

                    if (qtnApprox.Size == 0)
                    {
                    }
                    else if (qtnApprox.Size > 6)
                    {
                        CircleF circle = CvInvoke.MinEnclosingCircle(qtnVect[key]);
                        Point   centre = new Point();
                        centre.X = (int)circle.Center.X;
                        centre.Y = (int)circle.Center.Y;
                        CvInvoke.Circle(transformedImage, centre, (int)circle.Radius, new MCvScalar(0, 255, 0), 2, Emgu.CV.CvEnum.LineType.Filled, 0);
                        //break;
                    }
                }
                MessageBox.Show("Bubbles Detected");
                bubbleImage.Image = transformedImage;
            }
        }
        private void btnEtiquetar_Click(object sender, EventArgs e)
        {
            GrojoImage = redImage.Convert <Gray, byte>().ThresholdBinary(new Gray(10), new Gray(255));
            Emgu.CV.Util.VectorOfVectorOfPoint contoursRed = new Emgu.CV.Util.VectorOfVectorOfPoint();
            Mat matRed = new Mat();

            CvInvoke.FindContours(GrojoImage, contoursRed, matRed, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
            for (int i = 0; i < contoursRed.Size; i++)
            {
                var area = CvInvoke.ContourArea(contoursRed[i]);
                if (area > (int)numericSize.Value)
                {
                    var blob = CvInvoke.BoundingRectangle(contoursRed[i]);
                    blob.Y -= 5;
                    CvInvoke.PutText(img, "Rojo", blob.Location, Emgu.CV.CvEnum.FontFace.HersheySimplex, 0.5, new MCvScalar(255, 255, 255));
                    CvInvoke.PutText(combinadaImg, "Rojo", blob.Location, Emgu.CV.CvEnum.FontFace.HersheySimplex, 0.5, new MCvScalar(255, 255, 255));
                }
            }
            GverdeImage = greenImage.Convert <Gray, byte>().ThresholdBinary(new Gray(10), new Gray(255));
            Emgu.CV.Util.VectorOfVectorOfPoint contoursGreen = new Emgu.CV.Util.VectorOfVectorOfPoint();
            Mat matVer = new Mat();

            CvInvoke.FindContours(GverdeImage, contoursGreen, matVer, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
            for (int i = 0; i < contoursGreen.Size; i++)
            {
                var area = CvInvoke.ContourArea(contoursGreen[i]);
                if (area > (int)numericSize.Value)
                {
                    var blob = CvInvoke.BoundingRectangle(contoursGreen[i]);
                    blob.Y -= 5;
                    CvInvoke.PutText(img, "Verde", blob.Location, Emgu.CV.CvEnum.FontFace.HersheySimplex, 0.5, new MCvScalar(255, 255, 255));
                    CvInvoke.PutText(combinadaImg, "Verde", blob.Location, Emgu.CV.CvEnum.FontFace.HersheySimplex, 0.5, new MCvScalar(255, 255, 255));
                }
            }
            GazulImage = blueImage.Convert <Gray, byte>().ThresholdBinary(new Gray(10), new Gray(255));
            Emgu.CV.Util.VectorOfVectorOfPoint contoursBlue = new Emgu.CV.Util.VectorOfVectorOfPoint();
            Mat matAzu = new Mat();

            CvInvoke.FindContours(GazulImage, contoursBlue, matAzu, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
            for (int i = 0; i < contoursBlue.Size; i++)
            {
                var area = CvInvoke.ContourArea(contoursBlue[i]);
                if (area > (int)numericSize.Value)
                {
                    var blob = CvInvoke.BoundingRectangle(contoursBlue[i]);
                    blob.Y -= 5;
                    CvInvoke.PutText(img, "Azul", blob.Location, Emgu.CV.CvEnum.FontFace.HersheySimplex, 0.5, new MCvScalar(255, 255, 255));
                    CvInvoke.PutText(combinadaImg, "Azul", blob.Location, Emgu.CV.CvEnum.FontFace.HersheySimplex, 0.5, new MCvScalar(255, 255, 255));
                }
            }
            if (btnIntercambio.Text == "ORIGINAL")
            {
                pictureFirst.Image = combinadaImg.ToBitmap();
            }
            else
            {
                pictureFirst.Image = img.ToBitmap();
            }
        }
Esempio n. 6
0
        private int detectPageMarks()
        {
            Emgu.CV.Util.VectorOfVectorOfPoint contours = new Emgu.CV.Util.VectorOfVectorOfPoint();
            CvInvoke.FindContours(thresholded, contours, null, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple, new Point(0, 0));
            convertedWThreshold = originalThresholded.ToImage <Emgu.CV.Structure.Bgr, Byte>();

            int pageMarksCount = 0;

            for (int i = 0; i < contours.Size; i++)
            {
                Rectangle rect = CvInvoke.BoundingRectangle(contours[i]);
                double    k    = (rect.Height + 0.0) / rect.Width;

                if (pageMarksConfig.RatioLowerBound < k && k < pageMarksConfig.RatioUpperBound && rect.Height * rect.Width > pageMarksConfig.MinArea && rect.Height * rect.Width < pageMarksConfig.MaxArea)
                {
                    // Console.WriteLine("Found contour! "+rect.X+" "+rect.Y);
                    CvInvoke.Rectangle(originalThresholded, rect, redColor);
                    // CvInvoke.DrawContours(originalThresholded, contours, i,

                    if (rect.X < thresholded.Width * pageMarksConfig.MostLeftOffset && rect.Y < thresholded.Height * pageMarksConfig.MostTopOffset && checkIfPageMarkIsFilled(rect))
                    {
                        // Top-left mark
                        pageMarks[0] = new Point(rect.X, rect.Y);
                        Console.WriteLine("Found top-left mark at " + rect.X + " " + rect.Y);
                        Console.WriteLine("Size is: " + rect.Size.Width + " x " + rect.Size.Height);
                        pageMarksCount++;
                    }
                    else if (rect.X > thresholded.Width * pageMarksConfig.MostRightOffset && rect.Y < thresholded.Height * pageMarksConfig.MostTopOffset && checkIfPageMarkIsFilled(rect))
                    {
                        // Top-right mark
                        pageMarks[1] = new Point(rect.X + rect.Width, rect.Y);
                        Console.WriteLine("Found top-right mark at " + rect.X + " " + rect.Y);
                        Console.WriteLine("Size is: " + rect.Size.Width + " x " + rect.Size.Height);
                        pageMarksCount++;
                    }
                    else if (rect.X < thresholded.Width * pageMarksConfig.MostLeftOffset && rect.Y > thresholded.Height * pageMarksConfig.MostBottomOffset && checkIfPageMarkIsFilled(rect))
                    {
                        // Bottom-left mark
                        pageMarks[2] = new Point(rect.X, rect.Y + rect.Height);
                        Console.WriteLine("Found bottom-left mark at " + rect.X + " " + rect.Y);
                        Console.WriteLine("Size is: " + rect.Size.Width + " x " + rect.Size.Height);
                        pageMarksCount++;
                    }
                    else if (rect.X > thresholded.Width * pageMarksConfig.MostRightOffset && rect.Y > thresholded.Height * pageMarksConfig.MostBottomOffset && checkIfPageMarkIsFilled(rect))
                    {
                        // Bottom right mark
                        pageMarks[3] = new Point(rect.X + rect.Width, rect.Y + rect.Height);
                        Console.WriteLine("Found bottom-right mark at " + rect.X + " " + rect.Y);
                        Console.WriteLine("Size is: " + rect.Size.Width + " x " + rect.Size.Height);
                        pageMarksCount++;
                    }
                }
            }
            // CvInvoke.Imwrite("test_run.jpg",originalThresholded); // ----> PLEASE COMMENT THIS OUT <----
            convertedWThreshold.Dispose();
            return(pageMarksCount);
        }
Esempio n. 7
0
        public static Point[] ToArray(this Emgu.CV.Util.VectorOfVectorOfPoint vectorOfVectorOfPoint)
        {
            List <Point> insidePoints = new List <Point>();

            for (int i = 0; i < vectorOfVectorOfPoint.Size; i++)
            {
                insidePoints.AddRange(vectorOfVectorOfPoint[i].ToArray());
            }
            return(insidePoints.ToArray());
        }
        public int encontrarDimensionLetra()
        {
            int tamano = 0;

            System.Drawing.Bitmap bmp =
                new System.Drawing.Bitmap(System.Drawing.Image.FromFile(ruta + "files/6imagenthresherode.bmp"));
            Emgu.CV.Image <Emgu.CV.Structure.Gray, Byte> imgt = new Emgu.CV.Image <Emgu.CV.Structure.Gray, Byte>(bmp);

            Emgu.CV.Structure.MCvScalar sc = new Emgu.CV.Structure.MCvScalar();
            Size s = new Size(imgt.Width / 10, 1);

            Point p       = new Point(-1, -1);
            Mat   element = Emgu.CV.CvInvoke.GetStructuringElement(Emgu.CV.CvEnum.ElementShape.Rectangle, s, p);


            Emgu.CV.CvInvoke.MorphologyEx(imgt, imgt, Emgu.CV.CvEnum.MorphOp.Close, element, new Point(-1, -1), 1, Emgu.CV.CvEnum.BorderType.Constant, sc);
            guardarArchivo(imgt.Mat, "imagenCerrada");
            List <int> valores = new List <int>();



            Emgu.CV.Util.VectorOfVectorOfPoint contours = new Emgu.CV.Util.VectorOfVectorOfPoint();

            Emgu.CV.Mat hier = new Emgu.CV.Mat();
            Emgu.CV.CvInvoke.FindContours(imgt, contours, hier, Emgu.CV.CvEnum.RetrType.Tree, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxNone);

            Emgu.CV.Util.VectorOfVectorOfPoint contours_poly = new Emgu.CV.Util.VectorOfVectorOfPoint(contours.Size);

            for (int i = 0; i < contours.Size; i++)
            {
                if (contours[i].Size > 100)//80
                {
                    Emgu.CV.CvInvoke.ApproxPolyDP((contours[i]), contours_poly[i], 3, true);

                    Rectangle appRect = Emgu.CV.CvInvoke.BoundingRectangle(contours_poly[i]);                //get the bounding rect
                    if (appRect.Height > 2)
                    {
                        valores.Add(appRect.Height);
                    }
                }
            }
            valores.Sort();
            if (valores.Count % 2 == 0)
            {
                tamano = (valores[Convert.ToInt32(Math.Floor(valores.Count * 0.50))] + valores[Convert.ToInt32(Math.Floor(valores.Count * 0.50)) + 1]) / 2;
            }
            else
            {
                tamano = valores[Convert.ToInt32(Math.Round(valores.Count * 0.50))];
            }



            return(tamano);
        }
Esempio n. 9
0
        private void findPaperMarksBtn_Click(object sender, EventArgs e)
        {
            double maxArea          = 2500;
            double minArea          = 2200;
            double mostLeftOffset   = 0.25;
            double mostRightOffset  = 0.75;
            double mostTopOffset    = 0.25;
            double mostBottomOffset = 0.75;


            Emgu.CV.Util.VectorOfVectorOfPoint contours = new Emgu.CV.Util.VectorOfVectorOfPoint();
            Mat hierarchy = new Mat();

            CvInvoke.FindContours(thresholded, contours, null, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple, new Point(0, 0));

            for (int i = 0; i < contours.Size; i++)
            {
                Rectangle rect = CvInvoke.BoundingRectangle(contours[i]);
                double    k    = (rect.Height + 0.0) / rect.Width;

                if (0.95 < k && k < 1.05 && rect.Height * rect.Width > minArea && rect.Height * rect.Width < maxArea)
                {
                    // Console.WriteLine("Found contour! "+rect.X+" "+rect.Y);
                    CvInvoke.DrawContours(colorImage, contours, i, redColor);

                    if (rect.X < image.Width * mostLeftOffset && rect.Y < image.Height * mostTopOffset)
                    {
                        // Top-left mark
                        pageMarks[0] = new Point(rect.X, rect.Y);
                        Console.WriteLine("Found top-left mark at " + rect.X + " " + rect.Y);
                    }
                    else if (rect.X > image.Width * mostRightOffset && rect.Y < image.Height * mostTopOffset)
                    {
                        // Top-right mark
                        pageMarks[1] = new Point(rect.X, rect.Y);
                        Console.WriteLine("Found top-right mark at " + rect.X + " " + rect.Y);
                    }
                    else if (rect.X < image.Width * mostLeftOffset && rect.Y > image.Height * mostBottomOffset)
                    {
                        // Bottom-left mark
                        pageMarks[2] = new Point(rect.X, rect.Y);
                        Console.WriteLine("Found bottom-left mark at " + rect.X + " " + rect.Y);
                    }
                    else if (rect.X > image.Width * mostRightOffset && rect.Y > image.Height * mostBottomOffset)
                    {
                        // Bottom right mark
                        pageMarks[3] = new Point(rect.X, rect.Y);
                        Console.WriteLine("Found bottom-right mark at " + rect.X + " " + rect.Y);
                    }
                }
            }

            imageBox1.Image = colorImage;
        }
Esempio n. 10
0
        private void button1_Click_1(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                imgImage          = new Image <Bgr, byte>(ofd.FileName);
                pictureBox1.Image = imgImage.Bitmap;
            }

            Image <Gray, byte> imgOutput = imgImage.Convert <Gray, byte>().ThresholdBinary(new Gray(100), new Gray(255));

            Emgu.CV.Util.VectorOfVectorOfPoint contours = new Emgu.CV.Util.VectorOfVectorOfPoint();
            Mat hier = new Mat();
            Image <Gray, byte> imgout = new Image <Gray, byte>(imgImage.Width, imgImage.Height, new Gray(0));

            CvInvoke.FindContours(imgOutput, contours, hier, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
            CvInvoke.DrawContours(imgout, contours, -1, new MCvScalar(255, 0, 0));
            pictureBox1.Width  = imgout.Width;
            pictureBox1.Height = imgout.Height;
            pictureBox1.Image  = imgout.Bitmap;

            int w_l = k; // на какое кол-во кусков будет делиться картинка
            int h_l = k;

            int W = pictureBox1.Width / w_l;  // ширина куска
            int H = pictureBox1.Height / h_l; // длина куска

            List <Image> imageParts = new List <Image>();

            List <Image> ans = new List <Image>();

            for (int i = 0; i < pictureBox1.Height - h_l; i += 20)
            {
                for (int j = 0; j < pictureBox1.Width - w_l; j += 20)
                {
                    Rectangle rectangle = new Rectangle(j, i, w_l, h_l);
                    var       pic       = (Bitmap)pictureBox1.Image;
                    Image     img       = pic.Clone(rectangle, pic.PixelFormat);
                    if (CheckMatr(new Bitmap(img), i, j))
                    {
                        pictureBox2.Image = img;
                        Refresh();
                        Graphics g = this.CreateGraphics();

                        g.FillEllipse(new SolidBrush(Color.Red), i, j, 10, 10);
                        ans.Add(img);
                        richTextBox1.Text += "x: " + i + " y: " + j;
                        richTextBox1.Text += Environment.NewLine;
                    }
                }
            }
        }
Esempio n. 11
0
        public static Emgu.CV.Util.VectorOfVectorOfPoint FindContours(this Emgu.CV.IInputOutputArray image,
                                                                      Emgu.CV.CvEnum.ChainApproxMethod method)
        {
            var contours = new Emgu.CV.Util.VectorOfVectorOfPoint();

            Emgu.CV.CvInvoke.FindContours(image: image,
                                          contours: contours,
                                          hierarchy: null,
                                          mode: Emgu.CV.CvEnum.RetrType.External,
                                          method: method);
            return(contours);
        }
Esempio n. 12
0
        public static PointF[] ToArrayF(this Emgu.CV.Util.VectorOfVectorOfPoint vectorOfVectorOfPoint)
        {
            List <PointF> insidePoints = new List <PointF>();

            for (int i = 0; i < vectorOfVectorOfPoint.Size; i++)
            {
                for (int j = 0; j < vectorOfVectorOfPoint[i].Size; j++)
                {
                    insidePoints.Add(vectorOfVectorOfPoint[i][j]);
                }
            }
            return(insidePoints.ToArray());
        }
Esempio n. 13
0
        public static Image ShowContours(Image <Bgr, byte> image)
        {
            Image <Gray, byte> imageOutput = image.Convert <Gray, Byte>().ThresholdBinary(new Gray(100), new Gray(255));

            Emgu.CV.Util.VectorOfVectorOfPoint contours = new Emgu.CV.Util.VectorOfVectorOfPoint();

            Mat hier = new Mat();

            CvInvoke.FindContours(imageOutput, contours, hier, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
            CvInvoke.DrawContours(image, contours, -1, new MCvScalar(255, 0, 0));

            return(imageOutput.Bitmap);
        }
        private void detectarCentro()
        {
            matrizImagen = new int[img.Height, img.Width];


            /*if (img!=null)
             * {
             *  for(int i = 0;i<img.Height;i++)
             *  {
             *      for(int j=0;j<img.Width;j++)
             *      {
             *          if (imgout[i, j].Intensity == 0)
             *          {
             *              matrizImagen[i, j] = 0;
             *          }
             *
             *
             *      }
             *  }
             * }*/

            Emgu.CV.Util.VectorOfVectorOfPoint contours = new Emgu.CV.Util.VectorOfVectorOfPoint();
            Mat mat = new Mat();

            CvInvoke.FindContours(imgout, contours, mat, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);

            for (int x = 0; x < contours.Size; x++)
            {
                for (int i = 0; i < img.Height; i++)
                {
                    for (int j = 0; j < img.Width; j++)
                    {
                        imgout[i, j] = new Gray(0);
                    }
                }
                var area = CvInvoke.ContourArea(contours[x]);
                if (area > (int)numericSenCount.Value)
                {
                    CvInvoke.DrawContours(imgout, contours, x, new MCvScalar(255, 255, 255));
                    MCvMoments moments   = CvInvoke.Moments(imgout.Mat, false);
                    Point      centroide = new Point((int)(moments.M10 / moments.M00), (int)(moments.M01 / moments.M00));

                    papel       = pictureBox1.CreateGraphics();
                    pluma.Width = 5;
                    pluma.Color = Color.DarkRed;
                    papel.DrawRectangle(pluma, (int)(moments.M10 / moments.M00), (int)(moments.M01 / moments.M00), 5, 5);
                }
            }
            detectarBorde();
            //pictureBox2.Image = imgout.Bitmap;
        }
Esempio n. 15
0
        private void findContoursToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Image <Gray, byte> imgOutput = imgInput.Convert <Gray, byte>().ThresholdBinary(new Gray(100), new Gray(255));

            Emgu.CV.Util.VectorOfVectorOfPoint contours = new Emgu.CV.Util.VectorOfVectorOfPoint();
            Mat hier = new Mat();

            Image <Gray, byte> imgout = new Image <Gray, byte>(imgInput.Width, imgInput.Height, new Gray(0));

            CvInvoke.FindContours(imgOutput, contours, hier, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
            CvInvoke.DrawContours(imgout, contours, -1, new MCvScalar(255, 0, 0));

            pictureBox2.Image = imgout.Bitmap;
        }
Esempio n. 16
0
        protected PointF GetPositionFromBinary(Emgu.CV.Image <Emgu.CV.Structure.Gray, Byte> binaryImage, bool drawPositionInfo)
        {
            int maxNumberOfObects = 50;
            int minObjectArea     = 30 * 30;
            int maxObjectArea     = (int)(binaryImage.Size.Width * binaryImage.Size.Height / 1.05);

            ratPosition = new IncorrectPosition();
            //Point positionNotFound = new Point(50000, 50000);
            //var positionNotFound = new PointF(float.NaN, float.NaN);
            Emgu.CV.Image <Emgu.CV.Structure.Gray, Byte> temporaryBinaryImage = binaryImage.Clone();
            Emgu.CV.Util.VectorOfVectorOfPoint           contours             = new Emgu.CV.Util.VectorOfVectorOfPoint();
            Emgu.CV.Mat hierarchy = new Mat();
            CvInvoke.FindContours(temporaryBinaryImage, contours, hierarchy, RetrType.Ccomp, ChainApproxMethod.ChainApproxSimple);
            if (contours.Size > 0)
            {
                int numberOfObjects = contours.Size;
                //var h = hierarchy.GetInputOutputArray();
                if (numberOfObjects < maxNumberOfObects)
                {
                    float referenceArea = 0;
                    //index = hierarchy.GetData(new int[] { index, 0 })[0]
                    for (int index = 0; index < numberOfObjects; index++)
                    {
                        IInputArray contour = contours.GetInputArray().GetMat(index);
                        MCvMoments  moment  = CvInvoke.Moments(contour);
                        float       area    = (float)moment.M00;

                        if (area > minObjectArea && area < maxObjectArea && area > referenceArea)
                        {
                            ratPosition = new CorrectPosition(
                                x: (float)moment.M10 / area,
                                y: (float)moment.M01 / area);
                            referenceArea = area;
                        }
                    }
                }
            }
            if (drawPositionInfo)
            {
                DrawPositionInfo();
            }

            var positionToSend = new PointF
                                 (
                x: -2 * (ratPosition.Value.X - binaryImage.Size.Width / 2) / binaryImage.Size.Width,
                y: -2 * (ratPosition.Value.Y - binaryImage.Size.Height / 2) / binaryImage.Size.Height
                                 );

            return(positionToSend);
        }
Esempio n. 17
0
        public static Emgu.CV.Util.VectorOfPointF DetectEllipses(Image <Gray, byte> grayImage, Mat imageCopy)
        {
            var centerPoints  = new Emgu.CV.Util.VectorOfPointF();
            var contours      = new Emgu.CV.Util.VectorOfVectorOfPoint();
            Mat heirarchy     = null;
            var grayImageCopy = grayImage.Clone();
            var res           = CvInvoke.Threshold(grayImage, grayImageCopy, 170, 255, Emgu.CV.CvEnum.ThresholdType.Binary);

            //CvInvoke.Imwrite(Path.GetDirectoryName(myFile) + "\\" + Path.GetFileNameWithoutExtension(myFile) + "-threshold" + Path.GetExtension(myFile), grayImageCopy, new KeyValuePair<Emgu.CV.CvEnum.ImwriteFlags, int>(Emgu.CV.CvEnum.ImwriteFlags.JpegQuality, 95));
            grayImageCopy._Not();

            CvInvoke.FindContours(grayImageCopy, contours, heirarchy, Emgu.CV.CvEnum.RetrType.Ccomp, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
            // var circles = CvInvoke.HoughCircles(grayImage, Emgu.CV.CvEnum.HoughType.Gradient, 1, grayImage.Rows / 16);
            if (contours.Size > 0)
            {
                double largestArea = 0;
                for (int i = 0; i < contours.Size; i++)
                {
                    var contour = contours[i];
                    if (contour.Size > 4)
                    {
                        var rect   = CvInvoke.FitEllipse(contour);
                        var area   = rect.Size.Width * rect.Size.Height;
                        var width  = rect.Size.Width > rect.Size.Height ? rect.Size.Width : rect.Size.Height;
                        var height = rect.Size.Width > rect.Size.Height ? rect.Size.Height : rect.Size.Width;
                        if (area > 1000 && width / height < 3)
                        {
                            var averageDist  = AverageDistanceToEllipse(contour, rect);
                            var furthestDist = FurthestDistanceToEllipse(contour, rect);
                            if (averageDist < 1.5 && furthestDist < 4)
                            {
                                if (area > largestArea)
                                {
                                    largestArea = area;
                                }
                                centerPoints.Push(new PointF[] { rect.Center });
                                DrawContoursOnImage(imageCopy, contours[i]);
                                // CvInvoke.Ellipse(imageCopy, rect, new Bgr(System.Drawing.Color.Red).MCvScalar);
                                CvInvoke.Line(imageCopy, new Point((int)rect.GetVertices()[0].X, (int)rect.GetVertices()[0].Y), new Point((int)rect.GetVertices()[1].X, (int)rect.GetVertices()[1].Y), new Bgr(System.Drawing.Color.Red).MCvScalar);
                                CvInvoke.Line(imageCopy, new Point((int)rect.GetVertices()[1].X, (int)rect.GetVertices()[1].Y), new Point((int)rect.GetVertices()[2].X, (int)rect.GetVertices()[2].Y), new Bgr(System.Drawing.Color.Red).MCvScalar);
                                CvInvoke.Line(imageCopy, new Point((int)rect.GetVertices()[2].X, (int)rect.GetVertices()[2].Y), new Point((int)rect.GetVertices()[3].X, (int)rect.GetVertices()[3].Y), new Bgr(System.Drawing.Color.Red).MCvScalar);
                                CvInvoke.Line(imageCopy, new Point((int)rect.GetVertices()[3].X, (int)rect.GetVertices()[3].Y), new Point((int)rect.GetVertices()[0].X, (int)rect.GetVertices()[0].Y), new Bgr(System.Drawing.Color.Red).MCvScalar);
                            }
                        }
                    }
                }
            }

            return(centerPoints);
        }
Esempio n. 18
0
 private void Button3_Click(object sender, EventArgs e)
 {
     imgGray = img.Convert <Gray, Byte>();
     //Converted to blurred
     CvInvoke.GaussianBlur(imgGray, imgGray, new Size(5, 5), 0);
     // using adaptive threshhold
     CvInvoke.AdaptiveThreshold(imgGray, imgGray, 255, Emgu.CV.CvEnum.AdaptiveThresholdType.GaussianC, Emgu.CV.CvEnum.ThresholdType.BinaryInv, 75, 10);
     CvInvoke.Canny(imgGray, cannyImage, 75, 200);
     cannyImage.ConvertTo(imgGray, Emgu.CV.CvEnum.DepthType.Default, -1, 0);
     Emgu.CV.Util.VectorOfVectorOfPoint vector = new Emgu.CV.Util.VectorOfVectorOfPoint();
     CvInvoke.FindContours(cannyImage, vector, null, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
     CvInvoke.DrawContours(img, vector, -1, new MCvScalar(240, 0, 159), 3);
     MessageBox.Show("Question Part Detected");
     sheetDetectImage.Image = img;
 }
Esempio n. 19
0
        private void detectarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Binarización
            Image <Gray, byte> _imgOutput = _imgInput.Convert <Gray, byte>().ThresholdBinary(new Gray(50), new Gray(255));

            Emgu.CV.Util.VectorOfVectorOfPoint countours = new Emgu.CV.Util.VectorOfVectorOfPoint();

            Mat hier = new Mat();

            //Encontrar Contorno
            CvInvoke.FindContours(_imgOutput, countours, hier, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);

            CvInvoke.DrawContours(_imgOutput, countours, -1, new MCvScalar(255, 0, 0));

            pictureBox2.Image = _imgOutput.Bitmap;
        }
Esempio n. 20
0
        public void contour_0(int min, int max, Image <Bgr, byte> imgInput, int iron_r, int szar_r, int rain_r)
        {
            if (iron_r == 1)
            {
                Image <Gray, byte> imgOut = imgInput.Convert <Gray, byte>().InRange(new Gray(min), new Gray(max));

                Emgu.CV.Util.VectorOfVectorOfPoint contours = new Emgu.CV.Util.VectorOfVectorOfPoint();
                Mat hier = new Mat();

                CvInvoke.FindContours(imgOut, contours, hier, Emgu.CV.CvEnum.RetrType.Ccomp, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
                CvInvoke.DrawContours(imgInput, contours, -1, new MCvScalar(255, 0, 0), 1);
            }

            // kontur, pole i obwód dla palety barw Rain

            else if (rain_r == 1)
            {
                Image <Gray, byte> imgOut = imgInput.Convert <Gray, byte>().ThresholdBinaryInv(new Gray(min), new Gray(max));



                Emgu.CV.Util.VectorOfVectorOfPoint contours = new Emgu.CV.Util.VectorOfVectorOfPoint();
                Mat hier = new Mat();

                CvInvoke.FindContours(imgOut, contours, hier, Emgu.CV.CvEnum.RetrType.Ccomp, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
                CvInvoke.DrawContours(imgInput, contours, -1, new MCvScalar(255, 0, 0), 1);
            }

            // kontur, pole i obwód dla skali szarości
            else if (szar_r == 1)
            {
                Image <Gray, byte>[] channels = imgInput.Split();

                Image <Gray, byte> imgOut = channels[0];


                Image <Gray, byte> imgOut_1 = imgOut.InRange(new Gray(min), new Gray(max));



                Emgu.CV.Util.VectorOfVectorOfPoint contours = new Emgu.CV.Util.VectorOfVectorOfPoint();
                Mat hier = new Mat();

                CvInvoke.FindContours(imgOut_1, contours, hier, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
                CvInvoke.DrawContours(imgInput, contours, -1, new MCvScalar(255, 0, 0), 1);
            }
        }
Esempio n. 21
0
        public void pictureDetect(Bitmap currFrame)
        {
            using (Image <Gray, Byte> img = new Image <Rgb, byte>(currFrame).Convert <Gray, Byte>()){
                Image <Gray, byte> sobel  = new Image <Gray, byte>(currFrame);
                Image <Gray, byte> imgout = img.CopyBlank();
                //apply filters img
                sobel = img.Sobel(1, 0, 3).Add(imgout.Sobel(0, 1, 3)).AbsDiff(new Gray(0.0)).Convert <Gray, byte>().ThresholdBinary(new Gray(50), new Gray(255));
                OnSobelFilterReady(new ImgOut(sobel));

                Mat SE = CvInvoke.GetStructuringElement(Emgu.CV.CvEnum.ElementShape.Rectangle, new Size(10, 2), new Point(-1, -1));
                sobel = sobel.MorphologyEx(Emgu.CV.CvEnum.MorphOp.Dilate, SE, new Point(-1, -1), 1, Emgu.CV.CvEnum.BorderType.Reflect, new MCvScalar(255));
                OnRegionImgReady(new ImgOut(sobel));

                //find counturs
                Emgu.CV.Util.VectorOfVectorOfPoint contours = new Emgu.CV.Util.VectorOfVectorOfPoint();
                Mat m = new Mat();
                CvInvoke.FindContours(sobel, contours, m, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
                List <Rectangle> list = new List <Rectangle>();
                for (int i = 0; i < contours.Size; i++)
                {
                    Rectangle brect = CvInvoke.BoundingRectangle(contours[i]);
                    double    ar    = brect.Width / brect.Height;
                    if (ar > 2 && brect.Width > 25 && brect.Height > 8 && brect.Height < 100)
                    {
                        list.Add(brect);
                    }
                }

                foreach (var r in list)
                {
                    CvInvoke.Rectangle(imgout, r, new MCvScalar(255, 255, 255), -1);
                }
                OnImg3Ready(new ImgOut(imgout));

                imgout = img.Copy(imgout);
                //find counturs
                OnCoppedFromRegionImgReady(new ImgOut(imgout));

                //           imgout = imgout.Sobel(1, 0, 3).Add(imgout.Sobel(0, 1, 3)).AbsDiff(new Gray(0.0)).Convert<Gray, Byte>();

                //SE = CvInvoke.GetStructuringElement(Emgu.CV.CvEnum.ElementShape.Rectangle, new Size(10, 2), new Point(1, 1));
                //imgout = imgout.MorphologyEx(Emgu.CV.CvEnum.MorphOp.Erode, SE, new Point(1, 1), 1, Emgu.CV.CvEnum.BorderType.Reflect, new MCvScalar(255));

                Itt.TryDecode(list, imgout);
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            Emgu.CV.Util.VectorOfVectorOfPoint contours = new Emgu.CV.Util.VectorOfVectorOfPoint();
            Mat mat = new Mat();

            CvInvoke.FindContours(imgout, contours, mat, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);


            for (int i = 0; i < contours.Size; i++)
            {
                Rectangle   rect     = CvInvoke.BoundingRectangle(contours[i]);
                RotatedRect box      = CvInvoke.MinAreaRect(contours[i]);
                PointF[]    Vertices = box.GetVertices();
                //MessageBox.Show(Vertices[0].X.ToString() + "," + Vertices[0].Y.ToString() + " " + Vertices[1].X.ToString() + "," + Vertices[1].Y.ToString());
                //MessageBox.Show(Vertices[2].X.ToString() + "," + Vertices[2].Y.ToString() + " " + Vertices[3].X.ToString() + "," + Vertices[3].Y.ToString());
                //Vector AB
                PointF vecAB = new PointF((Vertices[1].X) - (Vertices[0].X), (Vertices[1].Y) - (Vertices[0].Y));
                PointF vecBC = new PointF((Vertices[2].X) - (Vertices[1].X), (Vertices[2].Y) - (Vertices[1].Y));
                //Modulo de Vab
                double modAB = Math.Sqrt(Math.Pow(vecAB.X, 2) + Math.Pow(vecAB.Y, 2));
                double modBC = Math.Sqrt(Math.Pow(vecBC.X, 2) + Math.Pow(vecBC.Y, 2));
                if (modAB < modBC)
                {
                    vecAB = vecBC;
                    modAB = modBC;
                }
                //MessageBox.Show(vecAB.ToString());
                //VectorHorizontal
                PointF vecHor = new PointF(1, 0);
                //Modulo de Vab
                //double modAB = Math.Sqrt(Math.Pow(vecAB.X, 2) + Math.Pow(vecAB.Y, 2));
                double modHor   = 1.0;
                double proPunto = vecAB.X * vecHor.X;

                double anguloRad = Math.Acos(proPunto / modAB * modHor);
                double anguloDeg = (anguloRad * 180) / Math.PI;
                //MessageBox.Show(anguloDeg.ToString());

                var blob = CvInvoke.BoundingRectangle(contours[i]);
                blob.Y -= 5;
                CvInvoke.PutText(img, "Angulo:" + anguloDeg.ToString(), blob.Location, Emgu.CV.CvEnum.FontFace.HersheySimplex, 0.5, new MCvScalar(255, 255, 255));
                //CvInvoke.PutText(imgout, "Angulo: " + anguloDeg.ToString(), blob.Location, Emgu.CV.CvEnum.FontFace.HersheyPlain, 1.0, new MCvScalar(100));
                pictureBox1.Image = img.ToBitmap();
                //pictureBox2.Image = imgout.ToBitmap();
            }
        }
Esempio n. 23
0
 private void MyFindContours()
 {
     if (originImg != null)
     {
         inputImg = originImg.Convert <Gray, Byte>().ThresholdBinary(new Gray((double)nudThreshold.Value), new Gray(255));
         contours = new Emgu.CV.Util.VectorOfVectorOfPoint();
         Mat hire = new Mat();
         try
         {
             CvInvoke.FindContours(inputImg, contours, hire, (RetrType)cboRetry.SelectedItem, (ChainApproxMethod)cboApprox.SelectedItem);
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         }
     }
 }
        private void btnInfo_Click(object sender, EventArgs e)
        {
            Emgu.CV.Util.VectorOfVectorOfPoint contours = new Emgu.CV.Util.VectorOfVectorOfPoint();
            Mat mat = new Mat();

            CvInvoke.FindContours(imgout, contours, mat, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
            for (int i = 0; i < contours.Size; i++)
            {
                var area = CvInvoke.ContourArea(contours[i]);
                if (area > (int)numericSenCount.Value)
                {
                    var blob = CvInvoke.BoundingRectangle(contours[i]);
                    blob.Y -= 5;
                    CvInvoke.PutText(img, "#:" + (i + 1).ToString(), blob.Location, Emgu.CV.CvEnum.FontFace.HersheySimplex, 0.5, new MCvScalar(255, 255, 255));
                }
            }
            //pictureBox1.Image = img.ToBitmap();
            for (int i = 0; i < contours.Size; i++)
            {
                Rectangle rect = CvInvoke.BoundingRectangle(contours[i]);
                papel       = pictureBox1.CreateGraphics();
                pluma.Width = 5;
                pluma.Color = Color.Green;
                papel.DrawRectangle(pluma, rect);
            }


            if (img != null)
            {
                if (imgout != null)
                {
                    detectarCentro();
                }
                else
                {
                    detectarBorde();
                    detectarCentro();
                }
            }
            else
            {
                MessageBox.Show("Debe cargar una imagen antes de buscar el borde", "Sin imagen", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 25
0
        /// <summary>
        /// 轮廓提取函数
        /// 20180416 修改人 於景瞵
        /// </summary>
        /// <param name="srcimage"> 原始图像</param>
        /// <param name="OutImage"> 存放轮廓图像</param>
        /// <returns> 返回目标图像</returns>
        private void regCoutour()
        {
            Mat srcimage  = this.FilterImage.Mat.Clone();
            Mat hierarchy = new Mat();

            Emgu.CV.Util.VectorOfVectorOfPoint Coutours = new Emgu.CV.Util.VectorOfVectorOfPoint();
            CvInvoke.FindContours(srcimage, Coutours, hierarchy, RetrType.List, ChainApproxMethod.LinkRuns, new Point(0, 0));
            //imageBox1.Image = b2;

            //List<Rectangle> rects = new List<Rectangle>();
            //开始遍历
            for (int i = 0; i < Coutours.Size; i++)
            {
                //得到这个连通区域的外接矩形
                var rect = CvInvoke.BoundingRectangle(Coutours[i]);
                //var Rect = CvInvoke.MinAreaRect(Coutours[i]);
                //var Area = CvInvoke.ContourArea(Coutours[i]);
                //如果高度不足,或者长宽比太小,认为是无效数据,否则把矩形画到原图上
                if ((rect.Height > 13 && rect.Width > 13) && (rect.Height < srcimage.Rows / 4 || rect.Width < srcimage.Cols / 4) &&
                    rect.Height < srcimage.Rows * 3 / 5 && rect.Left > srcimage.Cols / 6 && rect.Right < srcimage.Cols * 5 / 6 &&
                    rect.Top > srcimage.Rows / 4 && rect.Bottom < srcimage.Rows * 3 / 4)
                {
                    //int a = srcimage.Bitmap.GetPixel(rect.X + rect.Width / 2, rect.Y + rect.Height / 2).B;
                    var Rect = CvInvoke.MinAreaRect(Coutours[i]);
                    var Area = CvInvoke.ContourArea(Coutours[i]);
                    listRects.Add(rect);
                    //if (Area / (Rect.Size.Height * Rect.Size.Width) < 0.8)
                    //    dictRects.Add(rect, "一类");
                    //else if (Rect.Size.Height / Rect.Size.Width < 1.0 / 3.0 || Rect.Size.Height / Rect.Size.Width > 3.0)
                    //    dictRects.Add(rect, "一类");
                    //else if (Area > 2000)
                    //    dictRects.Add(rect, "一类");
                    //else
                    //    dictRects.Add(rect, "二类");
                    //CvInvoke.DrawContours(b1, b3, i, color);
                }
            }

            //foreach (var rect in listRects)
            //{
            //    Mat roiMat = new Mat(FilterImage.Mat,rect.Key);
            //    this.dictCoutours.Add(roiMat, rect.Key);
            //}
        }
Esempio n. 26
0
        //tiền xử lý ảnh đầu vào - out put là ảnh ROI dạng binary
        public Mat Pre_processing(Mat image)
        {
            //resize tất cả ảnh đầu vào về size 500x500
            CvInvoke.Resize(image, image, new Size(500, 500));

            //Step 1: convert rgb->lab(or hsv)
            Image <Lab, byte> imgLab = new Image <Lab, byte>(img.Width, img.Height);

            CvInvoke.CvtColor(image, imgLab, ColorConversion.Rgb2Lab);
            pictureBox_step1.Image = imgLab.ToBitmap();

            //Step 2: Histogram equalization & increase contrast
            imgLab._EqualizeHist();
            imgLab._GammaCorrect(2.4d);
            pictureBox_step2.Image = imgLab.ToBitmap();

            //Split Lab to 3-channel l,a,b
            imgLab.Split();

            //Step 3: Smooth image - loại bỏ nhiễu
            Image <Gray, byte> imgSmooth = new Image <Gray, byte>(img.Width, img.Height);
            Size size = new Size(3, 3);

            CvInvoke.GaussianBlur(imgLab[2], imgSmooth, size, 0, 0);
            pictureBox_step3.Image = imgSmooth.ToBitmap();

            //Step 4: Threshold - chuyển sang ảnh binary để phân đoạn region of interest (ROI)
            Image <Gray, byte> imgThres = new Image <Gray, byte>(img.Width, img.Height);

            CvInvoke.Threshold(imgSmooth, imgThres, Convert.ToInt32(trackBar1.Value), 255, ThresholdType.BinaryInv);
            pictureBox_step4.Image = imgThres.ToBitmap();

            Emgu.CV.Util.VectorOfVectorOfPoint contours = new Emgu.CV.Util.VectorOfVectorOfPoint();                  //tạo 1 contours là 1 vector chứa vector tập hợp các điểm để vẽ contours
            Mat hier = new Mat();                                                                                    //chứa thông tin về hình ảnh như số đường viền, xếp hạng các đường viền theo kích thước, trong ngoài

            Image <Bgr, byte> img_contour = new Image <Bgr, byte>(img.Bitmap);                                       //khai báo ảnh màu để vẽ contours vào - chính là ảnh gốc

            CvInvoke.FindContours(imgThres, contours, hier, RetrType.External, ChainApproxMethod.ChainApproxSimple); //tìm contours, đầu vào là ảnh binary đã phân đoạn, đầu ra là contours tìm đc
            CvInvoke.DrawContours(img_contour, contours, -1, new MCvScalar(0, 0, 255), 1);                           //vẽ contours lên ảnh với biên dạng màu đỏ, độ dày nét 1
            pictureBox_drawContour.Image = img_contour.ToBitmap();

            imgThreshed = imgThres.Mat; //gán ảnh đã phân ngưỡng vào 1 biến toàn cục để sử dụng cho hàm khác
            return(imgThres.Mat);
        }
        public GenerationWindow(Settings settings, Emgu.CV.Util.VectorOfVectorOfPoint contours, Dictionary <String, Emgu.CV.Util.VectorOfVectorOfPoint> features)
        {
            InitializeComponent();
            generatorThread = new BackgroundWorker();
            generatorThread.WorkerReportsProgress      = true;
            generatorThread.WorkerSupportsCancellation = true;
            generatorThread.DoWork             += new DoWorkEventHandler(Generator_DoWork);
            generatorThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Generator_RunWorkerCompleted);
            generatorThread.ProgressChanged    += new ProgressChangedEventHandler(Generator_ProgressChanged);
            DataPass tmp = new DataPass
            {
                settings  = settings,
                objects   = contours,
                inputData = features
            };

            information = tmp;
            generatorThread.RunWorkerAsync(tmp);
        }
 private void Generator_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
     if (e.Error != null)
     {
         MessageBox.Show(e.Error.Message);
     }
     else if (e.Cancelled)
     {
     }
     else
     {
         Emgu.CV.Util.VectorOfVectorOfPoint          temp = (Emgu.CV.Util.VectorOfVectorOfPoint)e.Result;
         Emgu.CV.Image <Emgu.CV.Structure.Bgr, byte> img  = new Emgu.CV.Image <Emgu.CV.Structure.Bgr, byte>(information.settings.Width, information.settings.Height, new Emgu.CV.Structure.Bgr(255, 255, 255));
         Emgu.CV.CvInvoke.DrawContours(img, temp, -1, new Emgu.CV.Structure.MCvScalar(0, 0, 0));
         ImageDisplayWindow displayWindow = new ImageDisplayWindow(img);
         displayWindow.ShowDialog();
         Close();
     }
 }
Esempio n. 29
0
        /// <summary>
        /// Method for transforming the image into black and white
        /// </summary>
        /// <returns>A </returns>
        public Image <Gray, byte> transformPicture(Image <Bgr, byte> picture)
        {
            // Create a new picture
            Image <Gray, byte> result = picture.Convert <Gray, byte>().ThresholdBinary(new Gray(150), new Gray(210));

            // Use the librairy for find the contours
            Emgu.CV.Util.VectorOfVectorOfPoint contours = new Emgu.CV.Util.VectorOfVectorOfPoint();
            Mat hier = new Mat();

            // Find the contours of picture
            CvInvoke.FindContours(result, contours, hier, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
            // Create a new picture void
            Image <Gray, byte> imgout = new Image <Gray, byte>(result.Width, result.Height, new Gray(0));

            // Draw the contours of the picture
            CvInvoke.DrawContours(imgout, contours, -1, new MCvScalar(255, 0, 0), -1);
            // Return the picture in bitmap
            //return result.Bitmap;
            return(result);
        }
Esempio n. 30
0
        private void FindCricleContours()
        {
            for (int index = 0; index <= nImages - 1; index++)
            {
                Emgu.CV.Util.VectorOfVectorOfPoint ContourInThisImage = new Emgu.CV.Util.VectorOfVectorOfPoint();
                Mat HierarchyInThisImage = new Mat();

                CvInvoke.FindContours(ImagesReadCV[index], ContourInThisImage, HierarchyInThisImage, Emgu.CV.CvEnum.RetrType.Ccomp, ChainApproxMethod.ChainApproxNone);
                ContoursInAllImages.Add(ContourInThisImage);
                HierarchyInAllImages.Add(HierarchyInThisImage);
                if (ContourInThisImage == null)
                {
                    MessageBox.Show("!!");
                }
                CvInvoke.CvtColor(ImagesReadCV[index], ImagesReadCV[index], ColorConversion.Gray2Bgr, 3);
                CvInvoke.DrawContours(ImagesReadCV[index], ContourInThisImage, -1, new MCvScalar(0, 255, 0, 255), 1);
            }
            MessageBox.Show("Done!");
            ReloadImageBox();
        }