OpenCV fitting minimum rectangle or polygon around contour (C#)

API:

  1. ApproxPolyDP: fitting minimum polygon
public static Point[] ApproxPolyDP(IEnumerable<Point> curve, double epsilon, bool closed);

Parameters:
curve: a collection of contour points;
epsilon: mainly indicates the accuracy of the output, which is the maximum distance between another contour point;
closed: indicates whether the output polygon is closed, true: closed

  1. BoundingRect/MinAreaRect: Fit the minimum rectangle (without rotation or rotation)
//拟合最小矩形,不旋转
public static Rect BoundingRect(InputArray curve);

//拟合最小矩形旋转
public static RotatedRect MinAreaRect(IEnumerable<Point> points);

Image processing process:
Generally, depending on the image quality, the image can be blurred (mean blur) first. After binarization, the edges of the image are extracted, and then the image contour is extracted (generally only the outer contour is extracted). Finally, the relevant API is called to extract the geometric features of the image.

Demo:


picFile = fileDialog.FileName;
inputMat = Cv2.ImRead(picFile, ImreadModes.Grayscale);
displayMat = Cv2.ImRead(picFile, ImreadModes.AnyColor);
outMat = new Mat(new Size(inputMat.Cols, inputMat.Rows), inputMat.Type());

//二值化
Cv2.Threshold(inputMat, inputMat,106 ,255, ThresholdTypes.Binary);

//提取边缘
Cv2.Canny(inputMat, outMat, 30, 90);


//仅查找外轮廓
Cv2.FindContours(outMat, out OpenCvSharp.Point[][] contours, out HierarchyIndex[] outputArray, RetrievalModes.External, ContourApproximationModes.ApproxNone);


//绘制轮廓
Scalar color = new Scalar(255, 0, 0);
for (int i = 0; i < contours.Length; i++)
{
    
    
    Mat rMat = new Mat();


    //拟合最小多边形
    contours[i] = Cv2.ApproxPolyDP(contours[i], 3, true);

    Rect rect = new Rect();
    RotatedRect rotatedRect = new RotatedRect();
    //拟合轮廓周围最小矩形--不旋转
    rect = Cv2.BoundingRect(contours[i]);

    //拟合轮廓周围最小矩形--旋转
    rotatedRect = Cv2.MinAreaRect(contours[i]);

    //获取旋转矩形四个顶点
    var rectPoints = rotatedRect.Points();

    //绘制矩形
    Cv2.Line(displayMat, ((Point)rectPoints[0]), ((Point)rectPoints[1]), color, 4);
    Cv2.Line(displayMat, ((Point)rectPoints[1]), ((Point)rectPoints[2]), color, 4);
    Cv2.Line(displayMat, ((Point)rectPoints[2]), ((Point)rectPoints[3]), color, 4);
    Cv2.Line(displayMat, ((Point)rectPoints[3]), ((Point)rectPoints[0]), color, 4);



}

picBox_Display.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(inputMat);
picBox_After.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(displayMat);


The original image
Insert image description here

Extraction effect
Insert image description here

Additional notes:
The OpenCV library used in .NET in this case is OpenCvSharp4

OpenCv library for .NET environment

Guess you like

Origin blog.csdn.net/weixin_40671962/article/details/127643796