当前位置: 首页 > news >正文

c#调用c++生成的dll,c++端使用opencv, c#端使用OpenCvSharp, 返回一张图像

c++代码:

// OpenCVImageLibrary.cpp  
#include <opencv2/opencv.hpp>  
#include <vector>  extern "C" {  __declspec(dllexport) unsigned char* ReadImageToBGR(const char* filePath, int* width, int* height, int* step) {  cv::Mat image = cv::imread(filePath, cv::IMREAD_COLOR);  if (image.empty()) {  *width = 0;  *height = 0;  *step = 0;  return nullptr;  }  *width = image.cols;  *height = image.rows;  *step = image.step;  // 分配内存并复制图像数据  unsigned char* imageData = new unsigned char[image.total() * image.elemSize()];  std::memcpy(imageData, image.data, image.total() * image.elemSize());  return imageData;  }  __declspec(dllexport) void FreeImageMemory(unsigned char* imageData) {  delete[] imageData;  }  
}

c#代码 (使用OpenCvSharp):

using OpenCvSharp;  
using System;  
using System.Runtime.InteropServices;  class Program  
{  // 导入DLL中的函数  [DllImport("OpenCVImageLibrary.dll", CallingConvention = CallingConvention.Cdecl)]  public static extern IntPtr ReadImageToBGR(string filePath, out int width, out int height, out int step);  [DllImport("OpenCVImageLibrary.dll", CallingConvention = CallingConvention.Cdecl)]  public static extern void FreeImageMemory(IntPtr imageData);  static void Main()  {  string imagePath = "path_to_your_image.jpg"; // 替换为你的图像路径  int width, height, step;  // 调用C++ DLL中的函数来读取图像  IntPtr imageDataPtr = ReadImageToBGR(imagePath, out width, out height, out step);  if (imageDataPtr == IntPtr.Zero)  {  Console.WriteLine("Failed to read the image.");  return;  }  // 将图像数据从IntPtr转换为OpenCvSharp的Mat对象  Mat mat = new Mat(height, width, MatType.CV_8UC3, imageDataPtr, step);  // 显示图像(这里假设你有一个GUI应用程序,比如WinForms或WPF)  // 例如,在WinForms中使用PictureBox控件来显示图像  // PictureBox pictureBox = ...; // 获取或初始化你的PictureBox控件  // Bitmap bitmap = mat.ToImage<Bgr, Byte>().ToBitmap();  // pictureBox.Image = bitmap;  // 如果你在控制台应用程序中,可以保存图像到文件  Cv2.ImWrite("output.jpg", mat);  // 释放C++中分配的内存  FreeImageMemory(imageDataPtr);  // 不需要手动释放Mat对象,因为它不拥有原始图像数据的所有权  }  
}
http://www.lryc.cn/news/378911.html

相关文章:

  • 【Android面试八股文】你能说一说View绘制流程与自定义View注意点吗?
  • 【第24章】Vue实战篇之用户信息展示
  • “打造智能售货机系统,基于ruoyi微服务版本生成基础代码“
  • oracle12c到19c adg搭建(五)dg搭建后进行切换19c进行数据字典升级
  • 在公司的一些笔记
  • 2020C++等级考试二级真题题解
  • 面试官:聊聊 nextTick
  • shell编程之条件语句(shell脚本)
  • QT中QSettings的使用系列之二:保存和恢复应用程序主窗口
  • Linux系统上安装Miniconda并安装特定版本的Python
  • 解决Qt中 -lGL无法找到的问题
  • 【重要】《HTML趣味编程》专栏内资源的下载链接
  • 苍穹外卖环境搭建
  • 切割游戏介绍
  • 对接Paypal、Stripe支付简单流程
  • 微服务中不同服务使用openfeign 相互调用
  • 社区项目-项目介绍环境搭建
  • 【论文阅读】-- Omnisketch:高效的多维任意谓词高速流分析
  • 【ajax核心03】封装底层axios函数
  • python科学计算
  • Leetcode - 132双周赛
  • Mongodb在UPDATE操作中使用$push向数组中插入数据
  • ArcGIS JSAPI 高级教程 - ArcGIS Maps SDK for JavaScript - 锐化效果
  • 信息系统项目管理师 | 信息系统安全技术
  • Java数据类型与运算符
  • 网络虚拟化考题
  • 《C++ Primer》导学系列:第 7 章 - 类
  • idea intellij 2023打开微服务项目部分module未在左侧项目目录展示(如何重新自动加载所有maven项目model)
  • 生成视频 zeroscope_v2_576w 学习笔记
  • H3C综合实验