cv::Mat类型转为CImage,MFC传入窗口句柄显示CImage图片

来源:互联网 发布:skype6.6mac官方下载 编辑:程序博客网 时间:2024/05/21 09:28
// 实现cv::Mat 结构到 CImage结构的转化
void MatToCImage(cv::Mat& mat, CImage& cImage){int width = mat.cols;int height = mat.rows;int channels = mat.channels();if (width <= 0){return;}if (!cImage.IsNull()){cImage.Destroy();//这一步是防止重复利用造成内存问题}if (!cImage.Create(width, height, 8 * channels)){return;}uchar* ps;uchar* pimg = (uchar*)cImage.GetBits(); //获取CImage的像素存贮区的指针int step = cImage.GetPitch();//每行的字节数,注意这个返回值有正有负// 如果是1个通道的图像(灰度图像) DIB格式才需要对调色板设置  // CImage中内置了调色板,我们要对他进行赋值:if (1 == channels){RGBQUAD* ColorTable;int MaxColors = 256;//这里可以通过CI.GetMaxColorTableEntries()得到大小(如果你是CI.Load读入图像的话)  ColorTable = new RGBQUAD[MaxColors];cImage.GetColorTable(0, MaxColors, ColorTable);//这里是取得指针  for (int i = 0; i<MaxColors; i++){ColorTable[i].rgbBlue = (BYTE)i;//BYTE和uchar一回事,但MFC中都用它  ColorTable[i].rgbGreen = (BYTE)i;ColorTable[i].rgbRed = (BYTE)i;}cImage.SetColorTable(0, MaxColors, ColorTable);delete[]ColorTable;}for (int i = 0; i < height; i++){ps = mat.ptr<uchar>(i);for (int j = 0; j < width; j++){if (1 == channels){*(pimg + i*step + j) = ps[j];//*(pimg + i*step + j) = 105;}else if (3 == channels){*(pimg + i*step + j * 3) = ps[j * 3];*(pimg + i*step + j * 3 + 1) = ps[j * 3 + 1];*(pimg + i*step + j * 3 + 2) = ps[j * 3 + 2];}}}//string str = CString2StdString(_T("C:\\sample1020.bmp"));//imwrite(str,mat);//这句话就是用来测试cimage有没有被赋值//cImage.Save(_T("C:\\sample1024.bmp"));}

//MFC传入窗口句柄显示CImage图片
void ShowPic(HWND hWnd, CImage &img){int width = img.GetWidth();int height = img.GetHeight();CRect wndRect;::GetWindowRect(hWnd, &wndRect);HDC hdc = GetDC(hWnd);HDC hDcImg = img.GetDC();CDC tmpDC;tmpDC.Attach(hDcImg);tmpDC.Detach();SetStretchBltMode(hdc, HALFTONE);::StretchBlt(hdc, 0, 0, wndRect.Width(), wndRect.Height(), hDcImg, 0, 0, width, height, SRCCOPY);img.ReleaseDC();ReleaseDC(hWnd, hdc);}


 
原创粉丝点击