1:需求:提取图像中物体的轮廓以及计算该面积和周长
2:详细代码如下:
public static void GetOutline()
{
try
{
#region 加载图像
Mat src = Cv2.ImRead(@"srcImg.bmp");
if (src.Empty())
{
Console.WriteLine("could not load image...\n");
return;
}
Cv2.ImShow("input image", src);
//Cv2.WaitKey();
#endregion
#region 高斯模糊
Mat blurImg = new Mat();
Cv2.GaussianBlur(src, blurImg, new Size(15, 15), 0, 0);
Cv2.ImShow("blur", blurImg);
#endregion
#region 二值化
Mat grayImg = new Mat();
Mat binary = new Mat();
Cv2.CvtColor(blurImg, grayImg, ColorConversionCodes.BGR2GRAY);
//threshold(gray_src, binary, 0, 255, THRESH_BINARY | THRESH_TRIANGLE);
Cv2.Threshold(grayImg, binary, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Triangle);
Cv2.ImShow("binary", binary);
#endregion
#region 形态学操作
Mat morphImage = new Mat();
Mat kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(3, 3), new Point(-1, -1));
Cv2.MorphologyEx(binary, morphImage, MorphTypes.Close, kernel, new Point(-1, -1), 2);
Cv2.ImShow("morphImg", morphImage);
#endregion
Point[][] contours;
HierarchyIndex[] hierarchies;
Cv2.FindContours(morphImage, out contours, out hierarchies, RetrievalModes.External, ContourApproximationModes.ApproxSimple, new Point());
Mat connImg = Mat.Zeros(src.Size(), MatType.CV_8UC3);
for (int i = 0; i < contours.Length; i++)
{
Rect rect = Cv2.BoundingRect(contours[i]);
if (rect.Width < src.Cols / 10)
continue;
if (rect.Width > (src.Cols - 20))
continue;
double area = Cv2.ContourArea(contours[i]);
double len = Cv2.ArcLength(contours[i], true);
Cv2.DrawContours(connImg, contours, (int)i, new Scalar(0, 0, 255), 1, LineTypes.Link8, hierarchies);
Console.WriteLine("area of star could :{0}", area);
Console.WriteLine("length of star could : {0}", len);
//printf("area of star could : %f\n", area);
//printf("length of star could : %f\n", len);
}
Cv2.ImShow("connImage", connImg);
Cv2.WaitKey();
}
catch (Exception ex)
{
throw ex;
}
}
原图:
高斯模糊:
形态学操作:
绘制轮廓:
计算结果: