C# OpenCV学习笔记五之图像轮廓

7 篇文章 1 订阅
7 篇文章 1 订阅

原始图

轮廓图

相关代码如下

            Image<Bgr, Byte> imageSource = new Image<Bgr, byte>((Bitmap)loadPictureBox.Image);
            Image<Gray, Byte> imageGrayscale = imageSource.Convert<Gray, Byte>();
            Image<Gray, Byte> dest = new Image<Gray, Byte>(imageGrayscale.Width, imageGrayscale.Height);

            CvInvoke.cvThreshold(imageGrayscale, dest, 30, 255, Emgu.CV.CvEnum.THRESH.CV_THRESH_BINARY);

            loadPictureBox.Image = dest.ToBitmap();

            IntPtr Dyncontour = new IntPtr();
            IntPtr Dynstorage = CvInvoke.cvCreateMemStorage(0);
            MCvContour con = new MCvContour();

            int n = CvInvoke.cvFindContours(dest, Dynstorage, ref Dyncontour, Marshal.SizeOf(con), Emgu.CV.CvEnum.RETR_TYPE.CV_RETR_TREE, Emgu.CV.CvEnum.CHAIN_APPROX_METHOD.CV_LINK_RUNS, new Point(0, 0));
            Seq<Point> DyncontourTemp = new Seq<Point>(Dyncontour, null);

            IntPtr dst = CvInvoke.cvCreateImage(CvInvoke.cvGetSize(dest), Emgu.CV.CvEnum.IPL_DEPTH.IPL_DEPTH_8U, 3);
            CvInvoke.cvZero(dst);

            int areaTotal = 0;//求轮廓面积
            double max = 0;//求轮廓最大矩阵对角线
            for (; DyncontourTemp != null && DyncontourTemp.Ptr.ToInt32() != 0; DyncontourTemp = DyncontourTemp.HNext)
            {
                Rectangle r = DyncontourTemp.BoundingRectangle;
                double tmp = Math.Sqrt(r.Height * r.Height + r.Width * r.Width);
                if (tmp > max)
                {
                    max = tmp;
                }
                
                areaTotal += r.Width * r.Height;

                //画出轮廓
                CvInvoke.cvRectangle(dst, new Point(r.X, r.Y), new Point(r.X + r.Width, r.Y + r.Height), new MCvScalar(255, 0, 0), 1, Emgu.CV.CvEnum.LINE_TYPE.EIGHT_CONNECTED, 0);
            }
            MessageBox.Show("Area Total :" + areaTotal.ToString());
            MessageBox.Show("Max Dist : " + max.ToString());

            CvInvoke.cvNamedWindow("dst");
            CvInvoke.cvShowImage("dst", dst);

            IntPtr2Image(dst).Save("001-1.jpg");//保存轮廓图形

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值