将opencv中的Mat居中显示到MFC的picture控件上

将图像类型由Mat转换为CImage后,使图片适应居中显示

void CXXX::ShowImage(Mat mImage)
{
	CRect rect;//定义矩形类  
	CWnd *pWnd= GetDlgItem(IDC_STATIC_CAM_SHOW);			//获取控件句柄  
	pWnd->GetClientRect(&rect);								//获取句柄指向控件区域的大小  
	CDC *pDc = pWnd->GetDC();								//获取picture的DC  
	int nWindowW = rect.Width();							//获取窗口宽度 
	int nWindowH = rect.Height();							//获取窗口高度  
	int nImageW = mImage.cols;								//获取图片宽度  
	int nImageH = mImage.rows;								//获取图片高度
	/*使图片在控件中居中全部显示*/
	float ratioW = (float)nWindowW / nImageW;
	float ratioH = (float)nWindowH / nImageH;
	CImage ImageCam;
	MatToCImage(mImage, ImageCam);
	pDc->SetStretchBltMode(COLORONCOLOR);
	if (ratioW < ratioH)
		ImageCam.Draw(pDc->m_hDC, 0, (int)(nWindowH - nImageH * ratioW)/2, nWindowW, (int)(nImageH * ratioW), 0, 0, nImageW, nImageH);
	else
		ImageCam.Draw(pDc->m_hDC, (int)(nWindowW - nImageW * ratioH) / 2, 0, (int)(nImageW* ratioH), nWindowH, 0, 0, nImageW, nImageH);
	ReleaseDC(pDc);
}
	
void CXXX::MatToCImage(Mat& mat, CImage& cimage)
{
	if (0 == mat.total())
	{
		return;
	}
	int nChannels = mat.channels();
	if ((1 != nChannels) && (3 != nChannels))
	{
		return;
	}
	int nWidth = mat.cols;
	int nHeight = mat.rows;
	//重建cimage
	cimage.Destroy();
	cimage.Create(nWidth, nHeight, 8 * nChannels);
	//拷贝数据
	uchar* pucRow;									//指向数据区的行指针
	uchar* pucImage = (uchar*)cimage.GetBits();		//指向数据区的指针
	int nStep = cimage.GetPitch();					//每行的字节数,注意这个返回值有正有负
	if (1 == nChannels)								//对于单通道的图像需要初始化调色板
	{
		RGBQUAD* rgbquadColorTable;
		int nMaxColors = 256;
		rgbquadColorTable = new RGBQUAD[nMaxColors];
		cimage.GetColorTable(0, nMaxColors, rgbquadColorTable);
		for (int nColor = 0; nColor < nMaxColors; nColor++)
		{
			rgbquadColorTable[nColor].rgbBlue = (uchar)nColor;
			rgbquadColorTable[nColor].rgbGreen = (uchar)nColor;
			rgbquadColorTable[nColor].rgbRed = (uchar)nColor;
		}
		cimage.SetColorTable(0, nMaxColors, rgbquadColorTable);
		delete[]rgbquadColorTable;
	}
	for (int nRow = 0; nRow < nHeight; nRow++)
	{
		pucRow = (mat.ptr(nRow));
		for (int nCol = 0; nCol < nWidth; nCol++)
		{
			if (1 == nChannels)
			{
				*(pucImage + nRow * nStep + nCol) = pucRow[nCol];
			}
			else if (3 == nChannels)
			{
				for (int nCha = 0; nCha < 3; nCha++)
				{
					*(pucImage + nRow * nStep + nCol * 3 + nCha) = pucRow[nCol * 3 + nCha];
				}
			}
		}
	}
}	
	

 

你可能感兴趣的:(学习MFC)