一、函数介绍
1.计算外接圆
计算一组点集的外接圆,函数是:
public static RotatedRect MinAreaRect
(
IInputArray points // 输入的轮廓
)
函数返回的是一个CircleF,它包含三个成员:
- Area,圆的面积。
- Center,圆心。
- Radius,半径。
2.计算外接椭圆
计算一组点集的外接椭圆,函数是:
public static RotatedRect FitEllipse
(
IInputArray points // 输入的轮廓
)
函数返回的是一个RotatedRect,也就是最小旋转外接矩形,它包含三个成员:
- Angle,顺时针方向的旋转角度。
- Center,旋转矩形的质心。
- Size,旋转矩形的宽度和高度。
注意了,这个返回的RotatedRect和用MinAreaRect()函数计算出来的结果是不一样的。
二、简单应用
1.原始素材
原始素材srcMat如下图:
2.代码
轮廓检索模式要选择RetrType.List,代码如下:
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.External, ChainApproxMethod.ChainApproxNone);
// 在一张黑色图中画出所有轮廓
Mat allContours = new Mat(new System.Drawing.Size(gray.Cols, gray.Rows), DepthType.Cv8U, 1);
allContours.SetTo(new MCvScalar(0, 0, 0));
CvInvoke.DrawContours(allContours, contours, -1, new MCvScalar(255, 255, 255), 1);
// 按照面积筛选,太小的轮廓不计算
Dictionary<int, double> dict = new Dictionary<int, double>();
if (contours.Size > 0)
{
for (int i = 0; i < contours.Size; i++)
{
double area = CvInvoke.ContourArea(contours[i]);
if (area > 50 && area < 3000000)
{
dict.Add(i, area);
}
}
}
// 开始画轮廓的最小外接圆和椭圆
var item = dict.OrderByDescending(v => v.Value); // v.Value就代表面积,是降序排列
foreach (var it in item)
{
int key = it.Key;
// 计算最小外接圆
CircleF circleF = CvInvoke.MinEnclosingCircle(contours[key]);
if (circleF.Radius > 1)
{
System.Drawing.Point center = new System.Drawing.Point((int)circleF.Center.X, (int)circleF.Center.Y);
CvInvoke.Circle(dstMat, center, (int)circleF.Radius, new MCvScalar(0, 0, 255), 2);
}
// 计算最小外接椭圆
RotatedRect rotatedRect = CvInvoke.FitEllipse(contours[key]);
if (rotatedRect.Size.Width > 10 && rotatedRect.Size.Width > 10)
{
System.Drawing.Point rcenter = new System.Drawing.Point((int)rotatedRect.Center.X, (int)rotatedRect.Center.Y);
// 两种画椭圆的办法
// CvInvoke.Ellipse(dstMat, rcenter, new System.Drawing.Size((int)(rotatedRect.Size.Width / 2), (int)(rotatedRect.Size.Height / 2)), rotatedRect.Angle, 0, 360, new MCvScalar(0, 255, 0), 2);
CvInvoke.Ellipse(dstMat, rotatedRect, new MCvScalar(0, 255, 0), 2, LineType.EightConnected);
}
}
CvInvoke.PutText(dstMat, "Contours number:" + item.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(255, 0, 0), 2, LineType.EightConnected, hierarchy);
CvInvoke.Imshow("All contours, " + allContours.Size.ToString(), allContours);
CvInvoke.Imshow("Final result image, " + dstMat.Size.ToString(), dstMat); // 显示最终结果
3.运行结果
如下所示:
- 红色的是最小外接圆。
- 绿色的是最小外接椭圆。
- 蓝色线条是其最外层轮廓。
原创不易,请勿抄袭。共同进步,相互学习。