void CXXXDlg::DrawOpenCvMat(Mat& img, UINT nID)
{
Mat imgTmp;
CRect rect;
GetDlgItem(nID)->GetClientRect(&rect);
// 獲取控件大小
int nWidth = rect.Width();
int nHeight = rect.Height();
resize(img, imgTmp, Size(nWidth, nHeight));// 縮放Mat並備份
//resize(img, imgTmp, Size(), 0.5, 0.5, INTER_LINEAR);//0.5:把原圖w h兩個方向縮小一倍
// 轉格式
switch (imgTmp.channels())
{
case 1:
cvtColor(imgTmp, imgTmp, CV_GRAY2BGRA); // GRAY單通道
break;
case 3:
cvtColor(imgTmp, imgTmp, CV_BGR2BGRA); // BGR三通道
break;
default:
break;
}
int pixelBytes = imgTmp.channels()*(imgTmp.depth() + 1); // 計算一個像素多少個字節
// 讀取位圖文件中的頭信息
// [製作bitmapinfo(數據頭)]
BITMAPINFO bitInfo;
bitInfo.bmiHeader.biBitCount = 8 * pixelBytes;
bitInfo.bmiHeader.biWidth = imgTmp.cols;
bitInfo.bmiHeader.biHeight = -imgTmp.rows;//必須爲負,否則圖像是翻轉顯示
bitInfo.bmiHeader.biPlanes = 1;
bitInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);//必須,初始化bitmapinfo.bmiHeader中的第一個參數
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;
// Mat.data + bitmap數據頭 -> MFC
CDC *pDC = GetDlgItem(nID)->GetDC();
//顯示
StretchDIBits(
pDC->GetSafeHdc(),
0, 0, rect.Width(), rect.Height(),
0, 0, rect.Width(), rect.Height(),
imgTmp.data,
&bitInfo,
DIB_RGB_COLORS,
SRCCOPY
);
//StretchDIBits()將DIB中矩形區域內像素使用的顏色數據拷貝到指定的目標矩形中。
//如果目標矩形比源矩形大小要大,那麼函數對顏色數據的行和列進行拉伸,以與目標矩形匹配。
//如果目標矩形大小要比源矩形小,那麼該函數通過使用指定的光柵操作對行列進行壓縮。
ReleaseDC(pDC);
}
在MFC需要顯示圖片的時候調用即可,如在按鈕中調用:
void CXXXDlg::OnBnClickedBtnShow()
{
FindContours* pf = new FindContours(); //自定義處理圖片的類
cv::Mat img;
pf->TestMain(img); //獲得處理後的圖片,保存在img中
//顯示img
DrawOpenCvMat(img, IDC_STATIC_IMG);
}