int ShowMat(cv::Mat img, HWND hWndDisplay)
{
if (img.channels() < 3)
{
return -1;
}
//構造將要顯示的Mat版本圖片
RECT rect;
::GetClientRect(hWndDisplay, &rect);
cv::Mat imgShow(abs(rect.top - rect.bottom), abs(rect.right - rect.left), CV_8UC3);
resize(img, imgShow, imgShow.size());
//在控件上顯示要用到的CImage類圖片
ATL::CImage CI;
int w = imgShow.cols;//寬
int h = imgShow.rows;//高
int channels = imgShow.channels();//通道數
CI.Create(w, h, 8 * channels);
//CI像素的復制
uchar* pS;
uchar* pImg = (uchar*)CI.GetBits();//得到CImage數據區地址
int step = CI.GetPitch();
for (int i = 0;i < h;i++)
{
pS = imgShow.ptr<uchar>(i);
for (int j = 0;j < w;j++)
{
for (int k = 0;k < 3;k++)
*(pImg + i * step + j * 3 + k) = pS[j * 3 + k];
//注意到這里的step不用乘以3
}
}
//在控件顯示圖片
HDC dc;
dc = ::GetDC(hWndDisplay);
CI.Draw(dc, 0, 0);
::ReleaseDC(hWndDisplay, dc);
CI.Destroy();
return 0;
}
void CmfcimageDlg::OnBnClickedOpenimg()
{
// TODO: 在此添加控件通知處理程序代碼
CString FilePath;
CFileDialog FileDlg(TRUE);
if (IDOK == FileDlg.DoModal())
{
//獲取FileOpen對話框返回的路徑名
FilePath = FileDlg.GetPathName();
//GetPathName返回的是CString類型,要經過轉換為string類型才能使用imread打開圖片
std::string pathName(CW2A(FilePath.GetString()));
//std::string pathName(FilePath.GetBuffer());
//讀取圖片
cv::Mat orgImg = cv::imread(pathName);
//顯示圖片
ShowMat(orgImg, GetDlgItem(IDC_PIC_SHOW)->GetSafeHwnd());
}
}