c#opencv绘制矩形的方法。
时间: 2024-12-08 07:13:12 浏览: 12
在C#中使用OpenCVSharp绘制矩形的方法通常涉及以下几个步骤[^2]:
1. **安装依赖**:
安装OpenCVSharp库,可通过NuGet包管理器搜索并添加`OpenCvSharp4.Windows`。
2. **初始化**:
```csharp
using Emgu.CV;
using Emgu.CV.Structure;
```
3. **设置窗体事件**:
```csharp
pictureBox.MouseDown += pictureBox_MouseDown;
pictureBox.MouseMove += pictureBox_MouseMove;
pictureBox.MouseUp += pictureBox_MouseUp;
```
4. **定义绘制函数**:
```csharp
private void pictureBox_MouseDown(object sender, MouseEventArgs e)
{
// 初始化矩形的起始点
startPoint = new Point(e.X, e.Y);
}
private void pictureBox_MouseMove(object sender, MouseEventArgs e)
{
// 当鼠标移动时更新矩形终点
endPoint = new Point(e.X, e.Y);
if (startPoint != null)
pictureBox.Image = DrawRectangle(pictureBox.Image, startPoint, endPoint);
}
private Mat DrawRectangle(Mat src, Point startPoint, Point endPoint)
{
// 使用蓝色绘制矩形
var rectangle = new Rectangle(startPoint, endPoint - startPoint);
CvInvoke.Rectangle(src, rectangle, Color.Blue, 2);
return src;
}
private void pictureBox_MouseUp(object sender, MouseEventArgs e)
{
// 如果按下鼠标按钮释放,则停止绘制
endPoint = null;
}
```
在这个示例中,当用户按下鼠标左键并在PictureBox上拖动时,会开始绘制矩形;当鼠标抬起时,绘制结束。`DrawRectangle`函数负责在给定的源图像上应用绘制的矩形。
阅读全文