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

发布于:2024-06-22 ⋅ 阅读:(116) ⋅ 点赞:(0)

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对象,因为它不拥有原始图像数据的所有权  
    }  
}

网站公告

今日签到

点亮在社区的每一天
去签到