显示:将Mat图片居中显示到MFC的picture控件上(通过StretchDIBits)

    xiaoxiao2022-07-04  122

    BOOL CXXXDlg::ShowMat(Mat image) { if (image.empty()) return FALSE; CRect rect; int width, height; BITMAPINFO bitmapInfo; BITMAPINFOHEADER* bmiHeader; width = image.cols; height = image.rows; if (width % 4) width = (width + 3) / 4 * 4; cv::Size winSize(width, height); cv::Mat cvImgTmp(winSize, CV_8UC3); if (image.size() != winSize) cv::resize(image, cvImgTmp, winSize); else cvImgTmp = image.clone(); if (cvImgTmp.channels()==1) cvtColor(cvImgTmp, cvImgTmp, CV_GRAY2BGR); GetDlgItem(IDC_STATIC_SHOW_MODE)->GetClientRect(&rect); bmiHeader = &bitmapInfo.bmiHeader; bmiHeader->biSize = sizeof(BITMAPINFOHEADER); bmiHeader->biWidth = cvImgTmp.cols; bmiHeader->biHeight = -cvImgTmp.rows; bmiHeader->biPlanes = 1; bmiHeader->biBitCount = 24; bmiHeader->biCompression = BI_RGB; bitmapInfo.bmiHeader.biSizeImage = 0; bmiHeader->biXPelsPerMeter = GetSystemMetrics(SM_CXSCREEN); bmiHeader->biYPelsPerMeter = GetSystemMetrics(SM_CYSCREEN); bmiHeader->biClrUsed = 0; bmiHeader->biClrImportant = 0; /*使图片在控件中居中全部显示*/ int nWindowW = rect.Width(); //获取窗口宽度 int nWindowH = rect.Height(); //获取窗口高度 int nImageW = cvImgTmp.cols; //获取图片宽度 int nImageH = cvImgTmp.rows; //获取图片高度 float fRatioW = (float)nWindowW / nImageW; float fRatioH = (float)nWindowH / nImageH; int nBeginW , nBeginH, nWeight, nHeight; if (fRatioW < fRatioH) { nBeginW = 0; nBeginH = (int)(nWindowH - (nImageH*fRatioW)) / 2; nWeight = nWindowW; nHeight = (int)(nImageH * fRatioW); } else { nBeginW = (int)(nWindowW - (nImageW*fRatioH)) / 2; nBeginH = 0; nWeight = (int)(nImageW * fRatioH); nHeight = nWindowH; } GetDlgItem(IDC_STATIC_SHOW_MODE)->GetDC()->FillSolidRect(0, 0, nWindowW, nWindowH, COLORREF(0)); GetDlgItem(IDC_STATIC_SHOW_MODE)->GetDC()->SetStretchBltMode(COLORONCOLOR); StretchDIBits(GetDlgItem(IDC_STATIC_SHOW_MODE)->GetDC()->GetSafeHdc() , nBeginW, nBeginH, nWeight, nHeight , 0, 0, nImageW, nImageH, cvImgTmp.data, &bitmapInfo, DIB_RGB_COLORS, SRCCOPY); return TRUE; }

     

    最新回复(0)