C# 图像控件不显示使用OpenCVsharp捕获的网络摄像头帧
我已经在XAML Code behind中编写了下面的代码,用OpencvsharpC# 图像控件不显示使用OpenCVsharp捕获的网络摄像头帧,c#,wpf,opencv,opencvsharp,C#,Wpf,Opencv,Opencvsharp,我已经在XAML Code behind中编写了下面的代码,用OpencvsharpVideoCapture.Read()在名为View的图像控件中显示作为Mat接收的网络摄像机帧 Mat mat = new Mat(); VideoCapture videoCapture = new VideoCapture(2); while (true) { videoCapture.Read(mat); viewer.Source = mat.ToBitmapImage();
VideoCapture.Read()在名为View
的图像控件中显示作为Mat
接收的网络摄像机帧
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();
}
}
简单地说,这段代码在我的图像控件中没有显示任何内容,应用程序被冻结。我知道这段代码产生了太多的垃圾,对此我无能为力。对我的问题有什么想法吗?我还按照链接中给出的说明更改了代码,如下所示:
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;
}
}
所有这些对我都不起作用。根据的评论,答案如下:
只需在主窗口
的构造函数中激活一个分派器
对象,并使用勾选
事件来更新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);
}
}
同时设置bi.CacheOption=BitmapCacheOption.OnLoad
@Clemens我使用了u和你设置的链接上提到的其他所有说明,我的问题与你的完全相同!他们都不为我工作。我将编辑我的问题并写下更改!您的while(true)
循环正在阻塞UI线程。改用计时器,例如调度员。是的,它起作用了。Tnx@Clemens