EmguCV ImageGrabbed Event WPF App

流过昼夜 提交于 2019-12-24 10:46:18

问题


I have problems with the following code

namespace MyApp
{    
    public partial class PhotoWindow : Window
    {
        private Capture _capture;

        public PhotoWindow ()
        {
            InitializeComponent();    
            _capture = new Capture();

            if (_capture != null)
            {
                //<Image> in XAML
                CaptureSource.Width = 150;
                CaptureSource.Height = 180;

                _capture.ImageGrabbed += ProcessFrame;
                _capture.Start();                
            }

            Activated += (s, e) => _capture.Start();
            Closing += (s, e) =>
            {
                if (_capture == null) return;
                _capture.Stop();                
                _capture.Dispose();
            };
        }

        private void ProcessFrame(object sender, EventArgs e)
        {
            try
            {
                Image<Bgr, Byte> frame = _capture.RetrieveBgrFrame();                   
                CaptureSource.Source = Helper.ToBitmapSource(frame);
            }
            catch (Exception exception)
            {

                System.Windows.MessageBox.Show(exception.ToString());
            }
        }

    }
}

when I run the application I get the exception System.InvalidOperationException: The thread that this call can not access this object because the owner is another thread on line CaptureSource.Source = Helper.ToBitmapSource(frame);

As I can solve this?


回答1:


It seems that ImageGrabbed event is raised from Capture's background thread and because of that your handler is running in that thread rather then the UI thread of your window.

You can use the Dispatcher to invoke code in the control's UI thread.

CaptureSource.Dispatcher.Invoke(() =>
{
   Image<Bgr, Byte> frame = _capture.RetrieveBgrFrame();                   
   CaptureSource.Source = Helper.ToBitmapSource(frame);
});



回答2:


I use Emgu.CV.UI.ImageBox in the UI to display the Image<,> frame from the Capture

Image<Bgr, Byte> frame = _capture.RetrieveBgrFrame();    
imageBox.Invoke(new Action(() => imageBox.Image = frame));


来源:https://stackoverflow.com/questions/11402314/emgucv-imagegrabbed-event-wpf-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!