Exemple #1
0
        private Mat GetSceleton(Mat grayImage)
        {
            var binary = new Mat();

            Cv2.Threshold(grayImage, binary, 240, 255, ThresholdType.BinaryInv);

            var skel = Mat.Zeros(binary.Rows, binary.Cols, MatType.CV_8UC1).ToMat();
            var temp = new Mat(binary.Cols, binary.Rows, MatType.CV_8UC1);


            var elem = Cv2.GetStructuringElement(StructuringElementShape.Cross,
                                                 new OpenCvSharp.CPlusPlus.Size(3, 3));

            bool done;

            do
            {
                Cv2.MorphologyEx(binary, temp, MorphologyOperation.Open, elem);
                Cv2.BitwiseNot(temp, temp);
                Cv2.BitwiseAnd(binary, temp, temp);
                Cv2.BitwiseOr(skel, temp, skel);
                Cv2.Erode(binary, binary, elem);

                double max;
                double min;
                Cv2.MinMaxLoc(binary, out min, out max);
                done = (max == 0);
            } while (!done);

            return(skel);
        }
 void Erode(Mat image, int number)
 {
     for (int i = 0; i < number; i++)
     {
         Cv2.Erode(image, image, new Mat());
     }
 }
Exemple #3
0
        static void Main(string[] args)
        {
            Mat src    = Cv2.ImRead("card.jpg");
            Mat gray   = new Mat();
            Mat binary = new Mat();
            Mat morp   = new Mat();
            Mat canny  = new Mat();
            Mat dst    = src.Clone();

            Mat kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(3, 3));

            Cv2.CvtColor(src, gray, ColorConversionCodes.BGR2GRAY);
            Cv2.Threshold(gray, binary, 150, 255, ThresholdTypes.Binary);
            Cv2.Dilate(binary, morp, kernel, new Point(-1, -1));
            Cv2.Erode(morp, morp, kernel, new Point(-1, -1), 3);
            Cv2.Dilate(morp, morp, kernel, new Point(-1, -1), 2);
            Cv2.Canny(morp, canny, 0, 0, 3);

            LineSegmentPoint[] lines = Cv2.HoughLinesP(canny, 1, Cv2.PI / 180, 140, 50, 10);

            for (int i = 0; i < lines.Length; i++)
            {
                Cv2.Line(dst, lines[i].P1, lines[i].P2, Scalar.Yellow, 2);
            }

            Cv2.ImShow("dst", dst);
            Cv2.WaitKey(0);
            Cv2.DestroyAllWindows();
        }
Exemple #4
0
        public List <Rect> FindBounds(Mat mask)
        {
            List <Rect> result = new List <Rect>();

            Cv2.Erode(mask, mask, new Mat());
            Cv2.Dilate(mask, mask, new Mat());
            Point[][]        contours;         //vector<vector<Point>> contours;
            HierarchyIndex[] hierarchyIndexes; //vector<Vec4i> hierarchy;
            Cv2.FindContours(
                mask,
                out contours,
                out hierarchyIndexes,
                ContourRetrieval.External,
                ContourChain.ApproxSimple
                );
            var contourIndex = 0;

            while ((contourIndex >= 0) && contours.Length != 0)
            {
                var contour = contours[contourIndex];

                var boundingRect = Cv2.BoundingRect(contour); //Find bounding rect for each contour
                result.Add(boundingRect);
                contourIndex = hierarchyIndexes[contourIndex].Next;
            }
            return(result);
        }
