Esempio n. 1
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;
            }
        }
Esempio n. 2
0
        private VectorOfPoint DetectHand(Mat processedImage)
        {
            Mat copy = new Mat();

            CvInvoke.CvtColor(processedImage, copy, ColorConversion.Bgr2Hsv);
            /*CvInvoke.InRange(processedImage, new ScalarArray(new MCvScalar(low_H, low_S, low_V)), new ScalarArray(new MCvScalar(high_H, high_S, high_V)), copy);*/
            CvInvoke.InRange(processedImage, new ScalarArray(new MCvScalar(0, 63, 59)), new ScalarArray(new MCvScalar(19, 228, 247)), copy);
            CvInvoke.Erode(copy, copy, null, new System.Drawing.Point(-1, -1), 5, BorderType.Constant, CvInvoke.MorphologyDefaultBorderValue);
            CvInvoke.Dilate(copy, copy, null, new System.Drawing.Point(-1, -1), 5, BorderType.Constant, CvInvoke.MorphologyDefaultBorderValue);

            VectorOfVectorOfPoint contours       = new VectorOfVectorOfPoint();
            VectorOfPoint         biggestContour = new VectorOfPoint();

            CvInvoke.FindContours(copy, contours, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);

            if (contours.Size > 0)
            {
                biggestContour = contours[0];
                for (int i = 0; i < contours.Size; i++)
                {
                    if (contours[i].Size > biggestContour.Size)
                    {
                        biggestContour = contours[i];
                    }
                }
                CvInvoke.ApproxPolyDP(biggestContour, biggestContour, 0.0015, true);
                handFrames++;
                return(biggestContour);
            }
            return(new VectorOfPoint());
        }
Esempio n. 3
0
        public Image <Bgr, byte> findrectangles(Image <Bgr, byte> image, int n1, int n2, int thicc, int tresh, int delta)
        {
            Image <Gray, byte> binarizedImage = blur(image, n1, n2);
            var contours = new VectorOfVectorOfPoint();

            CvInvoke.FindContours(
                binarizedImage,
                contours,
                null,
                RetrType.List,
                ChainApproxMethod.ChainApproxSimple);

            var contoursImage = image.Copy();

            var approxContour = new VectorOfPoint();

            for (int i = 0; i < contours.Size; i++)
            {
                CvInvoke.ApproxPolyDP(
                    contours[i],
                    approxContour,
                    CvInvoke.ArcLength(contours[i], true) * 0.05,
                    true);

                if (CvInvoke.ContourArea(approxContour, false) > tresh)
                {
                    var points = approxContour.ToArray();
                    if (isRectangle(points, delta) == true)
                    {
                        contoursImage.Draw(CvInvoke.MinAreaRect(approxContour), new Bgr(Color.GreenYellow), thicc);
                    }
                }
            }
            return(contoursImage);
        }
        private static VectorOfVectorOfPoint FindBiggestContour(Mat image)
        {
            var    biggest        = new VectorOfPoint();
            double max_area       = 0;
            var    contours       = new VectorOfVectorOfPoint();
            var    biggestContour = new VectorOfVectorOfPoint();
            var    hierarchy      = new Mat();

            CvInvoke.FindContours(image, contours, hierarchy, RetrType.Tree, ChainApproxMethod.ChainApproxSimple);
            for (int i = 0; i < contours.Size; ++i)
            {
                var area = CvInvoke.ContourArea(contours[i]);
                if (area > 100)
                {
                    var peri = CvInvoke.ArcLength(contours[i], true);
                    CvInvoke.ApproxPolyDP(contours[i], contours[i], 0.02 * peri, true); //Aproximate to ideal lines
                    if (area > max_area)
                    {
                        biggest  = contours[i];
                        max_area = area;
                    }
                }
            }
            biggestContour.Push(biggest);
            return(biggestContour);
        }
Esempio n. 5
0
        public void _findOutline()
        {
            using (var im = _mat.Clone())
            {
                VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();
                CvInvoke.FindContours(im, contours, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);

                var cts = contours.ToArrayOfArray()
                          .Select(x => CvInvoke.ConvexHull(x.Select(y => new PointF(y.X, y.Y)).ToArray())).ToArray();

                var cnt = cts.OrderByDescending(z => CvInvoke.ContourArea(new VectorOfPointF(z))).ToList();

                var result = new VectorOfPointF();

                foreach (var c in cnt)
                {
                    var vop  = new VectorOfPointF(c);
                    var peri = CvInvoke.ArcLength(vop, true);

                    var approx = new VectorOfPointF();
                    CvInvoke.ApproxPolyDP(vop, approx, _approxE * peri, true);

                    if (approx.Size == 4)
                    {
                        result = approx;
                        break;
                    }
                }

                _outline = result;
            }
        }
