title: How to copy the image data from a BitmapSource (WPF) to a cv::Mat (OpenCV) in C++/CLI in a different thread?
body: <p>I have a <code>BitmapSource</code> created in the UI thread and I would like to copy its pixel data to a <code>cv::Mat</code> for processing on a separate thread. Of course it works if I wrap the copy code with <code>Dispatcher.Invoke</code> call but then I waste synchronization time.</p>
  
  <pre><code>int width = bitmapSource-&gt;PixelWidth;
  int height = bitmapSource-&gt;PixelHeight;
  int bytesPerPixel = bitmapSource-&gt;Format.BitsPerPixel / 8;
  int stride = 4 * ((width * bytesPerPixel + 3) / 4);
  
  ...
  
  cv::Mat &amp;inputImage = wrapper.getRawImage();  // This is a refe
  if (inputImage.size().width != width || inputImage.size().height != height || inputImage.type() != newType) 
      inputImage = cv::Mat::zeros(height, width, newType);
  bitmapSource-&gt;CopyPixels(Int32Rect::Empty, IntPtr(inputImage.data), height*stride, stride);
  </code></pre>
  
  <p>I tried freezing the <code>bitmapSource</code> object and now it works until the call to <code>CopyPixels</code> but it fails when trying to copy its content to the <code>inputImage</code> data. If the object is frozen why <code>CopyPixels</code>can't copy its frozen buffer to another memory buffer? Any ideas on how to avoid invoking the call on the main thread? Is there any other WPF bitmap object capable of doing this?</p>