Exemple #5
0
        public Mat BarcodeRegion(Mat src_)
        {
            //Cv2.Resize(src, src, new Size(src.Size().Width / 2, src.Size().Height / 2));
            Mat src = src_.Clone();

            Cv2.CvtColor(src, src, ColorConversionCodes.RGB2GRAY);
            Cv2.GaussianBlur(src, src, new Size(3, 3), 0);
            Mat img_X = new Mat();
            Mat img_Y = new Mat();

            Cv2.Sobel(src, img_X, MatType.CV_16S, 1, 0);
            Cv2.Sobel(src, img_Y, MatType.CV_16S, 0, 1);

            Cv2.ConvertScaleAbs(img_X, img_X, 1, 0);
            Cv2.ConvertScaleAbs(img_Y, img_Y, 1, 0);

            Mat margin = img_X - img_Y;

            //Cv2.ImShow("img_Y", margin);
            //Cv2.WaitKey();
            Cv2.Resize(margin, margin, new Size(margin.Width * 0.3, margin.Height * 1.5), 0, 0, InterpolationFlags.Area);
            Cv2.Blur(margin, margin, new Size(3, 3));
            Cv2.MedianBlur(margin, margin, 3);

            Mat imgthreshold = new Mat();

            Cv2.Threshold(margin, imgthreshold, 80, 255, ThresholdTypes.Binary);
            //Cv2.AdaptiveThreshold(margin, imgthreshold, 255, AdaptiveThresholdTypes.GaussianC, ThresholdTypes.Binary, 3, -1);
            Cv2.ImShow("thresh", imgthreshold);
            Cv2.WaitKey();

            //先在水平方向上膨胀,填充条码中间的空隙
            Mat element = Cv2.GetStructuringElement(MorphShapes.Cross, new Size(5, 1));

            Cv2.MorphologyEx(imgthreshold, imgthreshold, MorphTypes.Dilate, element);
            //在垂直方向上腐蚀,分离条码和字符
            element = Cv2.GetStructuringElement(MorphShapes.Cross, new Size(1, 5));
            Cv2.MorphologyEx(imgthreshold, imgthreshold, MorphTypes.Erode, element);

            //去除字符
            element = Cv2.GetStructuringElement(MorphShapes.Cross, new Size(10, 10));
            Cv2.MorphologyEx(imgthreshold, imgthreshold, MorphTypes.Open, element);
            Cv2.MorphologyEx(imgthreshold, imgthreshold, MorphTypes.Close, element);


            element = Cv2.GetStructuringElement(MorphShapes.Cross, new Size(10, 10));
            Cv2.Erode(imgthreshold, imgthreshold, element);
            Cv2.Erode(imgthreshold, imgthreshold, element);
            Cv2.Dilate(imgthreshold, imgthreshold, element);
            Cv2.Resize(imgthreshold, imgthreshold, new Size(src.Width, src.Height), 0, 0, InterpolationFlags.Area);
            Cv2.ImShow("thresh", imgthreshold);
            Cv2.WaitKey();

            return(imgthreshold);


            //计算每个区域的最大内接矩,然后算其包含图像的黑白区域比例

            //Cv2.Dilate(imgthreshold, imgthreshold, element);
        }
Exemple #6
0
        private static void testBuiltinFilters()
        {
            using (var src = new Mat(@"..\..\Images\Car.jpg", ImreadModes.AnyDepth | ImreadModes.AnyColor))
            {
                using (var dst = new Mat())
                {
                    src.CopyTo(dst);

                    using (new Window("src", image: src))
                    {
                        Cv2.Erode(src, dst, new Mat());
                        using (new Window("Erode", image: dst))
                        {
                            Cv2.Dilate(src, dst, new Mat());
                            using (new Window("Dilate", image: dst))
                            {
                                Cv2.BitwiseNot(src, dst);
                                using (new Window("Invert", image: dst))
                                {
                                    Cv2.WaitKey();
                                }
                            }
                        }
                    }
                }
            }
        }
Exemple #7
0
        public List <Circle> FindCircleBounds(Mat mask)
        {
            List <Circle> result = new List <Circle>();

            Cv2.Erode(mask, mask, new Mat());
            // Cv2.Dilate(mask, mask, new Mat());
            Point[][]        contours;         //vector<vector<Point>> contours;
            HierarchyIndex[] hierarchyIndexes; //vector<Vec4i> hierarchy;
            Cv2.FindContours(
                mask,
                out contours,
                out hierarchyIndexes,
                ContourRetrieval.External,
                ContourChain.ApproxSimple
                );
            var contourIndex = 0;

            while ((contourIndex >= 0) && contours.Length != 0)
            {
                var     contour = contours[contourIndex];
                Point2f center  = new Point2f();
                float   radius;
                Cv2.MinEnclosingCircle(contour, out center, out radius); //Find bounding rect for each contour
                result.Add(new Circle(center.X, center.Y, radius));
                contourIndex = hierarchyIndexes[contourIndex].Next;
            }
            return(result);
        }
        //分水岭分割函数封装
        private Mat waterShed(Mat src, int MEADIANBlUR_KSIZE, Size ELEMENT_SIZE)
        {
            var imageGray   = new Mat();
            var thresh      = new Mat();
            var fg          = new Mat();
            var bgt         = new Mat();
            var bg          = new Mat();
            var marker      = new Mat();
            var marker32    = new Mat();
            var m           = new Mat();
            var res         = new Mat();
            var threshOpen  = new Mat();
            var threshClose = new Mat();

            Cv2.CvtColor(src, imageGray, ColorConversionCodes.BGR2GRAY);
            Cv2.EqualizeHist(imageGray, imageGray);                  //直方图均衡化
            Cv2.MedianBlur(imageGray, imageGray, MEADIANBlUR_KSIZE); //中值滤波
            Cv2.Threshold(imageGray, thresh, 0, 255, ThresholdTypes.Otsu);
            Cv2.Erode(thresh, fg, 0, null, 2);
            Cv2.Dilate(thresh, bgt, 0, null, 3);
            Cv2.Threshold(bgt, bg, 1, 128, ThresholdTypes.BinaryInv);
            marker = fg + bg;
            marker.ConvertTo(marker32, MatType.CV_32SC1);
            Cv2.Watershed(src, marker32);
            Cv2.ConvertScaleAbs(marker32, m);
            Cv2.Threshold(m, thresh, 0, 255, ThresholdTypes.Otsu);
            var element = Cv2.GetStructuringElement(MorphShapes.Rect, ELEMENT_SIZE); //获取自定义核

            Cv2.MorphologyEx(thresh, threshOpen, MorphTypes.Open, element);          //开运算
            Cv2.MorphologyEx(threshOpen, threshClose, MorphTypes.Close, element);    //闭运算;
            Cv2.BitwiseAnd(src, src, res, threshClose);
            return(res);
        }
