我正在尝试在 WPF 中显示相机捕获的帧。我已经可以显示图像了。但是想不通事件处理方法?在 WinForm 中它是 Application.Idle 但我应该在 WPF 中使用什么?我看过这个thread已经..我做不到。
最佳答案
为什么不能使用 Timer.Elapsed 事件?
请记住,Elapsed 回调发生在 Worker Thread 中,这使得 UI 无法更新。因此,您应该使用 SynchronizationContext 将 UI 更新操作定向到适当的线程。
private SynchronizationContext _context = SynchronizationContext.Current;
void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
using (Image<Bgr, byte> frame = capture.QueryFrame())
{
if (frame != null)
{
this._context.Send(o =>
{
using (var stream = new MemoryStream())
{
// My way to display frame
frame.Bitmap.Save(stream, ImageFormat.Bmp);
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = new MemoryStream(stream.ToArray());
bitmap.EndInit();
webcam.Source = bitmap;
}
},
null);
}
}
}
或者,由于所有 UI 任务都通过 Dispatcher,您可以对 DispatcherInactive 事件使用react:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//...
this.Dispatcher.Hooks.DispatcherInactive += new EventHandler(Hooks_DispatcherInactive);
}
void Hooks_DispatcherInactive(object sender, EventArgs e)
{
using (Image<Bgr, byte> frame = capture.QueryFrame())
{
if (frame != null)
{
using (var stream = new MemoryStream())
{
// My way to display frame
frame.Bitmap.Save(stream, ImageFormat.Bmp);
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = new MemoryStream(stream.ToArray());
bitmap.EndInit();
webcam.Source = bitmap;
};
}
}
}
关于c# - WPF 中的 EMGU CV 相机捕获?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4762409/