编程语言
首页 > 编程语言> > c#-在WPF中捕获EMGU CV摄像机?

c#-在WPF中捕获EMGU CV摄像机?

作者:互联网

我试图在WPF中显示照相机捕获的帧.我已经可以显示图像了.但是无法找出事件处理方法吗?在WinForm中是Application.Idle,但是在WPF中应该使用什么?我已经看过这个thread了..我做不到.

解决方法:

为什么不能使用Timer.Elapsed事件?

只需记住,在Worker Thread中会发生Elapsed回调,这将导致无法更新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事件做出反应:

    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;
                };
            }
        }
    }

标签:emgucv,image-processing,camera,wpf,c
来源: https://codeday.me/bug/20191105/1995547.html