使用C ++中的OpenCV读取图像并在C#中显示

时间:2015-07-16 05:33:55

标签: c# c++ opencv bitmap

我在C ++中有Mat,这是我的形象 我使用OpenCV进行了一些操作,现在想将它发送到我的C#项目并将其用作ImageSource
但是当我想在c#中调用转换器时,要将其转换为ImageSource,我会在bitmapObj.Save上遇到此错误:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

我的示例C ++源代码是:

Bitmap^ SomeClass::Test(System::String^ imgFileName)
{
   auto fileName = msclr::interop::marshal_as<string>(imgFileName);
   Mat img = imread(fileName);  
   auto bmp = gcnew Bitmap(img.cols, img.rows, img.step, Imaging::PixelFormat::Format24bppRgb, (IntPtr)img.data);
   img.release();
   return bmp;
}

我的样本c#代码是:

private void ImageTester(object sender, RoutedEventArgs e)
{
    var image = testClass.Test("test.png");
    bg.Source = ConvertToBitmapImageFromBitmap(image);          
}   

public static BitmapImage ConvertToBitmapImageFromBitmap(Bitmap btm)
{
    using(var ms = new MemoryStream())
    {
        btm.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        BitmapImage bImg = new BitmapImage();
        bImg.BeginInit();
        bImg.StreamSource = new MemoryStream(ms.ToArray());
        bImg.EndInit();
        return bImg;
    }
}       

0 个答案:

没有答案