API:
public static Point[] ApproxPolyDP(IEnumerable<Point> curve, double epsilon, bool closed);
参数:
curve:轮廓点集合;
epsilon:主要表示输出的精度,就是另个轮廓点之间最大距离数;
closed:表示输出的多边形是否封闭,true:封闭
//拟合最小矩形,不旋转
public static Rect BoundingRect(InputArray curve);
//拟合最小矩形旋转
public static RotatedRect MinAreaRect(IEnumerable<Point> points);
图像处理流程:
一般视图像质量,对图像可先进行模糊处理(均值模糊),二值化后,提取图像边缘,再提取图像轮廓(一般只提取外轮廓),最后调用相关API提取图像几何特征
演示:
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);
补充说明:
本案例在.NET使用的OpenCV库为OpenCvSharp4