Esempio n. 6
0
        private void DetectShapesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_imgInput == null)
            {
                return;
            }
            try
            {
                var tmpCnt   = ExtractContours(_imgInput);
                var contours = FilterContours(tmpCnt);
                AddContoursToResCollection(_currentFile, _fileSize, contours, true);

                for (var i = 0; i < contours.Size; i++)
                {
                    var perimeter = CvInvoke.ArcLength(contours[i], true);
                    var approx    = new VectorOfPoint();
                    CvInvoke.ApproxPolyDP(contours[i], approx, 0.03 * perimeter, true);
                }
                BuildClusterPack(_currentFile, contours);
                pictureBox1.Image = _imgInput.AsBitmap();
                //pictureBox2.Image = temp.AsBitmap();
            }
            catch (Exception ex)
            {
                listBox1.Items.Add(ex.Message);
            }
        }
Esempio n. 7
0
        public List <List <int[]> > getContours(string pathToImage, double tolerance)
        {
            img = new Image <Gray, byte>(pathToImage);
            UMat uimage = new UMat();

            contours = new VectorOfVectorOfPoint();
            CvInvoke.FindContours(img, contours, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);
            List <List <int[]> > allPoints = new List <List <int[]> >();
            int count = contours.Size;

            nContours = count;
            for (int i = 0; i < count; i++)
            {
                using (VectorOfPoint contour = contours[i])
                    using (VectorOfPoint approxContour = new VectorOfPoint())
                    {
                        CvInvoke.ApproxPolyDP(contour, approxContour, CvInvoke.ArcLength(contour, true) * tolerance, true);
                        Point[]      pts        = approxContour.ToArray();
                        List <int[]> contPoints = new List <int[]>();
                        for (int k = 0; k < pts.Length; k++)
                        {
                            int[] pointsCord = new int[2];
                            pointsCord[0] = pts[k].X;
                            pointsCord[1] = pts[k].Y;
                            contPoints.Add(pointsCord);
                        }
                        allPoints.Add(contPoints);
                    }
            }
            return(allPoints);
        }
Esempio n. 8
0
        public void FindBoundPolygon()
        {
            // find convexhull
            PointF[] ps = new PointF[this.slicePoints2d.Count];
            for (int i = 0; i < this.slicePoints2d.Count; i++)
            {
                PointF p = new PointF((float)this.slicePoints2d[i].x, (float)this.slicePoints2d[i].y);
                ps[i] = p;
            }
            PointF[] hull = CvInvoke.ConvexHull(ps);

            // find boundary polygon
            VectorOfPointF hull2 = new VectorOfPointF();

            hull2.Push(hull);
            VectorOfPointF poly = new VectorOfPointF();

            // when inferring # of polygon edge, the 3-rd param can be [0.0005,0.0015], than choose the best(how to define "best"??)
            CvInvoke.ApproxPolyDP(hull2, poly, 0.0003, true);
            for (int i = 0; i < poly.Size; i++)
            {
                this.cornerPoints2d.Add(new MyVector2(poly[i].X, poly[i].Y));
            }

            // unproject to 3d
            foreach (MyVector2 corner2d in this.cornerPoints2d)
            {
                MyVector3 corner3d = frame.GetPointSpaceCoord(new MyVector3(corner2d, 0.0));
                this.cornerPoints3d.Add(corner3d);
            }
        }
        private Point[] GetLargestContour(VectorOfVectorOfPoint contours)
        {
            Point[] largestContour = new Point[0];
            var     maxPeri        = 0.0;

            for (int i = 0; i < contours.Size; i++)
            {
                var contourVector = contours[i];
                using var contour = new VectorOfPoint();

                var peri = CvInvoke.ArcLength(contourVector, true);
                var area = CvInvoke.ContourArea(contourVector);
                CvInvoke.ApproxPolyDP(contourVector, contour, 0.1 * peri, true);

                if (contour != null) // && contour.ToArray().Length == 4 && CvInvoke.IsContourConvex(contour)
                {
                    if (peri > maxPeri)
                    {
                        largestContour = contour.ToArray();
                        maxPeri        = peri;
                    }
                }
            }

            return(largestContour);
        }
