gpt4 book ai didi

c# - Image Control 不显示使用 OpenCVsharp 捕获的网络摄像头帧

转载 作者:太空宇宙 更新时间:2023-11-03 22:45:12 27 4
gpt4 key购买 nike

我已经在我的 XAML 代码后面编写了下面的代码,以在名为 查看

Mat mat = new Mat();
VideoCapture videoCapture = new VideoCapture(2);

while (true)
{
videoCapture.Read(mat);
viewer.Source = mat.ToBitmapImage();
if (btn_stop.IsPressed)
{
break;
}
}
videoCapture.Release();

如您所见,我使用转换器将 Mat 格式转换为 BitmapImage,因此我可以将其用作我的控件的图像源。这是我使用的转换器:

static class Converters
{
public static BitmapImage ToBitmapImage(this Bitmap bitmap)
{
BitmapImage bi = new BitmapImage();
MemoryStream ms = new MemoryStream();
bi.BeginInit();
bitmap.Save(ms, ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
bi.StreamSource = ms;
bi.EndInit();
bi.Freeze();
return bi;
}

public static BitmapImage ToBitmapImage(this Mat mat)
{
return BitmapConverter.ToBitmap(mat).ToBitmapImage();
}
}

只是这段代码在我的图像控件中没有显示任何内容,应用程序被卡住了。我知道这段代码产生了太多垃圾,我对此无能为力。关于我的问题的任何想法?我还根据 this 中给出的说明更改了我的代码链接如下:

viewer.Source = (BitmapSource)new ImageSourceConverter().ConvertFrom(mat.ToBytes());  

还有这些转换器:

public static BitmapImage ToBitmapImage(this Mat mat)
{
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = new System.IO.MemoryStream(mat.ToBytes());
image.EndInit();
return image;
}

public static BitmapImage ToBitmapImage(this Mat mat)
{
using (var ms = new System.IO.MemoryStream(mat.ToBytes()))
{
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = ms;
image.EndInit();
return image;
}
}

这些都不适合我。

最佳答案

这是根据 Clemens 给出的答案的评论:
只需在 MainWindow 的构造函数中实例化一个 DispatcherTimer 对象,并使用 Tick 事件来更新 UI:

DispatcherTimer Timer = new DispatcherTimer();  
Timer.Tick += Timer_Tick;
Timer.Interval = TimeSpan.FromMilliseconds(30);
Timer.Start();

private void Timer_Tick(object sender, EventArgs e)
{
if (videoCapture.Read(frame))
{
view.Source = OpenCvSharp.Extensions.BitmapSourceConverter.ToBitmapSource(frame);
}
}

关于c# - Image Control 不显示使用 OpenCVsharp 捕获的网络摄像头帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48509517/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com