I am using EmguCV in WPF and i found this example tp capture image , I want to use bs1 in my some other method Method3(), but i am getting error that object belong to some other thread, anyone has any idea what is the problem ? bs1 is after all a global variable
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 function is
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;
}
}
If you create a wpf resource and want to use it on a different thread, you can call
Freeze()on the object before passing it on. That will make it immutable and legal to use on another thread.