How can I show a OpenCV image in a dialog of MFC.

asked 2016-07-17 20:43:35 -0500

The type of cv image is cv::mat. And there is a PictureControl in dialog, or any other control, (just for show image). There picture is a BMP file (512 *1024). I load it by "Mat img=imread("path")" , then do some processing by Opencv. And I want a good method to show it, it should not spend a lot of time (Should be less than 1ms). I have tried some methods as follows.

Method 1:

IplImage simg = src;
cvNamedWindow("IDC_STATIC_OUTPUT", 0);
cvResizeWindow("IDC_STATIC_OUTPUT", rect.Width, rect.Height);
HWND hWnd = (HWND)cvGetWindowHandle("IDC_STATIC_OUTPUT");
HWND hParent = ::GetParent(hWnd);
::SetParent(hWnd, GetDlgItem(IDC_PictureBox)->m_hWnd);
::ShowWindow(hParent, SW_HIDE);
cvShowImage("IDC_STATIC_OUTPUT", &simg);

Problem of this method: There is a flashing window out of dialog, and the running speed is slow.

Method 2: Use a function,

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;


Problem: The speed of update is slow (Perhaps I used it in a wrong way).And running speed also slow (maybe because piex by piex).

Method 3: Also a function. link text

Problem: I can not use that function normally.Cannot display pictures.

edit retag flag offensive close merge delete



Check the forum, there are several topics about MFC and OpenCV.

Anyway, if you want to copy the Mat data to a MFC bitmap, I suggest to do it in a separate thread, so it can run in parallel with the processing code.

For a very-very fast display I suggest to go OpenGL. It's easy to create an OpenGL bitmap in OpenCV, then check other forums for OpenGL-MFC interaction.

kbarni gravatar imagekbarni ( 2016-07-18 08:05:12 -0500 )edit

@kbarni thanks for your reply,I will check the forum for this quesition.

Dean Feng gravatar imageDean Feng ( 2016-07-18 19:40:25 -0500 )edit

in this blog i will show you how to show a OpenCV image in a dialog of MFC..and in chinese.

jsxyhelu gravatar imagejsxyhelu ( 2018-10-06 08:41:14 -0500 )edit