【发布时间】:2021-10-11 04:24:43
【问题描述】:
上下文
我有一台 Basler 相机,它会在捕获新图像时引发事件。
在事件 arg 中,我可以将图像抓取为字节数组。
我必须对此图像进行计算,然后将其显示在 WPF 应用程序中。相机刷新率高达40FPS。
问题并找到解决方案
可以在此处找到将字节数组转换为 WPF 图像的解决方案:Convert byte array to image in wpf
这个解决方案非常适合只转换一次字节数组,但是我觉得在 40FPS 时会丢失很多内存。每次都会创建一个新的 BitmapImage() 并且不能被释放。
是否有更好的解决方案来在 WPF 中显示一个变化高达 40 FPS 的字节数组?(可以完全重新考虑处理问题的方式)
代码
这种在 WPF 中显示相机流的解决方案有效,但 BitmapImage image = new BitmapImage(); 行对我来说并不好。
private void OnImageGrabbed(object sender, ImageGrabbedEventArgs e)
{
// Get the result
IGrabResult grabResult = e.GrabResult;
if (!grabResult.GrabSucceeded)
{
throw new Exception($"Grab error: {grabResult.ErrorCode} {grabResult.ErrorDescription}");
}
// Make process on the image
imageProcessor.Process(grabResult);
// Convert grabResult in BGR 8bit format
using Bitmap bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
IntPtr ptrBmp = bmpData.Scan0;
converter.Convert(ptrBmp, bmpData.Stride * bitmap.Height, grabResult);
bitmap.UnlockBits(bmpData);
// Creat the BitmapImage
BitmapImage image = new BitmapImage(); // <-- never Disposed !
using (MemoryStream memory = new MemoryStream())
{
bitmap.Save(memory, ImageFormat.Bmp);
memory.Position = 0;
image.BeginInit();
image.StreamSource = memory;
image.CacheOption = BitmapCacheOption.OnLoad;
image.EndInit();
image.Freeze();
}
LastFrame = image; // View is binded to LastFrame
}
【问题讨论】:
-
您遇到问题了吗?为什么你认为你不dispose it?
-
单个 WriteableBitmap 应该表现得更好。
-
我投票决定将此问题作为题外话结束,因为有关 代码优化 的问题是题外话。请参阅 Can I post questions about optimizing code on Stack Overflow? 和 Is it okay to ask for code optimization help? 了解更多信息。