OpenCV在轮廓周围拟合最小矩形或多边形(C#)

本文介绍了一种使用OpenCV库从图像中提取几何特征的方法。通过模糊处理、二值化、边缘检测等步骤预处理图像,然后提取并绘制轮廓,最后利用ApproxPolyDP、BoundingRect和MinAreaRect等API提取并绘制图像的几何特征。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

API:

  1. ApproxPolyDP:拟合最小多边形
public static Point[] ApproxPolyDP(IEnumerable<Point> curve, double epsilon, bool closed);

参数:
curve:轮廓点集合;
epsilon:主要表示输出的精度,就是另个轮廓点之间最大距离数;
closed:表示输出的多边形是否封闭,true:封闭

  1. BoundingRect/MinAreaRect:拟合最小矩形(不旋转或旋转)
//拟合最小矩形,不旋转
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

.NET 环境的OpenCv库

### 使用 OpenCvSharp 实现矩形识别 在 OpenCvSharp 中,可以通过轮廓检测来实现矩形的识别。具体来说,可以使用 `Cv2.FindContours` 来找到图像中的轮廓,并通过计算这些轮廓的几何特性(如面积、周长等),筛选出近似为矩形的区域。 以下是具体的实现方法和示例代码: #### 方法概述 1. **读取图像**:加载待处理的图像。 2. **灰度化与二值化**:将彩色图像转换为灰度图,并对其进行阈值处理以便更好地提取轮廓。 3. **寻找轮廓**:使用 `Cv2.FindContours` 找到所有的轮廓。 4. **过滤矩形**:对于每一个轮廓,判断其是否接近矩形形状。这通常通过检查轮廓的凸包拟合最小包围框来进行。 5. **绘制结果**:将最终识别出来的矩形绘制到原图上。 --- #### 示例代码 以下是一个完整的 C# 示例代码,展示如何使用 OpenCvSharp 进行矩形识别: ```csharp using OpenCvSharp; using System; class RectangleDetectionExample { static void Main(string[] args) { // 1. 加载输入图片 string imagePath = "input_image.png"; // 替换为实际路径 Mat srcImage = Cv2.ImRead(imagePath); if (srcImage.Empty()) { Console.WriteLine("无法加载图像!"); return; } // 2. 图像预处理:转灰度 -> 阈值化 Mat grayImage = new Mat(); Cv2.CvtColor(srcImage, grayImage, ColorConversionCodes.BGR2GRAY); Mat binaryImage = new Mat(); Cv2.Threshold(grayImage, binaryImage, 127, 255, ThresholdTypes.Binary); // 3. 寻找轮廓 Point[][] contours; HierarchyIndex[] hierarchy; Cv2.FindContours(binaryImage, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple); // 4. 筛选矩形轮廓 foreach (var contour in contours) { double perimeter = Cv2.ArcLength(contour, true); // 计算轮廓周长 var approxCurve = Cv2.ApproxPolyDP(contour, 0.02 * perimeter, true); // 多边形逼近 if (approxCurve.Length == 4 && Cv2.IsContourConvex(approxCurve)) // 判断是否为四边形且凸 { Rect boundingRect = Cv2.BoundingRect(contour); // 获取外接矩形 Cv2.Rectangle(srcImage, boundingRect, Scalar.Red, 2); // 绘制矩形边界 } } // 5. 显示结果 Cv2.ImShow("Original Image with Detected Rectangles", srcImage); Cv2.WaitKey(0); } } ``` --- #### 关键点解析 1. **图像预处理** - 将图像转化为灰度图有助于减少颜色干扰,提高后续操作效率[^1]。 - 使用阈值化技术创建黑白二值图,便于清晰地区分目标物体与背景。 2. **轮廓查找 (`FindContours`)** - 参数 `RetrievalModes.External` 表示仅检索最外部的轮廓。 - 参数 `ContourApproximationModes.ApproxSimple` 可简化复杂曲线为更少顶点的形式[^1]。 3. **矩形判定逻辑** - 借助 `ArcLength` 和 `ApproxPolyDP` 对轮廓进行多边形逼近,从而判断其是否有四个角点。 - 如果满足条件,则进一步验证该轮廓是否具有凸性属性。 4. **绘制矩形** - 使用 `BoundingRect` 得到每个符合条件的轮廓对应的最小外包矩形,并将其画在原始图像之上[^4]。 --- ### 注意事项 - 输入图像应尽量干净无噪声;如果存在较多杂乱像素,可能会影响轮廓提取效果。 - 不同应用场景下需调整阈值参数以适应特定需求。 - 若目标矩形倾斜角度较大,可考虑采用旋转后的最小包围盒替代标准直立矩形。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值