我正在使用Emgu OpenCV從網絡攝像頭抓取圖像,並且想用WPF Image
來控制它們。
所以我需要將圖像從Mat
轉換爲與Image
控件兼容的東西。所以我把從Emgu例子這個類:處理大圖像時垃圾收集器速度太慢
public static class BitmapSourceConvert
{
/// <summary>
/// Delete a GDI object
/// </summary>
/// <param name="o">The poniter to the GDI object to be deleted</param>
/// <returns></returns>
[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;
}
}
}
這就像爲小圖像(640×480爲例)魅力。當使用任務管理器(我在Windows 8上)時,我看到使用的內存在增加和減少。工作正常。
但是,當使用像1920x1080這樣的較大圖像時,應用程序會在短時間內崩潰,但不會有更多內存。當再次查看任務管理器時,我可以看到內存消耗增加,一旦下降,然後上升,直到拋出異常。 感覺垃圾收集器的工作不足以釋放所有空間。
所以我試圖通過在函數中的某處添加GC.Collect()手動啓動垃圾回收器。它再次運作。即使是大圖像。
我認爲手動調用垃圾收集器既不是好的樣式,也不是高性能的。任何人都可以請提供如何解決這個問題,而無需調用GC.Collect()?
水晶球說,你永遠不會調用IImage.Dispose()。是的,GC.Collect()會隱藏這個問題。 –