将mat从DLL c++传递到图像资源c#
本文关键字:图像 资源 mat DLL c++ | 更新日期: 2023-09-27 17:52:17
我正在使用Visual c# 2010,我喜欢从DLL c++发送图像到我的Visual c# 2010。图像有166*166*24从DLL c++发送到c#。我使用以下代码:
main.cpp
unsigned char* test()
{
read image from filename
Mat OriginalImg = imread(fileName, CV_LOAD_IMAGE_COLOR);
return (OriginalImg.data);}
OriginalImg.data return the pointer to the image.
main.h
extern "C" { __declspec(dllexport) unsigned char* test();}
,在我的visualc#程序中,我使用以下代码:
[DllImport("testng.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr test();
IntPtr intPtr1;
BitmapImage bitmapImage;
calling the c++ dll
intPtr1 = test(1);
if (intPtr1.ToString().CompareTo("0") != 0)
{
create a bitmap with the pointer
Bitmap bitmap = new Bitmap(166, 166, 3 * 166, System.Drawing.Imaging.PixelFormat.Format24bppRgb, intPtr1);
to show the bitmap i need to convert it to a bitmap image
bitmapImage=convertBitmapToBitmapImage(bitmap);
System.Windows.Media.ImageBrush ib = new System.Windows.Media.ImageBrush();
ib.ImageSource = bitmapImage;
i put the image received from c++ dll like a background to my canvas: canvasImage
windows.canvasImage.Background = ib;
}
BitmapImage convertBitmapToBitmapImage(Bitmap bitmap)
{
IntPtr hBitmap = bitmap.GetHbitmap();
BitmapSource retval;
try
{
retval = Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
}
finally
{
//DeleteObject(hBitmap);
}
return (BitmapImage)retval;
}
我的猜测是指向cv::Mat
数据的指针在函数test()
返回后不再有效,因为变量OriginalImg
超出了范围,析构函数已经清理了OriginalImg
数据。如果可能的话,请尝试将OriginalImg
设置为全局,以防止自动销毁变量。
一般来说,我建议为OpenCV制作一个通用的c++/CLI包装器。A为此发了一个帖子。例如,我现在正在处理与您相同的问题,我正在C++/CLI中创建System.Drawing.Bitmap
对象,而没有任何DllImport
s…