Exemple #9
0
 private void mnuFilterMorphologyErode_Click(object sender, EventArgs e)
 {
     // 収縮
     Cv2.Erode(_matDisp, _matDisp, null);
     // 画像の描画
     DrawMatImage(_matDisp);
 }
Exemple #10
0
        static void Main(string[] args)
        {
            Mat src   = Cv2.ImRead("colorball.png");
            Mat image = new Mat();
            Mat dst   = src.Clone();

            Mat kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(3, 3));

            Cv2.CvtColor(src, image, ColorConversionCodes.BGR2GRAY);
            Cv2.Dilate(image, image, kernel, new Point(-1, -1), 3);
            Cv2.GaussianBlur(image, image, new Size(13, 13), 3, 3, BorderTypes.Reflect101);
            Cv2.Erode(image, image, kernel, new Point(-1, -1), 3);

            CircleSegment[] circles = Cv2.HoughCircles(image, HoughMethods.Gradient, 1, 100, 100, 35, 0, 0);

            for (int i = 0; i < circles.Length; i++)
            {
                Point center = new Point(circles[i].Center.X, circles[i].Center.Y);

                Cv2.Circle(dst, center, (int)circles[i].Radius, Scalar.White, 3);
                Cv2.Circle(dst, center, 5, Scalar.AntiqueWhite, Cv2.FILLED);
            }

            Cv2.ImShow("dst", dst);
            Cv2.WaitKey(0);
            Cv2.DestroyAllWindows();
        }
 /// <summary>
 /// 腐蚀
 /// </summary>
 /// <param name="image">图片对象</param>
 /// <returns></returns>
 public static Image Corrosion(Image image)
 {
     using (Mat src = new Bitmap(image).ToMat())
     {
         Cv2.Erode(src, src, new Mat());
         return(src.ToBitmap());
     }
 }
    /// <summary>
    /// Called each time the Vuforia state is updated
    /// Tracks the given color and sets the position and rotation of the spraycan
    /// </summary>
    void OnTrackablesUpdated()
    {
        if (mFormatRegistered)
        {
            if (mAccessCameraImage)
            {
                Vuforia.Image image = CameraDevice.Instance.GetCameraImage(mPixelFormat);   // get the current camera image in the given pixel format

                if (image != null)
                {
                #if UNITY_EDITOR
                    inputMat = new Mat(image.Height, image.Width, MatType.CV_8UC1, image.Pixels);
                #else
                    inputMat = new Mat(image.Height, image.Width, MatType.CV_8UC3, image.Pixels);   // store the image's pixels in an OpenCV mat
                #endif

                    Cv2.Resize(inputMat, smallMat, new Size(480, 270));                                                                       // resizing for performance reasons (keep aspect ratio!)
                    Cv2.GaussianBlur(smallMat, blurredMat, new Size(11, 11), 0);                                                              // blur image to reduce noise
                    Cv2.CvtColor(blurredMat, hsvMat, ColorConversionCodes.RGB2HSV);                                                           // convert to HSV colors
                    Cv2.InRange(hsvMat, lowerHSVColor, upperHSVColor, thresholdMat);                                                          // filter out all pixels matching the given HSV range

                    Cv2.Erode(thresholdMat, thresholdMat, Cv2.GetStructuringElement(MorphShapes.Ellipse, new Size(3, 3)), null, 2);           // shave off pixels from blobs to eliminate small blobs
                    Cv2.Dilate(thresholdMat, thresholdMat, Cv2.GetStructuringElement(MorphShapes.Ellipse, new Size(3, 3)), null, 2);          // strengthen the remaining blobs

                    Cv2.FindContours(thresholdMat, out contours, hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple); // detect the blobs and save them as contours

                    if (contours.Length > 0)
                    {
                        Mat contour = contours.Aggregate((i, j) => i.ContourArea() > j.ContourArea() ? i : j);  // find the blob with the biggest ContourArea/Size

                        Point2f point;
                        float   radius;
                        Cv2.MinEnclosingCircle(contour, out point, out radius); // get the radius for passing a final threshold

                        if (radius > 5)
                        {
                            Moments moments = Cv2.Moments(contour); // use moments to calculate the center point of the biggest blob
                            double  area    = moments.M00;
                            double  m01     = moments.M01;
                            double  m10     = moments.M10;

                            double posX = m10 / area;
                            double posY = m01 / area;

                            double rotX = MapValue(posX, 0, 480, -31.5, 31.5);  // map the values to match coordinates usable in Unity
                            double rotY = MapValue(posY, 0, 270, -19.75, 19.75);

                            posX = MapValue(posX, 0, 480, -6, 6);
                            posY = MapValue(posY, 0, 270, 3.5, -3.5);

                            this.transform.localPosition    = new Vector3((float)posX, (float)posY, 10); // apply the changes to position and rotation
                            this.transform.localEulerAngles = new Vector3((float)rotY, (float)rotX, 0);
                        }
                    }
                }
            }
        }
    }
