问题描述
我写了这个示例code解释我的问题。我在VS 2013的解决方案,包含了一个C#项目和一个C ++项目。我尝试阅读OpenCV的C ++中(86)的图像。并希望在传递给一个C#项目86(使用CLR模式)为位图对象,然后BitmapImage的对象作为一个WPF的ImageSource使用。结果
我的C ++ code:
I wrote this sample code to explain my problem. I have a solution in VS 2013, contains one C# project and a C++ project. I try to read an image with OpenCV in C++ (x86). and want to pass in to a C# x86 project (used CLR mode) to a Bitmap Object and Then BitmapImage Object to use as a WPF ImageSource.
My C++ Code:
Bitmap^ SomeClass::Test(System::String^ imgFileName)
{
auto fileName = msclr::interop::marshal_as<string>(imgFileName);
Mat img = imread(fileName);
//Do something
auto bmp = gcnew Bitmap(img.cols, img.rows, img.step, Imaging::PixelFormat::Format24bppRgb, (IntPtr)img.data);
bmp->Save("InC++Side.png");
return bmp;
}
我的C#code:
My C# Code:
private void ImageTester(object sender, RoutedEventArgs e)
{
var image = testClass.Test("test.png");
image.Save("InC#Side.png");
bg.Source = ConvertToBitmapImageFromBitmap(image);
}
public static BitmapImage ConvertToBitmapImageFromBitmap(Bitmap image)
{
using(var ms = new MemoryStream())
{
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
BitmapImage bImg = new BitmapImage();
bImg.BeginInit();
bImg.StreamSource = new MemoryStream(ms.ToArray());
bImg.EndInit();
return bImg;
}
}
问题是用C ++(INC ++ Side.png)保存的文件是完美的;但另一种是presented C#中的位图对象只是与图像的高度和宽度一个灰色的矩形。结果
问题出在哪里?结果
我怎么可以将图像传递给我的C#项目?
Problem is that the file saved by C++ (InC++Side.png) is perfect; but the other one which is presented the Bitmap object in C# is just a gray rectangle with that image's Height and Width.
Where is the problem?
How I can pass the Image to my C# project?
推荐答案
看来这个问题是关于共享内存。结果垫
和位图
是共享 C ++
的内存。所以,当垫
对象销毁时,位图
对象无法访问数据。这就是为什么它的数据是在C ++侧正确的,但在C#中端里面什么都没有。结果
为了解决这个问题,我用静电台垫
。它永远不会释放,但能解决我的问题。
It seems that the problem is about the shared memory.Mat
and Bitmap
are share the memory in C++
. So, when the Mat
object destroys, the Bitmap
object can't access to the data. That's why its data is correct in C++ side but have nothing inside in C# side.
To solving this problem, I used static Mat
. It'll never release, but can solve my problem.
这篇关于转换的图像OpenCV的CV ::垫格式为C#的BitmapImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!