OpenCV+MFC快速应用:如何在MFC中显示Mat图像

来源:互联网 发布:软件提速精灵 编辑:程序博客网 时间:2024/06/06 02:15

在OpenCV的较早版本中使用IplImage以及CvvImage类(1.0版本),新版本中凸显C++语法(当然也保留了对于旧版本的支持,如经典的C语法)

使用MFC可以进行快速开发,而OpenCV则提供了强大的数据处理算法支持,二者强强联合,使得开发过程更加高效。

关于如何显示IplImage,请参见这两篇文章:

在MFC的View窗口中显示IplImage之一

在MFC的View窗口中显示IplImage之二


现在,OpenCV新版本更多地使用Mat而不是IplImage(你也可以进行Mat<-->IplImage的转换,但不建议这样做)

于是对应的,在MFC的View窗口中显示Mat方法产生了

void  DrawToHDC(Mat mat, HDC hDC, RECT rect){CImage img; //ATL::CImageint w = mat.cols;  //宽int h = mat.rows;  //高int chinnels = mat.channels();img.Create(w, h, chinnels << 3);RGBQUAD* pColorTable = NULL;int nMaxColors = 256;pColorTable = new RGBQUAD[nMaxColors];img.GetColorTable(0, nMaxColors, pColorTable);for (int i = 0; i < nMaxColors; i++){pColorTable->rgbBlue = (BYTE)i;pColorTable->rgbGreen = (BYTE)i;pColorTable->rgbRed = (BYTE)i;}img.SetColorTable(0, nMaxColors, pColorTable);delete[] pColorTable;int i, j, k;BYTE *pSource = NULL;BYTE *pImgData = (BYTE *)img.GetBits();int step = img.GetPitch();if (chinnels == 1){for (i = 0; i < h; ++i){pSource = mat.ptr<BYTE>(i);for (j = 0; j < w; ++j){*(pImgData + i*step + j) = pSource[j];}}}else if (chinnels == 3){for (i = 0; i < h; ++i){pSource = mat.ptr<BYTE>(i);for (j = 0; j < w; ++j){for (k = 0; k < 3; ++k){*(pImgData + i*step + j * 3 + k) = pSource[j * 3 + k];}}}}else{AfxMessageBox(TEXT("仅支持灰度图/3通道彩色图"));return;}SetStretchBltMode(hDC, COLORONCOLOR);img.StretchBlt(hDC, rect, SRCCOPY);img.Destroy();}

使用示例

// OnPaint/OnDrawCClientDC dc(this);Mat mat = imread(strFileName, CV_LOAD_IMAGE_UNCHANGED);RECT rect;GetClientRect(&rect);DrawToHDC(mat, dc.m_hDC, rect);//部分代码已省略

点此领取楼主



0 0
原创粉丝点击