3

I'm working with Emgu Cv in Winforms to do face recognition using Kinect. Now, i want to move to WPF. However, the EmguCv library support only Bitmap class.

Can i use the Bitmap class (used in Winforms) in WPF ? if not, is there an other method to use Emgu cv with kinect in WPF?

Thanks.

Rafik Haceb
  • 153
  • 1
  • 2
  • 14

1 Answers1

11

System.Drawing.Bitmap can not be used directly as image source for WPF, so you have to convert it to System.Windows.Media.Imaging.BitmapSource.

The best way to do it is by using Imaging.CreateBitmapSourceFromHBitmap.

You can use an extension method:

[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);
    }
}

Please note that you must invoke DeleteObject, because Bitmap.GetHbitmap() leaks a GDI handle (see this answer).

Once you have a BitmapSource, you can display it using an Image control and by setting the Source property.

You can read more about WPF imaging in this article: Imaging Overview

Community
  • 1
  • 1
Paolo Moretti
  • 54,162
  • 23
  • 101
  • 92
  • Hello, should i add a reference to system.Drawing ? – Rafik Haceb Sep 12 '12 at 20:44
  • @RafikHaceb Yes, make sure that your project has a reference to `System.Drawing.dll` and `PresentationCore.dll`. By the way, if you find an answer helpful, you can mark it as 'accepted'. See [How does accepting an answer work?](http://meta.stackexchange.com/a/5235/164263). – Paolo Moretti Sep 13 '12 at 08:03