Esempio n. 10
0
        private void AutoCrop(string path)
        {
            using var image = new Image <Bgr, byte>(path);
            // Grayscale
            var grayScaleImage = image.Convert <Gray, byte>();

            // Applying GaussianBlur
            var blurredImage = grayScaleImage.SmoothGaussian(5, 5, 0, 0);

            // OR
            CvInvoke.GaussianBlur(grayScaleImage, blurredImage, new Size(5, 5), 0);

            // Applying Canny algorithm
            var cannyImage = new UMat();

            CvInvoke.Canny(blurredImage, cannyImage, 50, 150);

            // Finding largest contours
            var contours = new VectorOfVectorOfPointF();

            CvInvoke.FindContours(cannyImage, contours, null, RetrType.Tree, ChainApproxMethod.ChainApproxSimple);

            for (int i = 0; i < contours.Size; i++)
            {
                var contourVector = contours[i];
                using var contour = new VectorOfPoint();
                var peri = CvInvoke.ArcLength(contourVector, true);
                CvInvoke.ApproxPolyDP(contourVector, contour, 0.1 * peri, true);
                if (contour.ToArray().Length == 4 && CvInvoke.IsContourConvex(contour))
                {
                    Debug.WriteLine(contour.ToString());
                    // return contour;
                }
            }
        }
        public static List <Triangle2DF> GetTraingles(UMat thresholeded)
        {
            List <Triangle2DF> _triangleList = new List <Triangle2DF>();

            using (VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint())
            {
                //try to find contours on previously prepared image -->
                CvInvoke.FindContours(thresholeded, contours, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);
                int count = contours.Size;
                for (int i = 0; i < count; i++)
                {
                    using (VectorOfPoint contour = contours[i])
                        using (VectorOfPoint approxContour = new VectorOfPoint())
                        {
                            CvInvoke.ApproxPolyDP(contour, approxContour, CvInvoke.ArcLength(contour, true) * 0.04, true);
                            if (CvInvoke.ContourArea(approxContour, false) > 1)
                            {
                                //triangle has 3 contours -->
                                if (approxContour.Size == 3)
                                {
                                    Point[] pts = approxContour.ToArray();
                                    _triangleList.Add(new Triangle2DF(
                                                          pts[0],
                                                          pts[1],
                                                          pts[2]
                                                          ));
                                }
                            }
                        }
                }
            }
            return(_triangleList);
        }
Esempio n. 12
0
        public static List <VectorOfPoint> GetContours(Image <Gray, Byte> image, ChainApproxMethod apxMethod = ChainApproxMethod.ChainApproxSimple, RetrType retrievalType = RetrType.List, double accuracy = 0.001d, double minimumArea = 10)
        {
            List <VectorOfPoint> convertedContours = new List <VectorOfPoint>();

            using (VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint())
            {
                using (Image <Gray, Byte> tempImage = image.Copy())
                {
                    CvInvoke.FindContours(tempImage, contours, null, retrievalType, apxMethod);
                }

                int count = contours.Size;
                for (int i = 0; i < count; i++)
                {
                    using (VectorOfPoint contour = contours[i])
                    {
                        VectorOfPoint approxContour = new VectorOfPoint();
                        CvInvoke.ApproxPolyDP(contour, approxContour, accuracy, false);
                        if (CvInvoke.ContourArea(approxContour, false) > minimumArea)
                        {
                            convertedContours.Add(approxContour);
                        }
                    }
                }
            }

            return(convertedContours);
        }
Esempio n. 13
0
        private Mat CannyShapeDetection(Mat frame)
        {
            Mat returnImg = new Mat(frame.Rows, frame.Cols, frame.Depth, frame.NumberOfChannels);

            CvInvoke.Canny(frame, returnImg, cannyThreshold, cannyThresholdLinking);

            List <Triangle2DF> triangleList = new List <Triangle2DF>();

            using (VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint()) {
                CvInvoke.FindContours(returnImg, contours, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);
                int count = contours.Size;
                for (int i = 0; i < count; i++)
                {
                    using (VectorOfPoint contour = contours[i])
                        using (VectorOfPoint approxContour = new VectorOfPoint()) {
                            CvInvoke.ApproxPolyDP(contour, approxContour, CvInvoke.ArcLength(contour, true) * 0.05, true);
                            if (CvInvoke.ContourArea(approxContour, false) > 250)
                            {
                                if (approxContour.Size == 3)
                                {
                                    var pts = approxContour.ToArray();
                                    triangleList.Add(new Triangle2DF(pts[0], pts[1], pts[2]));
                                }
                            }
                        }
                }
            }
            foreach (var triangle in triangleList)
            {
                CvInvoke.Polylines(returnImg, Array.ConvertAll(triangle.GetVertices(), System.Drawing.Point.Round), true, new MCvScalar(255));
            }

            return(returnImg);
        }
Esempio n. 14
0
        private void FindGlassTopContour()
        {
            VectorOfPoint contour              = new VectorOfPoint();
            VectorOfPoint approxContour        = new VectorOfPoint();
            VectorOfPoint longestContour       = new VectorOfPoint();
            VectorOfPoint longestContourApprox = new VectorOfPoint();

            int maxLength = 0;

            for (int i = 0; i < _contours.Size; i++)
            {
                contour = _contours[i];
                CvInvoke.ApproxPolyDP(contour, approxContour, CvInvoke.ArcLength(contour, true) * 0.1, true);

                if (approxContour.Size == 2)
                {
                    if ((approxContour.ToArray()[0].Y > _topLiquidPoint1.Y) ||
                        (approxContour.ToArray()[1].Y > _topLiquidPoint2.Y))
                    {
                        continue;
                    }
                    if (maxLength < (int)CvInvoke.ArcLength(approxContour, false))
                    {
                        maxLength            = (int)CvInvoke.ArcLength(approxContour, false);
                        longestContour       = contour;
                        longestContourApprox = approxContour;
                    }
                }
            }

            _glassTopContour       = longestContour;
            _approxGlassTopContour = approxContour;
        }
