【Emgu CV教程】10.3、轮廓之周长计算

本文介绍了如何使用OpenCV库中的函数计算图像中的轮廓周长,通过示例展示了如何获取白色物体轮廓,按周长排序并标注在图片上。
摘要由CSDN通过智能技术生成


一、轮廓的周长

计算轮廓的周长的函数是:

public static double ArcLength
(
	IInputArray curve, // 输入的轮廓
	bool isClosed // True代表是闭合的,False代表轮廓仅仅是一个曲线。
)

函数返回一个双精度小数。

三、简单应用

1.原始素材

原始素材srcMat如下图:
在这里插入图片描述

2.代码

计算图片中白色物体的所有轮廓的周长,并按照周长大小降序排列,并且在图片中要标注出轮廓的序号,代码如下:

Mat tempMat = srcMat.Clone();
Mat dstMat = srcMat.Clone();
Mat gray = new Mat();
int threshold = 40;

// 转成灰度图再二值化
CvInvoke.CvtColor(tempMat, gray, ColorConversion.Bgr2Gray);
CvInvoke.Threshold(gray, gray, threshold, 255, ThresholdType.Binary);
CvInvoke.Imshow("Gray and threshold", gray);

// 定义轮廓集合
VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();
VectorOfRect hierarchy = new VectorOfRect();

CvInvoke.FindContours(gray, contours, hierarchy, RetrType.List, ChainApproxMethod.ChainApproxNone);

Dictionary<int, double> dict = new Dictionary<int, double>();
if (contours.Size > 0)
{
    for (int i = 0; i < contours.Size; i++)
    {
        double girth = CvInvoke.ArcLength(contours[i], true);

        if (girth > 10 && girth < 3000000)
        {
            dict.Add(i, girth);
        }
    }
}

var item = dict.OrderByDescending(v => v.Value); // v.Value就代表周长,是降序排列
int index = 1;
foreach (var it in item)
{
    int key = it.Key;
    int area = Convert.ToInt32(it.Value);
    Rectangle rect = CvInvoke.BoundingRectangle(contours[key]);
    CvInvoke.Rectangle(dstMat, rect, new MCvScalar(255, 255, 255), 3);
    CvInvoke.PutText(dstMat, "Contour:" + index.ToString() + ",girth:" + area, new System.Drawing.Point(rect.X, rect.Y - 10), FontFace.HersheyComplex, 0.4, new Bgr(0, 255, 0).MCvScalar, 1, LineType.EightConnected, false);
    index++;
}

CvInvoke.PutText(dstMat, "Contours number:" + dict.Count(), new System.Drawing.Point(20, 20), FontFace.HersheyComplex, 0.5, new Bgr(0, 255, 0).MCvScalar, 1, LineType.EightConnected, false);
CvInvoke.DrawContours(dstMat, contours, -1, new MCvScalar(0, 255, 0), 2, LineType.EightConnected, hierarchy);
CvInvoke.Imshow("Final result image, " + dstMat.Size.ToString(), dstMat);

3.运行结果

轮廓检索模式要选择RetrType.List, 如下所示:
在这里插入图片描述

  1. 一共是7个轮廓,周长最大的是1687个像素(编号是1),面积最小的是37个像素(编号7)。
  2. 利用DrawContours()函数,将每个轮廓都画成绿色。
  3. 利用BoundingRectangle()函数,求出每个轮廓的最小外接矩形,并在后面用白色线条画出来。
  4. 在将轮廓逐个添加到 dict 字典时,仍然对轮廓的大小进行了筛选,可以有效的减少干扰。

原创不易,请勿抄袭。共同进步,相互学习。

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值