Click here to Skip to main content
15,881,898 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi, i am capturing image with Webcam. based on the device(laptop) used, the image capture either freezes at some point or not. What i want to achieve is to ensure that the capture does not freeze.

Here is the function that captures the image. it uses Direct Show Library
C#
private void captureImage()
       {
           // Release any previous buffer
           if (m_ip != IntPtr.Zero)
           {
               Marshal.FreeCoTaskMem(m_ip);
               m_ip = IntPtr.Zero;
           }

           // capture image
           m_ip = cam.Click();
           b = new Bitmap(cam.Width, cam.Height, cam.Stride, System.Drawing.Imaging.PixelFormat.Format24bppRgb, m_ip);

           // If the image is upsidedown
           b.RotateFlip(RotateFlipType.RotateNoneFlipY);

           System.Windows.Controls.Image win = UIHelper.FindChild<System.Windows.Controls.Image>(System.Windows.Application.Current.MainWindow, "photo");

           win.Source = BitmapToImageSource(b);
           cam.Dispose();
           this.DialogResult = true;
           this.Close();
       }


What I have tried:

i'm trying to implement the asynchronous operation in a the Tick event handler of a dispatcher timer

C#
void timer_Tick(object sender, EventArgs e)
        {
            i = --i;
            count.Content = i;
            if (i == 2)
            {
                prog.IsActive = true;
                new Task(captureImage).Start();
                
            }
            if (i == 0)
            {
                timer.Stop();
            }
        }


when i do that, i get this error "The calling thread cannot access this object because a different thread owns it" on this line "
C#
System.Windows.Controls.Image win = UIHelper.FindChild<System.Windows.Controls.Image>(System.Windows.Application.Current.MainWindow, "photo");
" in the capture function

but when i use a dispatcher.Invoke like this
C#
this.Dispatcher.Invoke((Action)(() =>
                {
                    captureImage();
                }));

the frame still freezes, any idea how to fix this?
Posted
Updated 19-Oct-17 21:46pm

1 solution

Learn the basics of MVVM. Bind properties of some controls (View) to properties of a ViewModel. The Binding engine takes care of the correct thread. In your model, run your thread for capturing the image, raise an event to the ViewModel for every new image.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900