Esempio n. 15
0
        private static List <RotatedRect> LineCorners(Image <Gray, byte> mImgThreshold)
        {
            List <RotatedRect> boxList = new List <RotatedRect>();

            using (VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint())
            {
                CvInvoke.FindContours(mImgThreshold, contours, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);
                var count = contours.Size;
                for (var i = 0; i < count; i++)
                {
                    using (VectorOfPoint contour = contours[i])
                        using (VectorOfPoint approxContour = new VectorOfPoint())
                        {
                            CvInvoke.ApproxPolyDP(contour, approxContour, CvInvoke.ArcLength(contour, true) * 0.05, true);
                            //if (CvInvoke.ContourArea(approxContour, false) < 10) //only consider contours with area greater than 250
                            // continue;

                            if (approxContour.Size != 2) // line
                            {
                                continue;
                            }
                            if (approxContour[1].X - approxContour[0].X < 5
//                              || approxContour[1].Y - approxContour[0].Y < 2
                                )
                            {
                                continue;
                            }

                            boxList.Add(CvInvoke.MinAreaRect(approxContour));
                        }
                }
            }

            return(boxList);
        }
Esempio n. 16
0
        private IEnumerable <Rectangle> GetBoundariesForProcessedImage(Mat edges)
        {
            List <Rectangle> boxList = new List <Rectangle>();

            using (VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint())
            {
                CvInvoke.FindContours(edges, contours, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);
                int contourCount = contours.Size;
                for (int i = 0; i < contourCount; i++)
                {
                    using (VectorOfPoint approxContour = new VectorOfPoint())
                        using (VectorOfPoint approx = contours[i])
                        {
                            CvInvoke.ApproxPolyDP(approx, approxContour, CvInvoke.ArcLength(approx, true) * 0.035, true);
                            Point[]         pts         = approxContour.ToArray();
                            LineSegment2D[] edgesList   = PointCollection.PolyLine(pts, true);
                            double          contourArea = CvInvoke.ContourArea(approxContour, true);
                            if (contourArea >= 500 && contourArea <= edges.Width * edges.Height / 5.0)
                            {
                                Rectangle contourRectangle = GetRectangleFromContour(approxContour, edgesList);
                                if (contourRectangle != default(Rectangle))
                                {
                                    boxList.Add(contourRectangle);
                                }
                            }
                        }
                }
            }

            return(boxList);
        }
        public Image <Gray, Byte> RescaleImage(Image <Gray, Byte> image)
        {
            var contours  = new VectorOfVectorOfPoint();
            var hierarchy = new Mat();

            CvInvoke.FindContours(image, contours, hierarchy, Emgu.CV.CvEnum.RetrType.Tree, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
            double largestArea = 0;
            int    index       = -1;

            for (int i = 0; i < contours.Size; i++)
            {
                double a = CvInvoke.ContourArea(contours[i], false);
                if (a > largestArea)
                {
                    largestArea = a;
                    index       = i;
                }
            }
            VectorOfPoint poly = new VectorOfPoint();

            CvInvoke.ApproxPolyDP(contours[index], poly, 3, true);
            Rectangle rect = CvInvoke.BoundingRectangle(poly);

            image.ROI = rect;
            var croppedImage = new Image <Gray, Byte>(image.Width, image.Height);
            var resizedImage = new Image <Gray, Byte>(Width, Height);

            croppedImage = image.Copy();
            CvInvoke.Resize(croppedImage, resizedImage, new Size(Width, Height));
            return(resizedImage);
        }
        private void detectShapeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (imgInput == null)
            {
                return;
            }

            try
            {
                var tempImg = imgInput.SmoothGaussian(5).Convert <Gray, byte>().ThresholdBinaryInv(new Gray(230), new Gray(255));
                VectorOfVectorOfPoint countors = new VectorOfVectorOfPoint();
                Mat m = new Mat();
                CvInvoke.FindContours(tempImg, countors, m, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);
                for (int i = 0; i < countors.Size; i++)
                {
                    double        perimeter = CvInvoke.ArcLength(countors[i], true);
                    VectorOfPoint approx    = new VectorOfPoint();
                    CvInvoke.ApproxPolyDP(countors[i], approx, 0.04 * perimeter, true);
                    CvInvoke.DrawContours(imgInput, countors, i, new MCvScalar(0, 0, 255), 2);

                    //moments center of the shape
                    var moments = CvInvoke.Moments(countors[i]);
                    int x       = (int)(moments.M10 / moments.M00);
                    int y       = (int)(moments.M01 / moments.M00);

                    if (approx.Size == 3)
                    {
                        CvInvoke.PutText(imgInput, "Triangle", new Point(x, y), Emgu.CV.CvEnum.FontFace.HersheySimplex, 0.5, new MCvScalar(0, 0, 255), 2);
                    }
                    if (approx.Size == 4)
                    {
                        Rectangle rec = CvInvoke.BoundingRectangle(countors[i]);
                        double    ar  = (double)rec.Height / rec.Width;

                        if (ar >= 0.95 && ar <= 1.05)
                        {
                            CvInvoke.PutText(imgInput, "Square", new Point(x, y), Emgu.CV.CvEnum.FontFace.HersheySimplex, 0.5, new MCvScalar(0, 0, 255), 2);
                        }
                        else
                        {
                            CvInvoke.PutText(imgInput, "Rectangle", new Point(x, y), Emgu.CV.CvEnum.FontFace.HersheySimplex, 0.5, new MCvScalar(0, 0, 255), 2);
                        }
                    }
                    if (approx.Size == 6)
                    {
                        CvInvoke.PutText(imgInput, "Hexagon", new Point(x, y), Emgu.CV.CvEnum.FontFace.HersheySimplex, 0.5, new MCvScalar(0, 0, 255), 2);
                    }
                    if (approx.Size > 6)
                    {
                        CvInvoke.PutText(imgInput, "Circle", new Point(x, y), Emgu.CV.CvEnum.FontFace.HersheySimplex, 0.5, new MCvScalar(0, 0, 255), 2);
                    }
                    pictureBox2.Image = imgInput.ToBitmap();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 19
0
        private static VectorOfPoint getLinkedContoursOfImage(VectorOfPoint contour)
        {
            VectorOfPoint approxContour = new VectorOfPoint();

            CvInvoke.ApproxPolyDP(contour, approxContour, CvInvoke.ArcLength(contour, true) * 0.05, true);

            return(approxContour);
        }
Esempio n. 20
0
        public static List <Point> ApproximationPoints(List <Point> points)
        {
            var           points1       = new Points(points);
            var           drawingPoints = points1.ConvertToDrawingPoints();
            var           vectorPoints  = new VectorOfPoint(drawingPoints);
            VectorOfPoint approximation = new VectorOfPoint();

            CvInvoke.ApproxPolyDP(vectorPoints, approximation, DataHandler.FindMaxInAllData(points).Count * 0.03, true);
            return(ConvertApproximationToPoints(approximation));
        }
Esempio n. 21
0
 private void fnFindTriangleRect()
 {
     triangleRectImage = img.CopyBlank();
     using (VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint())
     {
         CvInvoke.FindContours(cannyEdges, contours, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);
         int count = contours.Size;
         for (int i = 0; i < count; i++)
         {
             using (VectorOfPoint contour = contours[i])
                 using (VectorOfPoint approxContour = new VectorOfPoint())
                 {
                     CvInvoke.ApproxPolyDP(contour, approxContour, CvInvoke.ArcLength(contour, true) * 0.05, true);
                     if (CvInvoke.ContourArea(approxContour, false) > 250) //only consider contour with area > 250
                     {
                         if (approxContour.Size == 3)                      //The contour has 3 vertices, is a triangle
                         {
                             Point[] pts = approxContour.ToArray();
                             triangleList.Add(new Triangle2DF(pts[0], pts[1], pts[2]));
                         }
                         else if (approxContour.Size == 4) // The contour has 4 vertices
                         {
                             #region Determine if all the angles in the contours are within [80,100] degree
                             bool            isRectangle = true;
                             Point[]         pts         = approxContour.ToArray();
                             LineSegment2D[] edges       = PointCollection.PolyLine(pts, true);
                             for (int j = 0; j < edges.Length; j++)
                             {
                                 double dAngle = Math.Abs(edges[(j + 1) % edges.Length].GetExteriorAngleDegree(edges[j]));
                                 if (dAngle < 80 || dAngle > 100)
                                 {
                                     isRectangle = false;
                                     break;
                                 }
                             }
                             #endregion
                             if (isRectangle)
                             {
                                 boxList.Add(CvInvoke.MinAreaRect(approxContour));
                             }
                         }
                     }
                 }
         }
     }
     foreach (Triangle2DF triangle in triangleList)
     {
         triangleRectImage.Draw(triangle, new Bgr(Color.DarkBlue), 2);
     }
     foreach (RotatedRect box in boxList)
     {
         triangleRectImage.Draw(box, new Bgr(Color.Red), 2);
     }
     ImgBox_Triangle_Rect.Image = triangleRectImage.Bitmap;
 }
        private void shapeDetectorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ActiveMdiChild is ImageView)
            {
                string shape;

                // Variables
                Image <Gray, byte>    gray     = ((ImageView)ActiveMdiChild).Mat.ToImage <Gray, byte>();
                Image <Gray, byte>    thresh   = ((ImageView)ActiveMdiChild).Mat.ToImage <Gray, byte>();
                VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();

                // Smoothing and Thresholding
                gray = gray.SmoothGaussian(3);
                CvInvoke.Threshold(gray, thresh, 127, 255, ThresholdType.Binary);

                // Calling findContours from threshold
                CvInvoke.FindContours(gray, contours, new Mat(), RetrType.List, ChainApproxMethod.ChainApproxSimple);

                // Getting contour from vector
                VectorOfPoint cnt    = contours[0];
                VectorOfPoint approx = new VectorOfPoint();

                CvInvoke.ApproxPolyDP(cnt, approx, 3, true);
                Rectangle rect        = CvInvoke.BoundingRectangle(cnt);
                double    aspectRatio = (double)(rect.Width) / rect.Height;

                // Detecting shape using approximation of polygon
                if (approx.Size == 3)
                {
                    shape = "triangle";
                }
                else if (approx.Size == 4)
                {
                    if (aspectRatio >= 0.95 && aspectRatio <= 1.05)
                    {
                        shape = "square";
                    }
                    else
                    {
                        shape = "rectangle";
                    }
                }
                else
                {
                    shape = "circle";
                }

                shapeDetectionView = new ShapeDetectionView(((ImageView)ActiveMdiChild).FileName, shape);
                shapeDetectionView.ShowDialog();
            }
            else
            {
                MessageBox.Show("Image shold be selected!", "Filtering Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }
        }
Esempio n. 23
0
        public Image <Bgr, byte> Lab4Func(int t = 0, double trhld = 80, double minzone = 50)
        {
            var grayImage      = MainImageExp.Convert <Gray, byte>();
            int kernelSize     = 5;                           // радиусразмытия
            var bluredImage    = grayImage.SmoothGaussian(kernelSize);
            var threshold      = new Gray(trhld);             // пороговоезначение
            var color          = new Gray(255);               // этим цветомбудут закрашены пиксели,имеющие значение >threshold
            var binarizedImage = bluredImage.ThresholdBinary(threshold, color);
            var contours       = new VectorOfVectorOfPoint(); // контейнер для хранения контуров

            CvInvoke.FindContours(
                binarizedImage, // исходное чёрно-белое изображение
                contours,       // найденные контуры
                null,           // объект для хранения иерархии контуров (в данном случае не используется)
                RetrType.List,  // структура возвращаемых данных (в данном случае список)
                ChainApproxMethod.ChainApproxSimple);

            var contoursImage = MainImageExp.CopyBlank();

            var approxContour = new VectorOfPoint();

            ShT = 0;
            ShR = 0;
            for (int i = 0; i < contours.Size; i++)
            {
                CvInvoke.ApproxPolyDP(
                    contours[i],                                  // исходныйконтур
                    approxContour,                                // контурпослеаппроксимации
                    CvInvoke.ArcLength(contours[i], true) * 0.05, // точностьаппроксимации, прямо//пропорциональнаяплощадиконтура
                    true);                                        // контур становится закрытым (первая и последняя точки соединяются)}
                if (CvInvoke.ContourArea(approxContour, false) > minzone)
                {
                    if (approxContour.Size == 3 && (t == 3 || t == 0))
                    {
                        ShT++;
                        var points = approxContour.ToArray();
                        contoursImage.Draw(new Triangle2DF(points[0], points[1], points[2]),
                                           new Bgr(Color.GreenYellow), 2);
                    }
                    if (approxContour.Size == 4 && (t == 4 || t == 0))
                    {
                        var points = approxContour.ToArray();
                        if (isRectangle(points) == true)
                        {
                            ShR++;
                            contoursImage.Draw(CvInvoke.MinAreaRect(approxContour),
                                               new Bgr(Color.GreenYellow), 2);
                        }
                    }
                }
            }

            MainImageExp = contoursImage.Convert <Bgr, byte>();
            return(MainImageExp);
        }
Esempio n. 24
0
        public Image <Bgr, byte> GetPalm(Mat mask)
        {
            int width  = mask.Width;
            int height = mask.Height;
            var temp   = new Mat();
            var result = mask.ToImage <Bgr, byte>();
            VectorOfVectorOfPoint contours       = new VectorOfVectorOfPoint();
            VectorOfPoint         biggestContour = new VectorOfPoint();

            CvInvoke.FindContours(mask, contours, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);
            if (contours.Size > 0)
            {
                biggestContour = contours[0];
                for (int i = 0; i < contours.Size; i++)
                {
                    if (contours[i].Size > biggestContour.Size)
                    {
                        biggestContour = contours[i];
                    }
                }
            }
            if (biggestContour.Size != 0)
            {
                //Gaunam rankos konturus
                CvInvoke.ApproxPolyDP(biggestContour, biggestContour, 0.00000001, false);
                var         points = biggestContour.ToArray();
                VectorOfInt hull   = new VectorOfInt();
                //find the palm hand area using convexitydefect
                CvInvoke.ConvexHull(biggestContour, hull, true);
                var box     = CvInvoke.MinAreaRect(biggestContour);
                Mat defects = new Mat();
                CvInvoke.ConvexityDefects(biggestContour, hull, defects);

                if (!defects.IsEmpty)
                {
                    //Data from Mat are not directly readable so we convert it to Matrix<>
                    Matrix <int> m = new Matrix <int>(defects.Rows, defects.Cols, defects.NumberOfChannels);
                    defects.CopyTo(m);

                    for (int i = 0; i < m.Rows; i++)
                    {
                        int   startIdx   = m.Data[i, 0];
                        int   endIdx     = m.Data[i, 1];
                        Point startPoint = points[startIdx];
                        Point endPoint   = points[endIdx];
                        //draw  a line connecting the convexity defect start point and end point in thin red line
                        CvInvoke.Line(result, startPoint, endPoint, new MCvScalar(0, 0, 255));
                    }
                }
            }

            return(result);
        }
        public static VectorOfVectorOfPoint getApproxContour(VectorOfVectorOfPoint vectors)
        {
            var approxContours = new VectorOfVectorOfPoint();

            for (int i = 0; i < vectors.Size; i++)
            {
                var contour = new VectorOfPoint();
                CvInvoke.ApproxPolyDP(vectors[i], contour, CvInvoke.ArcLength(vectors[i], true) * 0.05, true);
                approxContours.Push(contour);
            }
            return(approxContours);
        }
Esempio n. 26
0
 public bool Is_Triangle(VectorOfPoint hull)
 {
     CvInvoke.ApproxPolyDP(hull, hull, 10, true);
     if (hull.Size == 3)
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Esempio n. 27
0
        public static double Solidity(VectorOfPoint contour, VectorOfPoint convexHull)
        {
            double contourArea = CvInvoke.ContourArea(contour);

            VectorOfPoint vpHull = new VectorOfPoint();

            CvInvoke.ApproxPolyDP(convexHull, vpHull, 0.001, true);

            double hullArea = Math.Abs(CvInvoke.ContourArea(vpHull));

            return(contourArea / hullArea);
        }
Esempio n. 28
0
    //fonction pour dessiner les limits des obj et creer leur centroide
    List <RotatedRect> DrawRectangle(Image <Gray, byte> imageSeuil, String name)
    {
        List <RotatedRect> boxList = new List <RotatedRect>();

        contours = new VectorOfVectorOfPoint();
        Mat m = new Mat();

        CvInvoke.FindContours(imageSeuil, contours, m, Emgu.CV.CvEnum.RetrType.External, Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);

        for (int i = 0; i < contours.Size; i++)
        {
            double        perimeter = CvInvoke.ArcLength(contours[i], true);
            VectorOfPoint approx    = new VectorOfPoint();
            CvInvoke.ApproxPolyDP(contours[i], approx, 0.04 * perimeter, true);
            if (CvInvoke.ContourArea(approx, false) > 250) //only consider contours with area greater than 250
            {
                if (approx.Size == 4)                      //The contour has 4 vertices, it is a rectangle
                {
                    bool            isRectangle = true;
                    Point[]         pts         = approx.ToArray();
                    LineSegment2D[] edges       = PointCollection.PolyLine(pts, true);

                    for (int j = 0; j < edges.Length; j++)
                    {
                        double angle = Math.Abs(
                            edges[(j + 1) % edges.Length].GetExteriorAngleDegree(edges[j]));
                        if (angle < 80 || angle > 100)
                        {
                            isRectangle = false;
                            break;
                        }
                    }
                    if (isRectangle)
                    {
                        boxList.Add(CvInvoke.MinAreaRect(approx));
                    }
                }

                foreach (RotatedRect box in boxList)
                {
                    CvInvoke.Polylines(imageMat, Array.ConvertAll(box.GetVertices(), Point.Round), true,
                                       new Bgr(System.Drawing.Color.Blue).MCvScalar, 2);
                    var moments = CvInvoke.Moments(contours[i]);
                    int x       = (int)(moments.M10 / moments.M00);
                    int y       = (int)(moments.M01 / moments.M00);
                    CvInvoke.PutText(imageMat, name, new Point(x, y), Emgu.CV.CvEnum.FontFace.HersheySimplex, 0.5, new MCvScalar(0, 0, 255), 2);
                }
            }
        }

        return(boxList);
    }
Esempio n. 29
0
        private Triangle2DF TriangleFromInfrared(Mat infraredMat)
        {
            Image <Gray, short> infraredImg = infraredMat.ToImage <Gray, short>();
            var smoothedInfraredImg         = infraredImg.PyrDown();

            smoothedInfraredImg = smoothedInfraredImg.PyrUp();

            using (Mat convertedMat = new Mat(infraredMat.Size, DepthType.Cv8U, 1))
                using (Mat multiplierMat = new Mat(infraredMat.Size, DepthType.Cv8U, 1)) {
                    infraredImg.Mat.ConvertTo(convertedMat, DepthType.Cv8U, 1d / 256d);

                    multiplierMat.SetTo(new MCvScalar(infraMultiplier));

                    CvInvoke.Multiply(convertedMat, multiplierMat, convertedMat);

                    Mat thresholdMat = new Mat(infraredMat.Size, DepthType.Cv8U, 1);
                    CvInvoke.Threshold(convertedMat, thresholdMat, 230, 255, ThresholdType.Binary);

                    List <Triangle2DF> triangleList = new List <Triangle2DF>();

                    using (VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint()) {
                        CvInvoke.FindContours(thresholdMat, contours, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);
                        int count = contours.Size;
                        for (int i = 0; i < count; i++)
                        {
                            using (VectorOfPoint contour = contours[i])
                                using (VectorOfPoint approxContour = new VectorOfPoint()) {
                                    CvInvoke.ApproxPolyDP(contour, approxContour, CvInvoke.ArcLength(contour, true) * 0.05, true);
                                    if (CvInvoke.ContourArea(approxContour, false) > 250)
                                    {
                                        if (approxContour.Size == 3)
                                        {
                                            var pts = approxContour.ToArray();
                                            triangleList.Add(new Triangle2DF(pts[0], pts[1], pts[2]));
                                        }
                                    }
                                }
                        }
                    }

                    var biggestTri = triangleList.OrderBy((tri) => tri.Area).FirstOrDefault();
                    CvInvoke.Polylines(thresholdMat, Array.ConvertAll(biggestTri.GetVertices(), System.Drawing.Point.Round), true, new MCvScalar(255));

                    foreach (var triangle in triangleList)
                    {
                        CvInvoke.Polylines(convertedMat, Array.ConvertAll(triangle.GetVertices(), System.Drawing.Point.Round), true, new MCvScalar(255));
                    }
                    //CvInvoke.Imshow("threshold", thresholdMat);

                    return(biggestTri);
                }
        }
Esempio n. 30
0
        public void FindRectangles()
        {
            Image <Gray, byte> img = originalMat.ToImage <Bgr, byte>().Canny(127, 255);

            VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();
            Mat mat = new Mat();

            CvInvoke.FindContours(img, contours, mat, RetrType.External, ChainApproxMethod.ChainApproxSimple);

            VectorOfPoint         contour = new VectorOfPoint();
            VectorOfVectorOfPoint squares = new VectorOfVectorOfPoint();

            for (int i = 0; i < contours.Size; i++)
            {
                CvInvoke.ApproxPolyDP(contours[i], contour, CvInvoke.ArcLength(contours[i], true) * 0.02, true);
                if (contour.Size == 4 && Math.Abs(CvInvoke.ContourArea(contour)) > SearchSize && CvInvoke.IsContourConvex(contour))
                {
                    Rectangle rect     = CvInvoke.BoundingRectangle(contour);
                    Rectangle maskRect = new Rectangle(rect.Location, rect.Size);

                    Size inflateSize = new Size((int)(maskRect.Width * -0.1), (int)(maskRect.Height * -0.1));
                    maskRect.Inflate(inflateSize);

                    Mat shapeMat = new Mat(originalMat, maskRect);

                    int[] colorScalars = CvInvoke.Mean(shapeMat).ToArray().Select(x => (int)x).ToArray();
                    Color color        = Color.FromArgb(255, colorScalars[2], colorScalars[1], colorScalars[0]);

                    if (color.ToArgb() == Color.ToArgb())
                    {
                        double maxCosine = 0.0;

                        for (int j = 2; j < 5; j++)
                        {
                            double cosine = Math.Abs(Angle(contour[j % 4], contour[j - 2], contour[j - 1]));
                            maxCosine = cosine > maxCosine ? cosine : maxCosine;
                        }

                        if (maxCosine < 0.3)
                        {
                            squares.Push(contour);
                        }
                    }
                }
            }

            Image <Bgr, byte> imgOut = new Image <Bgr, byte>(originalImage);

            CvInvoke.DrawContours(imgOut, squares, -1, new MCvScalar(0, 0, 255));
            image.Image = new Bitmap(imgOut.Bitmap);
            imgOut.Dispose();
        }