将来自dll c ++的mat传递给imagesource c#

时间:2014-03-24 10:38:12

标签: c# c++ opencv

我正在使用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();}

在我的程序Visual C#中,我使用了这段代码:

 [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;



                }

1 个答案:

答案 0 :(得分:0)

我的猜测是cv::Mat数据的指针在函数test()返回后不再有效,因为变量OriginalImg超出范围,析构函数已清除OriginalImg数据。如果可以防止自动销毁变量,请尝试将OriginalImg设为全局。

通常,我建议为OpenCV制作通用的C ++ / CLI包装器。关于此问题的a post。例如,我现在正在处理与您相同的问题,并且我在C ++ / CLI中创建了一个System.Drawing.Bitmap对象而没有任何DllImport ...