美文网首页
C#:轮廓面积周长

C#:轮廓面积周长

作者: 大龙10 | 来源:发表于2023-12-09 14:46 被阅读0次

    一、程序

            private void uiButton11_Click(object sender, EventArgs e)
            {
                Mat src = src_img.Clone();
                // 如果背景色是白色,则需要进行此操作。即黑色变白色,白色变黑色。
                // 按位运算
                // opencv非运算不是1变0,0变1。而是 !x = 255 - x
                Cv2.BitwiseNot(src, src);
                // 高斯模糊
                Mat blur = new Mat();
                Cv2.GaussianBlur(src, blur, new OpenCvSharp.Size(15, 15), 0, 0);
                //Cv2.ImShow("滤波", blur);
                // 二值化
                Mat grayImg = new Mat();
                Mat binary = new Mat();
                Cv2.CvtColor(blur, grayImg, ColorConversionCodes.BGR2GRAY);
                Cv2.Threshold(grayImg, binary, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Triangle);
                //Cv2.ImShow("二值化", binary);
                // 形态学操作
                Mat morphImage = new Mat();
                Mat kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(3, 3), new OpenCvSharp.Point(-1, -1));
                Cv2.MorphologyEx(binary, morphImage, MorphTypes.Close, kernel, new OpenCvSharp.Point(-1, -1), 2);
                //Cv2.ImShow("形态学操作", morphImage);
                OpenCvSharp.Point[][] contours;
                HierarchyIndex[] hierarchies;
                // 寻找轮廓
                Cv2.FindContours(morphImage, out contours, out hierarchies, RetrievalModes.External, ContourApproximationModes.ApproxSimple, new OpenCvSharp.Point());
    
                Mat dest = Mat.Zeros(src.Size(), MatType.CV_8UC3);
                for (int i = 0; i < contours.Length; i++)
                {
                    double area = Cv2.ContourArea(contours[i]);
                    double len = Cv2.ArcLength(contours[i], true);
                    Cv2.DrawContours(dest, contours, (int)i, new Scalar(0, 0, 255), 1, LineTypes.Link8, hierarchies);
                    Cv2.PutText(dest, "area:" + area.ToString(""), new OpenCvSharp.Point(20, 50), HersheyFonts.HersheySimplex, 1, new Scalar(0, 255, 255), 1, LineTypes.Link4);
                    Cv2.PutText(dest, "length:" + len.ToString("0.00"), new OpenCvSharp.Point(20, 150), HersheyFonts.HersheySimplex, 1, new Scalar(0, 255, 255), 1, LineTypes.Link4);
                }        
                pictureBox1.Image = dest.ToBitmap();
            }
        }
    
    

    二、结果

    运行结果

    三、资料

    蒋智昊的博客
    http://chanpinxue.cn/archives/5181.html
    

    相关文章

      网友评论

          本文标题:C#:轮廓面积周长

          本文链接:https://www.haomeiwen.com/subject/nibdgdtx.html