Exemple #13
0
        private static void PreProcessing()
        {
            //Cv2.GaussianBlur(_mask, _mask, new Size(4, 4), 8, 6);
            Cv2.Erode(_mask, _mask, null);
            //Cv2.Erode(_mask, _mask, null);

            Cv2.Dilate(_mask, _mask, null);
            //Cv2.Dilate(_mask, _mask, null);
        }
Exemple #14
0
        // PreProcessing Part
        private Bitmap PreProcessing(Mat img)
        {
            var element = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(5, 5), new OpenCvSharp.Point(0, 0));

            Cv2.Threshold(img, img, 100, 255, ThresholdTypes.Binary);
            Cv2.Erode(img, img, element);
            Cv2.Dilate(img, img, element);

            return(OpenCvSharp.Extensions.BitmapConverter.ToBitmap(img));
        }
Exemple #15
0
        static OpenCvSharp.Point[][] GetCountours(Mat thresholdedImage, int erodeIterations)
        {
            using (var erodedImage = new Mat())
            {
                Cv2.Erode(thresholdedImage, erodedImage, new Mat(), iterations: erodeIterations);

                Cv2.FindContours(erodedImage, out var contours, out var hierarchyIndices, RetrievalModes.List, ContourApproximationModes.ApproxSimple);

                return(contours);
            }
        }
        public static void soften(ref Mat input_image)
        {
            Cv2.MedianBlur(input_image, input_image, 7);

            OpenCvSharp.Point morph_point = new OpenCvSharp.Point(1, 1);
            Mat erodeElement  = Cv2.GetStructuringElement(shape: MorphShapes.Rect, new OpenCvSharp.Size(3, 3));
            Mat dilateElement = Cv2.GetStructuringElement(shape: MorphShapes.Rect, new OpenCvSharp.Size(3, 3));

            Cv2.Erode(input_image, input_image, erodeElement, morph_point, 5, borderType: BorderTypes.Reflect);
            Cv2.Dilate(input_image, input_image, dilateElement, morph_point, 5, borderType: BorderTypes.Reflect);
        }
Exemple #17
0
        public List <Mat> ProcessPuzzle(Mat unwarpedPuzzle)
        {
            Cv2.Erode(unwarpedPuzzle, horzSubtract, kernelHorz);
            Cv2.Dilate(horzSubtract, horzSubtract, kernelHorz);

            Cv2.Erode(unwarpedPuzzle, vertSubtract, kernelVert);
            Cv2.Dilate(vertSubtract, vertSubtract, kernelVert);

            unwarpedSudoku = unwarpedSudoku - (horzSubtract + vertSubtract);

            return(getIndividualBoxes(unwarpedSudoku));
        }
