title: How to minimize the lag from the live stream using OpenCV/EmguCV WPF
body: <p>I am using EmguCV to get a live stream from a high-resolution webcam. (full HD)
  The issue is that there is a significant lag in the video.
  I compared with the Windows camera app and my application is much more delayed.</p>
  
  <p>Here is the code snippet I am using to get the live stream and show on the canvas.
  I am wondering if I am missing anything important to minimize the lag.
  If anybody is experienced, please help me.</p>
  
  <pre><code>void init_camera()
  {
      m_capture= new VideoCapture(0);
      m_capture.ImageGrabbed += ProcessFrame;
  }
  
  void ProcessFrame()
  {
      if (m_capture_in_progress)
          return;
      m_capture_in_progress = true;
      if (m_capture != null &amp;&amp; m_capture.Ptr != IntPtr.Zero)
      {
          m_capture.Retrieve(m_frame, 0);
          if (m_frame != null &amp;&amp; m_frame.Bitmap != null)
          {
              if (IsRecording &amp;&amp; m_video_writer != null &amp;&amp; m_video_writer.IsOpened)
              {
                  try
                  {
                      m_video_writer.Write(m_frame);
                  }
                  catch (Exception ex)
                  {
                      log(ex.Message + "\n" + ex.StackTrace);
                  }
              }
  
              this.Dispatcher.Invoke(() =&gt;
              {
                  using (var stream = new MemoryStream())
                  {
                      m_frame.Bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                      using (var outstream = new MemoryStream(stream.ToArray()))
                      {
  
                          BitmapImage bitmap = new BitmapImage();
                          bitmap.BeginInit();
                          bitmap.StreamSource = new MemoryStream(stream.ToArray());
                          bitmap.CacheOption = BitmapCacheOption.OnLoad;
                          bitmap.EndInit();
  
                          ui_canvas.Background = new ImageBrush(bitmap);
                      }
                  };
              });
          }
      }
      m_capture_in_progress = false;
  }
  
  
  </code></pre>