Capture EMGU CV camera in WPF?

Everything that I try to display in the frame of captured frames in WPF. I can already display the image. But you can not understand the way events are handled? In WinForm, this is Application.Idle, but what should I use in WPF? I already saw this thread . I could not do that.

+3
source share
1 answer

Why can't you use the Timer.Elapsed event?

Just remember that the Elapsed callback occurs in the Worker Thread, which makes it impossible to update the user interface. Therefore, you should use SynchronizationContext to direct UI update actions to the appropriate thread.

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

, , DispatcherInactive event:

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

Source: https://habr.com/ru/post/1786986/


All Articles