(七)海康工业相机与OpenCV,C#联合编程

发布时间:2026/7/5 2:08:10
(七)海康工业相机与OpenCV,C#联合编程 OpenCVOpen Source Computer Vision Library是一个开源的计算机视觉和机器学习软件库。它由英特尔于1999年发起研发现已发展为全球最流行的开源计算机视觉库。海量算法包含 2500 多个优化的计算机视觉与机器学习算法涵盖经典算法和前沿的深度学习模型。开源免费采用 Apache 2 许可企业和个人均可自由使用、修改和分发。跨平台支持支持 Windows、Linux、macOS、Android 等多个操作系统。多语言接口原生使用 C 编写同时提供 Python、Java、MATLAB 等语言的接口。OpenCvSharp 是 OpenCV 的另一个 .NET 原生封装库同样通过 P/Invoke 实现 C 与 C# 的交互。一、下载并安装OpenCVSahrp1、创建工程1文件-新建-项目2选择所需要采用的框架版本以4.8为例3将项目的编译配置切换为“Release”并将目标平台设定为“x64”运行成功显示新窗口4在窗体中添加显示控件工具箱-PictureBox属性在右下角名称大小颜色样式等从文件中加载一张图片并显示到picturebox点击按钮显示图片private void button1_Click(object sender, EventArgs e) { LoadImage(./139.jpg); }// 从文件中读取图像在名为 pictureBox1 的 PictureBox 控件显示 private void LoadImage(string filePath) { try { // 从文件创建 Image 对象 Image img Image.FromFile(filePath); // 将图像赋值给 PictureBox pictureBox1.Image img; // 可选调整 PictureBox 的显示模式 pictureBox1.SizeMode PictureBoxSizeMode.Zoom; // 按比例缩放适应控件 } catch (Exception ex) { MessageBox.Show($加载图片失败{ex.Message}); } }成功显示图片2、创建工程1引用-管理NuGet程序包2浏览-OpenCv,安装OpenCvSharrp4和OpenCvSharp4runtimre.win在有时候可能会用到OpenCvSharrp4.Extensions二、OpenCVSahrp与C#联合编程private void button1_Click(object sender, EventArgs e) { // action(); string imagePath ./139.jpg; string grayImagePath ./gray.jpg; Mat colorMat Cv2.ImRead(imagePath, ImreadModes.Color); if (colorMat.Empty()) { Console.WriteLine(无法加载图像请检查路径是否正确。); return; } // 创建用于存放灰度图的 Mat 对象 Mat grayMat new Mat(); // 将彩色图转换为灰度图 Cv2.CvtColor(colorMat, grayMat, ColorConversionCodes.BGR2GRAY); // 保存灰度图 Cv2.ImWrite(grayImagePath, grayMat); Console.WriteLine($灰度图已保存至 {grayImagePath}); Bitmap show BitmapConverter.ToBitmap(grayMat); pictureBox1.Image show; // 释放资源 colorMat.Dispose(); grayMat.Dispose(); }头文件using OpenCvSharp; using OpenCvSharp.Extensions;利用opencv 读取一张图片并转化为灰度图将灰度图写为文件将OpenCv Mat格式转化为BitMap并显示。三、海康相机读取 图片利用OpenCVSahrp处理并显示1将BitMap转化为OpenCv格式public static Mat BitmapToMat(Bitmap bitmap) { if (bitmap null) { //DebugLog(Bitmap 为 null); return null; } try { OpenCvSharp.Mat mat OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap);//用 return mat; } catch (Exception ex) { return null; } }2从海康相机中读取一张图片并转化为opencv格式并显示private void button1_Click(object sender, EventArgs e) { // LoadImage(./139.jpg); //枚举设备 int nRet DeviceEnumerator.EnumDevices(enumTLayerType, out deviceInfoList); if (nRet ! MvError.MV_OK) { //ShowErrorMsg(Enumerate devices fail!, nRet); return; } // ch:获取选择的设备信息 | en:Get selected device information IDeviceInfo deviceInfo deviceInfoList[0]; try { // ch:打开设备 | en:Open device device DeviceFactory.CreateDevice(deviceInfo); } catch (Exception ex) { MessageBox.Show(Create Device fail! ex.Message); return; } int result device.Open(); if (result ! MvError.MV_OK) { //ShowErrorMsg(Open Device fail!, result); return; } //ch: 判断是否为gige设备 | en: Determine whether it is a GigE device if (device is IGigEDevice) { //ch: 转换为gigE设备 | en: Convert to Gige device IGigEDevice gigEDevice device as IGigEDevice; // ch:探测网络最佳包大小(只对GigE相机有效) | en:Detection network optimal package size(It only works for the GigE camera) int optionPacketSize; result gigEDevice.GetOptimalPacketSize(out optionPacketSize); if (result ! MvError.MV_OK) { // ShowErrorMsg(Warning: Get Packet Size failed!, result); } else { result device.Parameters.SetIntValue(GevSCPSPacketSize, (long)optionPacketSize); if (result ! MvError.MV_OK) { //ShowErrorMsg(Warning: Set Packet Size failed!, result); } } } // ch:设置采集连续模式 | en:Set Continues Aquisition Mode device.Parameters.SetEnumValueByString(AcquisitionMode, Continuous); device.Parameters.SetEnumValueByString(TriggerMode, Off); // ch:开始采集 | en:Start Grabbing result device.StreamGrabber.StartGrabbing(); if (result ! MvError.MV_OK) { //ShowErrorMsg(Start Grabbing Fail!, result); return; } IFrameOut frameOut; nRet device.StreamGrabber.GetImageBuffer(1000, out frameOut); if (MvError.MV_OK nRet) { if (pictureBox1.Image ! null) { pictureBox1.Image.Dispose(); } Mat grayMat new Mat(); // 创建新图并显示 Bitmap show frameOut.Image.ToBitmap(); Mat colorMat BitmapToMat(show); Cv2.CvtColor(colorMat, grayMat, ColorConversionCodes.BGR2GRAY); pictureBox1.Image show; // 保存灰度图 string grayImagePath ./gray.jpg; Cv2.ImWrite(grayImagePath, grayMat); grayMat.Dispose(); } else { return; } // ch:停止采集 | en:Stop Grabbing result device.StreamGrabber.StopGrabbing(); if (result ! MvError.MV_OK) { // ShowErrorMsg(Stop Grabbing Fail!, result); return; } }3运行结果4WPF 中应用时可以转化为BitImage显示using OpenCvSharp.Extensions; public static BitmapImage ConvertToBitmapImage(System.Drawing.Bitmap bitmap) { using (MemoryStream memory new MemoryStream()) { // 将 System.Drawing.Bitmap 保存到内存流 bitmap.Save(memory, ImageFormat.Png); memory.Position 0; BitmapImage bitmapImage new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.CacheOption BitmapCacheOption.OnLoad; bitmapImage.StreamSource memory; bitmapImage.EndInit(); bitmapImage.Freeze(); // 跨线程使用时需要 Freeze return bitmapImage; } }注为了方便演示本节示例中全部代码在按钮的UI进程中执行的实际使用时UI线程和后台进程要分开处理。