Display a image in a MFC/C++ application using OpenCV

10,667

Solution 1

So I found something to make it work after long researches.

The solution is to create the window and then insert it inside the picture box. I'm not sure it's good practice but I haven't found anything better for now.

cvNamedWindow("IDC_STATIC_OUTPUT", 0); 
cvResizeWindow("IDC_STATIC_OUTPUT", 420, 240);

HWND hWnd = (HWND) cvGetWindowHandle("IDC_STATIC_OUTPUT"); 
HWND hParent = ::GetParent(hWnd); 
     ::SetParent(hWnd, GetDlgItem(IDC_PIC1)->m_hWnd); 
     ::ShowWindow(hParent, SW_HIDE); 

cvShowImage("IDC_STATIC_OUTPUT", frame_copy);

In this case the picture box is called IDC_PIC1 and frame_copy is a OpenCV IplImage.

Hope this helps somebody.

Solution 2

Using the following code you can convert Mat to CImage and then display CImage everywhere you want:

int Mat2CImage(Mat *mat, CImage &img){
  if(!mat || mat->empty())
    return -1;
  int nBPP = mat->channels()*8;
  img.Create(mat->cols, mat->rows, nBPP);
  if(nBPP == 8)
  {
    static RGBQUAD pRGB[256];
    for (int i = 0; i < 256; i++)
        pRGB[i].rgbBlue = pRGB[i].rgbGreen = pRGB[i].rgbRed = i;
    img.SetColorTable(0, 256, pRGB);
  }
  uchar* psrc = mat->data;
  uchar* pdst = (uchar*) img.GetBits();
  int imgPitch = img.GetPitch();
  for(int y = 0; y < mat->rows; y++)
  {
    memcpy(pdst, psrc, mat->cols*mat->channels());//mat->step is incorrect for those images created by roi (sub-images!)
    psrc += mat->step;
    pdst += imgPitch;
  }

  return 0;
}
Share:
10,667
david
Author by

david

Updated on June 25, 2022

Comments

  • david
    david almost 2 years

    I would like to display in a MFC application, frames that I capture from an avi file with OpenCV (cvCaptureFromAVI function).

    I'm new to MFC but feel like I'm close to making it work. But instead of the frames being displayed in the picture box they are displayed in a new window.

    cvGetWindowName returns always a null value.

    There is my code:

    CWnd* hPic = 0;
    hPic = GetDlgItem(IDC_STATICPIC1);  
    const char* szWindName = cvGetWindowName(hPic->GetSafeHwnd());
    cvShowImage(szWindName, frame_copy);