Exemple #18
0
        private static Bitmap PrepareImage(Bitmap image)
        {
            //Mat src = new Mat(@"D:\tesseract4\docs\tables\balans_1kv_2013_21.jpg", ImreadModes.GrayScale);
            //var src = Cv2.ImRead(@"D:\tesseract4\docs\tables\balans_1kv_2013_21.jpg");
            var gray = image.ToGrayscaleMat();

            var bw = new Mat();

            Cv2.AdaptiveThreshold(~gray, bw, 256, AdaptiveThresholdTypes.MeanC, ThresholdTypes.Binary, 25, -2);

            var horizontal = bw.Clone();
            var vertical   = bw.Clone();
            var scale      = 15;

            var horizontalSize      = horizontal.Cols / scale;
            var verticalSize        = vertical.Rows / scale;
            var horizontalStructure = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(horizontalSize, 1));
            var verticalStructure   = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(1, verticalSize));

            Cv2.Erode(horizontal, horizontal, horizontalStructure, new OpenCvSharp.Point(-1, -1));
            Cv2.Dilate(horizontal, horizontal, horizontalStructure, new OpenCvSharp.Point(-1, -1));

            Cv2.Erode(vertical, vertical, verticalStructure, new OpenCvSharp.Point(-1, -1));
            Cv2.Dilate(vertical, vertical, verticalStructure, new OpenCvSharp.Point(-1, -1));

            //SaveImage(vertical, "vertical");

            //Cv2.Canny(src, dst, 50, 200);

            //using (new Window(horizontal))
            //{
            //  Cv2.WaitKey();
            //}
            var mask = horizontal + vertical;
            //SaveImage(mask, "mask");
            var newMask = new Mat();

            Cv2.AdaptiveThreshold(~mask, newMask, 256, AdaptiveThresholdTypes.MeanC, ThresholdTypes.Binary, 7, -2);
            //SaveImage(newMask, "newMask");

            newMask = mask + newMask;

            SaveImage(newMask, "hyperMask");

            //var withOutTable = gray + newMask;

            //SaveImage(withOutTable, "withOutTable");

            return(BitmapConverter.ToBitmap(mask));
        }
Exemple #19
0
        private static void MorphOps(Mat thresh)
        {
            //create structuring element that will be used to "dilate" and "erode" image.
            //the element chosen here is a 3px by 3px rectangle
            var erodeElement = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(3, 3));
            //dilate with larger element so make sure object is nicely visible
            var dilateElement = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(8, 8));

            Cv2.Erode(thresh, thresh, erodeElement);
            Cv2.Erode(thresh, thresh, erodeElement);

            Cv2.Dilate(thresh, thresh, dilateElement);
            Cv2.Dilate(thresh, thresh, dilateElement);
        }
Exemple #20
0
 //腐蚀
 private void BtnChange4_Click(object sender, RoutedEventArgs e)
 {
     using (var src = new Mat(@"..\..\Images\ocv02.jpg", ImreadModes.AnyDepth | ImreadModes.AnyColor))
     {
         Cv2.Erode(src, src, new Mat());
         var         mem = src.ToMemoryStream();
         BitmapImage bmp = new BitmapImage();
         bmp.BeginInit();
         bmp.StreamSource = mem;
         bmp.EndInit();
         imgOutput.Source = bmp;
     }
     SetSource(@"..\..\Images\ocv02.jpg");
 }
