我有一个基于opencv的dll,用c ++编写。我需要在dll中加载cv :: Mat图像,然后从C#UI调用它。我在WinForms中工作,但现在转向WPF。
我在dll中公开了以下功能:
__declspec(dllexport)uchar* GetBlankFrame(void)
{
cv::Mat img = cv::imread("D://data/TestPattern.jpg", 1);
static cv::Mat tmp;
cv::cvtColor(img, tmp, CV_BGRA2BGR);
return tmp.data;
}
在winForms应用程序中,我曾经用它来创建一个Bitmap:
[DllImport("tester.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr GetBlankFrame();
IntPtr frame = GetBlankFrame();
Bitmap blank = new Bitmap(600, 800, 3 * 600, System.Drawing.Imaging.PixelFormat.Format24bppRgb, GetBlankFrame());
这很好用。
现在,我正在尝试将此功能移至WPF应用程序。要显示图片,我似乎需要使用BitmapSource
代替Bitmap
。
我在尝试:
IntPtr frame = GetBlankFrame();
BitmapSource srcFrame = Imaging.CreateBitmapSourceFromHBitmap(frame, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
但它给了我:
An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in PresentationCore.dll
我哪里错了?
谢谢。
答案 0 :(得分:0)
我已经解决了这个问题:
public BitmapSource convertBitmap(Bitmap source)
{
return Imaging.CreateBitmapSourceFromHBitmap(source.GetHbitmap(), IntPtr.Zero,
Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
}
IntPtr frame = GetBlankFrame();
Bitmap blank = new Bitmap(600, 800, 3 * 600, System.Drawing.Imaging.PixelFormat.Format24bppRgb, frame);
BitmapSource src = convertBitmap(blank);
不确定这是否是最好/最有效的方式(可以接受更多建议),但它看起来有效。