我在WPF中使用EmguCV,我发现这个例子TP捕获图像,我想在我的一些其他方法Method3()中使用bs1,但我得到错误,该对象属于一些其他线程,任何人都有任何想法是什么问题? BS1毕竟是一个全局变量后WPF线程错误
BitmapSource bs1;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
capture = new Capture(); ///capture image
timer = new DispatcherTimer(); // timer object
timer.Interval = new TimeSpan(500);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
using ( Image<Bgr, byte> Frame = capture.QueryFrame())
{
if (Frame != null)
{
bs1 = ToBitmapSource(Frame);
webcam.Source = ToBitmapSource(Frame); // ToBitmapSource convert image to bitmapsource webcam is a picture in mainwindow
Frame.Save("fg.jpeg"); //this work but use lot of processing
}
}
}
public void Method3_click (...)
{
use_of_bs1(bs1);
}
private void use_of_bs1()
{
data.Text = "waiting...";
System.Threading.ThreadPool.QueueUserWorkItem(Startwork);
}
private void Startwork(object state)
{
try
{
_work = _worker.bs1_analysis(bs1); // it is where bs1 giving thread errorbs1_analysis is library function
}
catch (Exception ex)
{
Dispatcher.BeginInvoke(new ShowworkInformationDelegate(ShowworkInformation));
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
Dispatcher.BeginInvoke(new ShowWorkInformationDelegate(ShowWorkInformation));
}
/// ToBitmapsource功能
public static BitmapSource ToBitmapSource(Emgu.CV.IImage image)
{
using (System.Drawing.Bitmap source = image.Bitmap)
{
IntPtr ptr = source.GetHbitmap();
BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ptr, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
DeleteObject(ptr);
return bs;
}
}
看看http://blog.somecreativity.com/2008/01/10/wpf-equivalent-of-invokerequired/ – Mohit 2012-03-06 12:06:29
考虑到你使用的是DispatcherTimer,我猜你的Tick()是在调度程序线程正确地被解雇,所以你不需要特别调度。有可能指定什么函数引发这个错误?您发布的代码或您拥有的** NOT **代码(例如'Capture'类或'ToBitmapSource()'funcion)? – 2012-03-06 12:34:00
实际上方法3是引发错误的方法 method3是一个按钮,它具有也使用bs1的线程的功能 – murmansk 2012-03-07 05:40:26