Exemple #21
0
        private void GlareDetection(ref System.Drawing.Bitmap image, out System.Drawing.Bitmap mask)
        {
            mask = null;

            Mat hsv = new Mat();
            Mat src = BitmapConverter.ToMat(image);

            Cv2.CvtColor(src, hsv, ColorConversionCodes.BGR2HSV);
            Mat[] planes;
            Cv2.Split(hsv, out planes);
            Cv2.ImWrite(@"C:\temp\hImage.png", planes[0]);
            Cv2.ImWrite(@"C:\temp\sImage.png", planes[1]);
            Cv2.ImWrite(@"C:\temp\vImage.png", planes[2]);
            mask = BitmapConverter.ToBitmap(planes[2]);

            Mat nonSat = new Mat(new OpenCvSharp.Size(src.Width, src.Height), MatType.CV_8UC1, 0);

            //nonSat = Cv2.Threshold(planes[1], nonSat, 180, 255, ThresholdTypes.Binary);
            for (int i = 0; i < planes[1].Cols; i++)
            {
                for (int j = 0; j < planes[1].Rows; j++)
                {
                    byte e = planes[1].Get <byte>(j, i);
                    byte v = planes[2].Get <byte>(j, i);
                    if (e < 150 && v > 220)
                    {
                        nonSat.Set <byte>(j, i, 255);
                    }
                    else
                    {
                        nonSat.Set <byte>(j, i, 0);
                    }
                }
            }

            var disk = Cv2.GetStructuringElement(
                MorphShapes.Rect,
                new OpenCvSharp.Size(5, 5),
                new OpenCvSharp.Point(2, 2));

            Mat m = new Mat();

            Cv2.Erode(nonSat, m, disk);
            Cv2.ImWrite(@"C:\temp\maskImage.png", nonSat);

            Mat dst = new Mat();

            src.CopyTo(dst, m);
            mask = BitmapConverter.ToBitmap(dst);
        }
        private Mat morphOps(Mat thresh, int x)
        {
            //create structuring element that will be used to "dilate"
            Mat erodeElement  = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(1, 1));
            Mat dilateElement = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(x, x));

            Cv2.Erode(thresh, thresh, erodeElement);
            Cv2.Dilate(thresh, thresh, dilateElement);
            Cv2.Dilate(thresh, thresh, dilateElement);
            Cv2.Erode(thresh, thresh, dilateElement);
            Cv2.Erode(thresh, thresh, dilateElement);

            return(thresh);
        }
        private static Point[][] GetContoursForParagraph(Mat imageToProcesing)
        {
            Point[][]        wordsContours;
            HierarchyIndex[] hierarchyIndexes;
            var kernelH = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(1, 1));

            Cv2.Erode(imageToProcesing, imageToProcesing, kernelH, null, 4);
            Cv2.Dilate(imageToProcesing, imageToProcesing, kernelH, null, 4);
            FindContours(imageToProcesing, out wordsContours, out hierarchyIndexes);
            Mat newOutput = new Mat();

            newOutput = CreateMaskParagraph(imageToProcesing);
            Point[][] contoursMask; //vector<vector<Point>> contours;
            FindContours(newOutput, out contoursMask, out hierarchyIndexes);
            return(contoursMask);
        }
        private Mat histMasking(Mat cameraMat)
        {
            Mat hsvMat = new Mat();
            Mat dstMat = new Mat();

            Cv2.CvtColor(cameraMat, hsvMat, ColorConversionCodes.BGR2HSV);
            Cv2.CalcBackProject(new[] { hsvMat }, new[] { 0, 1 }, handHist, dstMat, new[] { new Rangef(0, 180), new Rangef(0, 255) });

            if (filter2D)
            {
                Mat filter2DMat = Cv2.GetStructuringElement(filter2DShape, (new Size(filter2DSize.x, filter2DSize.y)));
                Cv2.Filter2D(dstMat, dstMat, -1, filter2DMat);
            }

            if (thresholdFilter)
            {
                Cv2.Threshold(dstMat, dstMat, thresholdLow, thresholdHigh, ThresholdTypes.Binary);
            }

            if (morphologyTransformation)
            {
                Mat morphologyTransformationMat =
                    Cv2.GetStructuringElement(morphologyTransformationShape, (new Size(morphologyTransformationSize.x, morphologyTransformationSize.y)));
                Cv2.MorphologyEx(dstMat, dstMat, morphologyTransformationType, morphologyTransformationMat, null, morphologyTransformationIterations);
            }

            if (dilatateFilter)
            {
                Mat dilatateShapeMat = Cv2.GetStructuringElement(this.dilatateShape, (new Size(dilatateSize.x, dilatateSize.y)));
                Cv2.Dilate(dstMat, dstMat, dilatateShapeMat, null, dilatateIterations);
            }

            if (erodeFilter)
            {
                Mat erodeShapeMat = Cv2.GetStructuringElement(this.erodeShape, (new Size(erodeSize.x, erodeSize.y)));
                Cv2.Erode(dstMat, dstMat, erodeShapeMat, null, erodeIterations);
            }

            handMask = dstMat;

            if (bitwiseFilter)
            {
                // Cv2.BitwiseAnd(cameraMat, dstMat, dstMat); //TODO: we need it to mask our hand, in this form it return exception
            }

            return(dstMat);
        }
Exemple #25
0
        private void bn_Erode_Click(object sender, RoutedEventArgs e)
        {
            if (listImage.Count > 0)
            {
                string strTitle = listImage[_nSelWin].Title;
                Mat    matSrc   = listImage[_nSelWin].fn_GetImage();
                Mat    matDst   = new Mat();
                int    width    = matSrc.Cols;
                int    height   = matSrc.Rows;
                timeStart = DateTime.Now;

                Cv2.Erode(matSrc, matDst, new Mat());

                fn_WriteLog($"[Erode] {strTitle} ({(DateTime.Now - timeStart).TotalMilliseconds} ms)");
                fn_NewImage(matDst, $"{strTitle}_Erode");
            }
        }
