title: OpenCV 2.4 : Displaying a cv::Mat in MFC
body: <p>I am updating an existing code base from IplImage* to the newer cv::Mat. I was wondering how to display my cv::Mat object to MFC. The current solution we are using is based on the old CvvImage class:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>void DrawPicToHDC(IplImage *img, UINT ID, bool bOnPaint)
  {
      CDC *pDC = GetDlgItem(ID)-&gt;GetDC();
      HDC hDC= pDC-&gt;GetSafeHdc();
      CRect rect;
      GetDlgItem(ID)-&gt;GetClientRect(&amp;rect);
      CvvImage cimg;
      cimg.CopyOf( img );
      cimg.DrawToHDC( hDC, &amp;rect );
      ReleaseDC( pDC );
  }
  </code></pre>
  
  <p>I came across <a href="https://stackoverflow.com/questions/12891307/using-opencv-2-4-loading-an-image-in-mfc-sdi-view-or-control">this</a> thread but unfortunately the answer provided doesn't meet my needs because the answers still require you to convert the Mat to an IplImage* before displaying.</p>
  
  <p>Is there any way to do this using cv::Mat only? Any help is much appreciated.</p>
  
  <p><strong>UPDATE:</strong>
  I adapted the above function to using cv::Mat with the help from Kornel's answer. I now do not need to include the CvvImage class:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>void DrawPicToHDC(cv::Mat cvImg, UINT ID, bool bOnPaint)
  {
      // Get the HDC handle information from the ID passed
      CDC *pDC = GetDlgItem(ID)-&gt;GetDC();
      HDC hDCDst = pDC-&gt;GetSafeHdc();
      CRect rect;
      GetDlgItem(ID)-&gt;GetClientRect(&amp;rect);
      cv::Size winSize(rect.right, rect.bottom);
  
      // Resize the source to the size of the destination image if necessary
      cv::Mat cvImgTmp(winSize, CV_8UC3);
      if (cvImg.size() != winSize)
      {
          cv::resize(cvImg, cvImgTmp, winSize);
      }
      else
      {
          cvImgTmp = cvImg;
      }
  
      // Rotate the image
      cv::flip(cvImgTmp,cvImgTmp,0);
  
      // Initialize the BITMAPINFO structure
      BITMAPINFO bitInfo;
      bitInfo.bmiHeader.biBitCount = 24;
      bitInfo.bmiHeader.biWidth = winSize.width;
      bitInfo.bmiHeader.biHeight = winSize.height;
      bitInfo.bmiHeader.biPlanes = 1;
      bitInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
      bitInfo.bmiHeader.biCompression = BI_RGB;
      bitInfo.bmiHeader.biClrImportant = 0;
      bitInfo.bmiHeader.biClrUsed = 0;
      bitInfo.bmiHeader.biSizeImage = 0;
      bitInfo.bmiHeader.biXPelsPerMeter = 0;
      bitInfo.bmiHeader.biYPelsPerMeter = 0;
  
      // Add header and OPENCV image's data to the HDC
      StretchDIBits(hDCDst, 0, 0,
          winSize.width, winSize.height, 0, 0,
          winSize.width, winSize.height,
          cvImgTmp.data, &amp;bitInfo, DIB_RGB_COLORS, SRCCOPY);
  
      ReleaseDC( pDC );
  }
  </code></pre>