一、轮廓的周长
计算轮廓的周长的函数是:
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, 如下所示:
- 一共是7个轮廓,周长最大的是1687个像素(编号是1),面积最小的是37个像素(编号7)。
- 利用DrawContours()函数,将每个轮廓都画成绿色。
- 利用BoundingRectangle()函数,求出每个轮廓的最小外接矩形,并在后面用白色线条画出来。
- 在将轮廓逐个添加到 dict 字典时,仍然对轮廓的大小进行了筛选,可以有效的减少干扰。
原创不易,请勿抄袭。共同进步,相互学习。