Exemple #26
0
        public static void cv_15()  // 形态学系列之 腐蚀/膨胀
        {
            //膨胀原理:跟卷积操作相似,假设有图像A和结构元素B,结构元素B在A上面移动,其中B定义其中心点为锚点,计算B覆盖下A的最大像素值用来替换锚点的像素,其中结构体B可以是任意形状。
            //腐蚀原理:腐蚀与膨胀的操作的过程一样,不同的是以最小值替换锚点重叠下的像素值。
            //Cv2.GetStructuringElement(): 获取结构元素
            //Cv2.Dilate(): 膨胀,通过使用特定的结构元素来扩展图像。
            //Cv2.Erode(): 腐蚀,通过使用特定的结构元素来侵蚀图像。

            Mat src = new Mat(@"G:\\pics\7.jpg", ImreadModes.Color);

            Cv2.ImShow("src", src);

            int size = 5; //要为奇数
            Mat structuringElement = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(size, size), new OpenCvSharp.Point(-1, -1));

            /* 参数     1,MorphShapes shape   结果元素的形状
             *         2,Size ksize  结构元素的大小
             *         3,Point anchor    结构元素的锚点(中心点)
             */

            Mat DilateImg = new Mat();

            Cv2.Dilate(src, DilateImg, structuringElement, new OpenCvSharp.Point(-1, -1), 1);  //膨胀

            /*   参数:1,   源图像
             *       2,   输出图像
             *       3,   结构元素,奇数
             *       4,   锚点位置,默认是null
             *       5,   应用膨胀的次数。[默认情况下这是1]
             */

            Mat ErodeImg = new Mat();

            Cv2.Erode(src, ErodeImg, structuringElement, new OpenCvSharp.Point(-1, -1), 1);    //腐蚀

            /*   参数:1,源图像
             *        2,输出图像
             *        3,结构元素,奇数
             *        4, 锚点位置,默认是null
             *        5,应用膨胀的次数。[默认情况下这是1]
             */

            Cv2.ImShow("ErodeImg", ErodeImg);
            Cv2.ImShow("DilateImg", DilateImg);
            Cv2.WaitKey();
        }
        private IEnumerable <Rect> DetectMotion(Mat frame)
        {
            Mat fgmask = new Mat();

            _segmentor.Apply(frame, fgmask);
            if (fgmask.Empty())
            {
                yield break;
            }

            Cv2.Threshold(fgmask, fgmask, 25, 255, ThresholdTypes.Binary);
            int noiseSize = 9;
            Mat kernel    = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(noiseSize, noiseSize));

            Cv2.Erode(fgmask, fgmask, kernel);
            kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(noiseSize, noiseSize));
            Cv2.Dilate(fgmask, fgmask, kernel, new Point(-1, -1), 3);
            Cv2.FindContours(fgmask, out Point[][] contours, out HierarchyIndex[] hierarchies, RetrievalModes.Tree, ContourApproximationModes.ApproxSimple);
