C#使用OpenCvSharp4库中5个基础函数-灰度化、高斯模糊、Canny边缘检测、膨胀、腐蚀
使用OpenCV可以对彩色原始图像进行基本的处理,涉及到5个常用的处理:
-
- 灰度化
-
- 模糊处理
-
- Canny边缘检测
-
- 膨胀
-
- 腐蚀
1、测试图像lena.jpg
本例中我们采用数字图像处理中经常用到的一副标准图像lena.png
作为测试图像,如下图所示:
具体资源下载地址为:lena图像下载地址
2、使用Visual Studio 2022创建一个基于C# .Net控制台的程序
首先我们新建一个基于C# .Net控制台的程序,项目名为OpenCVExample
,然后把lena.jpg
拷贝到E:\SoftDevelop\CPlus\VS2022Projects\CSharpExamples\OpenCVExample\OpenCVExample\bin\Debug\images
对应目录下,如下图所示:
安装OpenCvSharp4和OpenCvSharp4.runtime.win两个NuGet包,或者直接安装OpenCvSharp4.Windows包
安装OpenCvSharp4和OpenCvSharp4.runtime.win两个NuGet包之后,packages.config
配置文件如下:
<?xml version="1.0" encoding="utf-8"?>
<packages><package id="OpenCvSharp4" version="4.9.0.20240103" targetFramework="net48" /><package id="OpenCvSharp4.runtime.win" version="4.9.0.20240103" targetFramework="net48" /><package id="System.Buffers" version="4.5.1" targetFramework="net48" /><package id="System.Memory" version="4.5.5" targetFramework="net48" /><package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net48" /><package id="System.Runtime.CompilerServices.Unsafe" version="6.0.0" targetFramework="net48" /><package id="System.ValueTuple" version="4.5.0" targetFramework="net48" />
</packages>
C#示例代码
对应的C#代码如下:
using OpenCvSharp;namespace OpenCVExample
{public class Program{/// <summary>/// OpenCV的5个基础函数-灰度化、高斯模糊、Canny边缘检测、膨胀、腐蚀/// </summary>public static void FiveBasicFunction(){Mat img = Cv2.ImRead("images/lena.jpg"); // 读取图像Mat grayImg = new Mat();Cv2.CvtColor(img, grayImg, ColorConversionCodes.BGR2GRAY);Mat blurImg = new Mat();Cv2.GaussianBlur(grayImg, blurImg, new Size(7, 7), 0);Mat cannyImg = new Mat();Cv2.Canny(blurImg, cannyImg, 150, 200);Mat dialationImg = new Mat();Mat kernel = new Mat(5, 5, MatType.CV_8UC1);Cv2.Dilate(blurImg, dialationImg, kernel);Mat erodeImg = new Mat();Cv2.Erode(dialationImg, erodeImg, kernel);Cv2.ImShow("Image", img); // 显示原图像Cv2.ImShow("Gray Image", grayImg); // 显示灰度图像Cv2.ImShow("Blur Image", blurImg); // 显示高斯模糊图像Cv2.ImShow("Canny Image", cannyImg); // 显示Canny边缘检测图像Cv2.ImShow("Dialation Image", dialationImg); // 膨胀图Cv2.ImShow("Erode Image", erodeImg); // 腐蚀图Cv2.WaitKey(0);Cv2.DestroyAllWindows();}static void Main(string[] args){FiveBasicFunction();//Console.ReadKey();}}
}
程序运行结果
在VS2022中运行上述代码,结果如下图所示:
参考资料
- https://github.com/shimat/opencvsharp
- LEARN OPENCV C++ in 4 HOURS | Including 3x Projects | Computer Vision
- Learn-OpenCV-cpp-in-4-Hours
- LEARN OPENCV in 3 HOURS with Python | Including 3xProjects | Computer Vision
- Learn-OpenCV-in-3-hours