C# EmguCV事件WPF应用程序
我对以下代码有问题C# EmguCV事件WPF应用程序,c#,multithreading,emgucv,C#,Multithreading,Emgucv,我对以下代码有问题 namespace MyApp { public partial class PhotoWindow : Window { private Capture _capture; public PhotoWindow () { InitializeComponent(); _capture = new Capture(); i
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());
}
}
}
}
名称空间MyApp
{
公共部分类PhotoWindow:Window
{
私人捕获(private Capture);;
公共摄影窗口()
{
初始化组件();
_捕获=新捕获();
如果(_capture!=null)
{
//在XAML中
CaptureSource.Width=150;
CaptureSource.高度=180;
_capture.imagegrapped+=ProcessFrame;
_capture.Start();
}
已激活+=(s,e)=>_capture.Start();
关闭+=(s,e)=>
{
if(_capture==null)返回;
_capture.Stop();
_capture.Dispose();
};
}
私有void ProcessFrame(对象发送方、事件参数)
{
尝试
{
图像帧=_capture.RetrieveBgrFrame();
CaptureSource.Source=Helper.ToBitmapSource(框架);
}
捕获(异常)
{
System.Windows.MessageBox.Show(exception.ToString());
}
}
}
}
当我运行应用程序时,我得到异常System.invalidooperationexception:此调用无法访问此对象的线程,因为所有者是第CaptureSource.Source=Helper.ToBitmapSource(frame)行上的另一个线程代码>
我可以解决这个问题吗?似乎ImageGrapped事件是从Capture的后台线程引发的,因此您的处理程序是在该线程中运行的,而不是在窗口的UI线程中运行的
您可以使用Dispatcher调用控件UI线程中的代码
CaptureSource.Dispatcher.Invoke(() =>
{
Image<Bgr, Byte> frame = _capture.RetrieveBgrFrame();
CaptureSource.Source = Helper.ToBitmapSource(frame);
});
CaptureSource.Dispatcher.Invoke(()=>
{
图像帧=_capture.RetrieveBgrFrame();
CaptureSource.Source=Helper.ToBitmapSource(框架);
});
似乎ImageCapture事件是从Capture的后台线程引发的,因此处理程序运行在该线程中,而不是窗口的UI线程中
您可以使用Dispatcher调用控件UI线程中的代码
CaptureSource.Dispatcher.Invoke(() =>
{
Image<Bgr, Byte> frame = _capture.RetrieveBgrFrame();
CaptureSource.Source = Helper.ToBitmapSource(frame);
});
CaptureSource.Dispatcher.Invoke(()=>
{
图像帧=_capture.RetrieveBgrFrame();
CaptureSource.Source=Helper.ToBitmapSource(框架);
});
我在UI中使用Emgu.CV.UI.ImageBox
来显示捕获的图像帧
Image<Bgr, Byte> frame = _capture.RetrieveBgrFrame();
imageBox.Invoke(new Action(() => imageBox.Image = frame));
Image frame=\u capture.RetrieveBgrFrame();
Invoke(新操作(()=>imageBox.Image=frame));
我在UI中使用Emgu.CV.UI.ImageBox
来显示捕获的图像帧
Image<Bgr, Byte> frame = _capture.RetrieveBgrFrame();
imageBox.Invoke(new Action(() => imageBox.Image = frame));
Image frame=\u capture.RetrieveBgrFrame();
Invoke(新操作(()=>imageBox.Image=frame));