【发布时间】:2012-09-04 07:40:00
【问题描述】:
我正在使用 Winforms 中的 Emgu Cv 使用 Kinect 进行人脸识别。现在,我想转移到 WPF。但是,EmguCv 库仅支持 Bitmap 类。
我可以在 WPF 中使用 Bitmap 类(在 Winforms 中使用)吗?如果没有,是否有其他方法可以在 WPF 中使用 Emgu cv 和 kinect?
谢谢。
【问题讨论】:
我正在使用 Winforms 中的 Emgu Cv 使用 Kinect 进行人脸识别。现在,我想转移到 WPF。但是,EmguCv 库仅支持 Bitmap 类。
我可以在 WPF 中使用 Bitmap 类(在 Winforms 中使用)吗?如果没有,是否有其他方法可以在 WPF 中使用 Emgu cv 和 kinect?
谢谢。
【问题讨论】:
System.Drawing.Bitmap不能直接作为WPF的图片源,需要转换成System.Windows.Media.Imaging.BitmapSource。
最好的方法是使用Imaging.CreateBitmapSourceFromHBitmap。
你可以使用扩展方法:
[DllImport("gdi32")]
private static extern int DeleteObject(IntPtr o);
public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
IntPtr ip = source.GetHbitmap();
try
{
return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip,
IntPtr.Zero, Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
}
finally
{
DeleteObject(ip);
}
}
请注意,您必须调用 DeleteObject,因为 Bitmap.GetHbitmap() 会泄漏 GDI 句柄(请参阅 this 答案)。
一旦有了BitmapSource,就可以使用Image 控件并通过设置Source 属性来显示它。
您可以在本文中阅读有关 WPF 成像的更多信息:Imaging Overview
【讨论】:
System.Drawing.dll 和PresentationCore.dll。顺便说一句,如果您发现有帮助的答案,您可以将其标记为“已接受”。见How does accepting an answer work?。