Exemple #28
0
        public void MotionDetector(SoftwareBitmap input, SoftwareBitmap output, Algorithm algorithm)
        {
            if (algorithm.AlgorithmName == "MotionDetector")
            {
                using Mat mInput     = SoftwareBitmap2Mat(input);
                using Mat mOutput    = new Mat(mInput.Rows, mInput.Cols, MatType.CV_8UC4);
                using Mat fgMaskMOG2 = new Mat(mInput.Rows, mInput.Cols, MatType.CV_8UC4);
                using Mat temp       = new Mat(mInput.Rows, mInput.Cols, MatType.CV_8UC4);

                this.mog2.Apply(mInput, fgMaskMOG2, (double)algorithm.AlgorithmProperties[0].CurrentValue);
                Cv2.CvtColor(fgMaskMOG2, temp, ColorConversionCodes.GRAY2BGRA);

                using Mat element = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(3, 3));
                Cv2.Erode(temp, temp, element);
                temp.CopyTo(mOutput);
                Mat2SoftwareBitmap(mOutput, output);
            }
        }
        /// <summary>
        /// 提前图片里的表格
        /// </summary>
        /// <param name="mat"></param>
        /// <returns></returns>
        public Mat To_extract_form(Mat mat)
        {
            using (Mat horizontal横线图 = mat.Clone())
                using (Mat vertical竖线图 = mat.Clone())
                    //为了获取横向的表格线,设置腐蚀和膨胀的操作区域为一个比较大的横向直条
                    //横核,函数
                    using (Mat horizontalStructure = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(horizontal横线图.Cols / 20, 1)))
                        //竖核,函数
                        using (Mat verticalStructure = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(1, vertical竖线图.Rows / 30)))
                        {
                            //横腐蚀
                            Cv2.Erode(~horizontal横线图, horizontal横线图, horizontalStructure, new OpenCvSharp.Point(-1, -1));

                            //横膨胀
                            Cv2.Dilate(horizontal横线图, horizontal横线图, horizontalStructure, new OpenCvSharp.Point(-1, -1));

                            //竖腐蚀
                            Cv2.Erode(~vertical竖线图, vertical竖线图, verticalStructure, new OpenCvSharp.Point(-1, -1));

                            //竖膨胀
                            Cv2.Dilate(vertical竖线图, vertical竖线图, verticalStructure, new OpenCvSharp.Point(-1, -1));


                            Mat Image纯表格 = horizontal横线图 + vertical竖线图;
                            Cv2.CvtColor(~Image纯表格, Image纯表格, ColorConversionCodes.BGR2GRAY);

                            //var window先腐蚀再膨胀纵向 = new Window("先腐蚀再膨胀纵向");
                            //window先腐蚀再膨胀纵向.Image = vertical竖线图;

                            //using (new Window("horizontal横线图", WindowMode.AutoSize, horizontal横线图))
                            //using (new Window("vertical竖线图", WindowMode.AutoSize, vertical竖线图))
                            //using (new Window("Image纯表格", WindowMode.AutoSize, Image纯表格))
                            //{
                            //    Window.WaitKey(0);

                            //    //Image阈值化.SaveImage(@"D:\new1\langyp.fontyp.exp0.tif");
                            //}
                            //var window横纵向 = new Window("横纵向");
                            //window横纵向.Image = Image纯表格;
                            //Image纯表格.SaveImage(@"D:\new1\纯表格.tif");
                            //Cv2.ImWrite("横纵向.jpg", Image纯表格);
                            return(Image纯表格);
                        }
        }
        //图像分割
        private void ucBtnExt_A1_BtnClick(object sender, EventArgs e)
        {
            Scalar apple_hsv_min_1 = new Scalar(apple_h_min_1, apple_s_min, apple_v_min);
            Scalar apple_hsv_max_1 = new Scalar(apple_h_max_1, apple_s_max, apple_v_max);
            Scalar apple_hsv_min_2 = new Scalar(apple_h_min_2, apple_s_min, apple_v_min);
            Scalar apple_hsv_max_2 = new Scalar(apple_h_max_2, apple_s_max, apple_v_max);

            Scalar pear_hsv_min = new Scalar(pear_h_min, pear_s_min, pear_v_min);
            Scalar pear_hsv_max = new Scalar(pear_h_max, pear_s_max, pear_v_max);

            Cv2.CvtColor(srcImg, hsvImg, ColorConversionCodes.BGR2HSV);
            this.pictureBoxIpl_img.ImageIpl = hsvImg;
            //输出Log
            newLog = "[msg] 显示HSV图像";
            //等待1s
            Cv2.WaitKey(1000);
            //计算苹果掩膜
            Cv2.InRange(hsvImg, apple_hsv_min_1, apple_hsv_max_1, apple_1);
            Cv2.InRange(hsvImg, apple_hsv_min_2, apple_hsv_max_2, apple_2);
            //合并掩膜
            Cv2.Add(apple_1, apple_2, apple_mask);
            //膨胀腐蚀
            Mat apple_element = Cv2.GetStructuringElement(MorphShapes.Rect,
                                                          new OpenCvSharp.Size(3, 3), new OpenCvSharp.Point(-1, -1));

            Cv2.Dilate(apple_mask, apple_mask, apple_element, new OpenCvSharp.Point(-1, -1), 1);
            Cv2.Erode(apple_mask, apple_mask, apple_element, new OpenCvSharp.Point(-1, -1), 1);
            //计算梨子掩膜
            Cv2.InRange(hsvImg, pear_hsv_min, pear_hsv_max, pear_mask);
            //膨胀腐蚀   注意核大小取值
            Mat pear_element_erode = Cv2.GetStructuringElement(MorphShapes.Rect,
                                                               new OpenCvSharp.Size(7, 7), new OpenCvSharp.Point(-1, -1));
            Mat pear_element_dilate = Cv2.GetStructuringElement(MorphShapes.Rect,
                                                                new OpenCvSharp.Size(7, 7), new OpenCvSharp.Point(-1, -1));

            Cv2.Erode(pear_mask, pear_mask, pear_element_erode, new OpenCvSharp.Point(-1, -1), 1);
            Cv2.Dilate(pear_mask, pear_mask, pear_element_dilate, new OpenCvSharp.Point(-1, -1), 1);
            Cv2.Add(apple_mask, pear_mask, fruit_mask);
            //显示图像分割效果
            this.pictureBoxIpl_img.ImageIpl = fruit_mask;
            //输出日志
            newLog = "[msg] 图像分割完毕";
        }