C# opencv
时间: 2023-12-31 21:04:58 浏览: 155
c#环境下得opencv
C#使用OpenCV的一些代码如下:
1. 需要加头文件
```csharp
using OpenCvSharp;
```
2. 读取图片
```csharp
Mat img1 = new Mat("F:\\all_truck\\truck_3.jpg", ImreadModes.Color);
Cv2.ImShow("win1", img1);
Cv2.WaitKey(0);
```
3. 定义一个没有初始化的图片作为复制
```csharp
Mat pBkImage_copy = new Mat();
pBkImage.CopyTo(pBkImage_copy);
```
4. 灰度化
```csharp
Cv2.CvtColor(img1, img1, ColorConversionCodes.BGR2GRAY);
```
5. 高斯模糊和size数据格式的定义
```csharp
Size ksize = new Size(5, 5);
Cv2.GaussianBlur(img1, img1, ksize, 0);
```
6. 二值化
```csharp
Cv2.Threshold(img1, img1, 128, 255, ThresholdTypes.Binary);
```
7. 开闭运算
```csharp
Mat kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(3, 3));
Cv2.MorphologyEx(img1, img1, MorphTypes.Open, kernel);
```
8. FindContours查找轮廓和contours参数的定义和操作
```csharp
Point[][] contours;
HierarchyIndex[] hierarchy;
Cv2.FindContours(img1, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
```
9. Rect和Size格式的定义
```csharp
Rect rect = Cv2.BoundingRect(contours[0]);
Size size = new Size(rect.Width, rect.Height);
```
10. resize函数在图片上画矩形框在图片上画直线
```csharp
Cv2.Rectangle(img1, rect, Scalar.Red, 2);
Cv2.Line(img1, new Point(0, 0), new Point(img1.Width, img1.Height), Scalar.Blue, 2);
```
阅读全文