嗨,我正在尝试将 BitmapSource 从 Kinect RGB 颜色流转换为位图。我越来越空了。我正在为 Windows SDK 1.6、Visual Studio 2012、Windows 7 Ultimate 64bit、EmguCV 2.4.2.1777 使用 Kinect。这是代码:
void _kinect_ColorFrameReady( object sender, ColorImageFrameReadyEventArgs e )
{
using ( ColorImageFrame colorFrame = e.OpenColorImageFrame() )
{
if ( colorFrame == null )
{
return;
}
if ( colorFrame != null )
{
this.colorPixels = new byte[colorFrame.PixelDataLength];
colorFrame.CopyPixelDataTo( this.colorPixels );
int stride = colorFrame.Width * 4;
colorBmp = BitmapSource.Create(
colorFrame.Width,
colorFrame.Height,
96,
96,
PixelFormats.Bgr32,
null,
colorPixels,
stride
);
currentColorFrame = new Image<Bgr, Byte>( colorBmp.ToBitmap() );
this.imgOutput.Source = ImageHelpers.ToBitmapSource( currentColorFrame );
}
}
}
辅助方法:
public static System.Drawing.Bitmap ToBitmap(this BitmapSource bitmapsource)
{
System.Drawing.Bitmap bitmap;
using ( var outStream = new MemoryStream() )
{
// from System.Media.BitmapImage to System.Drawing.Bitmap
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add( BitmapFrame.Create( bitmapsource ) );
enc.Save( outStream );
bitmap = new System.Drawing.Bitmap( outStream );
return bitmap;
}
}
[DllImport("gdi32")]
private static extern int DeleteObject(IntPtr o);
/// <summary>
/// Convert an IImage to a WPF BitmapSource. The result can be used in the Set Property of Image.Source
/// </summary>
/// <param name="image">The Emgu CV Image</param>
/// <returns>The equivalent BitmapSource</returns>
public static BitmapSource ToBitmapSource(IImage image)
{
using (System.Drawing.Bitmap source = image.Bitmap)
{
IntPtr ptr = source.GetHbitmap(); //obtain the Hbitmap
BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
ptr,
IntPtr.Zero,
Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
DeleteObject(ptr); //release the HBitmap
return bs;
}
}
请指出我的错误或尽快给我任何建议。