opencvsharp4中利用cv2.drawcontours画矩形框
时间: 2024-12-02 14:14:32 浏览: 24
在OpenCVSharp 4中,你可以使用`cv2.drawContours()`函数来在原始图像上绘制轮廓的矩形框。这里有一个基本步骤:
1. **读取和预处理图像**:
```csharp
Mat im = Cv2.ImRead("test.jpg");
Mat imGray;
Cv2.CvtColor(im, imGray, ColorBgrToGray);
```
2. **二值化或应用边缘检测**:
```csharp
Mat thresholded;
int thresholdValue = 127;
Core.Threshold(imGray, thresholded, thresholdValue, 255, ThresholdType.Binary);
```
3. **查找轮廓**:
```csharp
VectorOfVectorOfPoint contours;
int hierarchyIndex = -1; // 使用默认的层次结构
Point offset = new Point(); // 用于调整轮廓的位置
Cv2.FindContours(thresholded, out contours, out hierarchyIndex, RetrievalModes.Tree, ContourApproximationModes.Simple);
```
4. **绘制轮廓矩形框**:
```csharp
using (Graphics g = Graphics.FromImage(im))
{
foreach (var contour in contours)
{
var approx = new Point[][] { contour.ToArray() };
Cv2.DrawContours(g, approx, -1, Scalar.Red, 2, LineTypes.Polyline, offset);
Cv2.Rectangle(g, new RectangleF(contour[0].X, contour[0].Y, contour[contour.Count - 1].X - contour[0].X, contour[contour.Count - 1].Y - contour[0].Y), Scalar.Yellow, 2); // 绘制矩形框
}
}
```
注意,`approx`变量用于近似多边形轮廓,而`Rectangle`函数则用来直接绘制矩形。
阅读全文