// CCameraCtrl::DoPropExchange - 持久性支持 void CCameraCtrl::DrawMatToWin(cv::Mat &mat, CDC *pDC, CRect rect) { if (mat.empty()) { return; } //如果图像的大小大于屏幕区域的大小,则把图像缩放到控件的大小 if (mat.cols>(rect.right - rect.left) || mat.rows>(rect.bottom - rect.top)) { resize(mat, mat, Size(rect.right - rect.left, rect.bottom - rect.top)); } rect.right = rect.left + mat.size().width; rect.bottom = rect.top + mat.size().height; int width = mat.cols; int height = mat.rows; int channels = mat.channels(); CImage CI; CI.Destroy(); /*clear*/ CI.Create(width, height, /*positive: left-bottom-up or negative: left-top-down*/ 8 * channels); /*numbers of bits per pixel*/ //copy values 复制Mat数据 uchar* ps; uchar* pimg = (uchar*)CI.GetBits(); //A pointer to the bitmap buffer //The pitch is the distance, in bytes. represent the beginning of // one bitmap line and the beginning of the next bitmap line int step = CI.GetPitch(); if (mat.channels() == 1) { RGBQUAD* pColorTable = NULL; int nMaxColors = CI.GetMaxColorTableEntries(); pColorTable = new RGBQUAD[nMaxColors]; CI.GetColorTable(0, nMaxColors, pColorTable); for (int i = 0; i < nMaxColors; i++) { pColorTable[i].rgbBlue = (BYTE)i; pColorTable[i].rgbGreen = (BYTE)i; pColorTable[i].rgbRed = (BYTE)i; } CI.SetColorTable(0, nMaxColors, pColorTable); delete[] pColorTable; } if (mat.channels() == 1 || mat.channels() == 3) { for (int i = 0; i < height; ++i) { ps = (mat.ptr<uchar>(i)); for (int j = 0; j < width; ++j) { if (channels == 1) //gray { *(pimg + i*step + j) = ps[j]; } else if (channels == 3) //color { for (int k = 0; k < 3; ++k) { *(pimg + i*step + j * 3 + k) = ps[j * 3 + k]; } } } } /*设置伸缩模式,否则会出现图像的失真*/ } else { MessageBox(_T("只能处理灰度图或者三通道图片")); ReleaseDC(pDC); return; } SetStretchBltMode(pDC->m_hDC, STRETCH_DELETESCANS | COLORONCOLOR); CI.StretchBlt(pDC->m_hDC, rect, SRCCOPY); /*释放资源*/ ReleaseDC(pDC); } // CCameraCtrl::OnDraw - 绘图函数 void CCameraCtrl::OnDraw( CDC* pdc, const CRect& rcBounds, const CRect& /* rcInvalid */) { if (!pdc) return; // TODO: 用您自己的绘图代码替换下面的代码。 /*pdc->FillRect(rcBounds, CBrush::FromHandle((HBRUSH)GetStockObject(WHITE_BRUSH))); pdc->Ellipse(rcBounds);*/ //m_dlg.MoveWindow(rcBounds, 1); Mat srcImage = imread("D:\\face1.bmp", 2 | 4); DrawMatToWin(srcImage, pdc, rcBounds); }
#include "atlimage.h" using namespace ATL;