mfc +opencv 读取图片显示到对话框
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()); } }