原图:
代码:
Mat src = Cv2.ImRead(FilePath.Image.Shapes);
Mat gray = new Mat();
Mat binary = new Mat();
Cv2.CvtColor(src, gray, ColorConversionCodes.BGR2GRAY);
Cv2.Threshold(gray, binary, 1, 255, ThresholdTypes.Binary);
//轮廓
ConnectedComponents cc = Cv2.ConnectedComponentsEx(binary);
foreach (var b in cc.Blobs.Skip(1))
{
Mat m = new Mat(binary, b.Rect);
Cv2.FindContours(m, out Point[][] contours, out _, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
//寻找最大内切圆
double dist;
double maxdist;
Point center = new Point();
foreach (var VPResult in contours)
{
maxdist = 0d;
for (int i = 0; i < m.Cols; i++)
{
for (int j = 0; j < m.Rows; j++)
{
//点到轮廓的最大距离
dist = Cv2.PointPolygonTest(VPResult, new Point(i, j), true);
if (dist > maxdist)
{
maxdist = dist;
center = new Point(i, j);
}
}
}
Cv2.Circle(src, b.Left + center.X, b.Top + center.Y, (int)maxdist, Scalar.Red);
}
}
结果: