#include"opencv2\opencv.hpp"
#include"opencv2\highgui\highgui.hpp"
HWND hPlayWnd0 = NULL; //句柄
hPlayWnd0 = GetDlgItem(IDC_CAM)->m_hWnd; //初始化的时候进行
void DrawMat(Mat cvImg, HWND hWnd, UINT ID)
{
cv::Mat img;
HWND hShowWnd = ::GetDlgItem(hWnd, ID);
CWnd cWnd;
cWnd.Attach(hShowWnd);
CRect rect;
cWnd.GetClientRect(&rect);
if (rect.Width() % 4 != 0)
{
rect.SetRect(rect.left, rect.top, rect.left + (rect.Width() + 3) / 4 * 4, rect.bottom); //调整图像宽度为4的倍数
}
cv::Rect dst(rect.left, rect.top, rect.right, rect.bottom);
cv::resize(cvImg, img, cv::Size(rect.Width(), rect.Height())); //使图像适应控件大小
unsigned int m_buffer[sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 256];
BITMAPINFO* m_bmi = (BITMAPINFO*)m_buffer;
BITMAPINFOHEADER* m_bmih = &(m_bmi->bmiHeader);
memset(m_bmih, 0, sizeof(*m_bmih));
m_bmih->biSize = sizeof(BITMAPINFOHEADER);
m_bmih->biWidth = img.cols; //必须为4的倍数
m_bmih->biHeight = -img.rows; //在自下而上的位图中 高度为负
m_bmih->biPlanes = 1;
m_bmih->biCompression = BI_RGB;
m_bmih->biBitCount = 8 * img.channels();
if (img.channels() == 1) //当图像为灰度图像时需要设置调色板颜色
{
for (int i = 0; i < 256; i++)
{
m_bmi->bmiColors[i].rgbBlue = i;
m_bmi->bmiColors[i].rgbGreen = i;
m_bmi->bmiColors[i].rgbRed = i;
m_bmi->bmiColors[i].rgbReserved = 0;
}
}
CDC *pDC = cWnd.GetDC();
::StretchDIBits(pDC->GetSafeHdc(), 0, 0, rect.Width(), rect.Height(), 0, 0, rect.Width(), rect.Height(), img.data, (BITMAPINFO*)m_bmi, DIB_RGB_COLORS, SRCCOPY);
cWnd.ReleaseDC(pDC);
cWnd.Detach();
}