如何转换cv::Mat到MFC CBitmap



如何将OpenCV图像转换为Microsoft Foundation Classes (MFC) CBitmap对象?

我尝试了以下操作,但失败了,

    cv::Mat tmp;
    (Load opencv image ...)
    cv::Size size = tmp.size();
    CBitmap bitmap;
    // 3 colors (RGB), 24bits (8bits*3channels) 
    if (!bitmap.CreateBitmap(128, 128, 1, 24, (void *)tmp.data)) {
        TRACE0("Failed to create bitmap for image displayn");
        return;
    }

这篇文章分享了将IplImage转换为CBitmap的方法:

CBitmap* IplImageToCBitmap(IplImage* img) 
{
    CDC dc;
    CDC memDC;
    if (!dc.CreateDC("DISPLAY", NULL, NULL, NULL))
        return NULL;
    if (!memDC.CreateCompatibleDC(&dc))
        return NULL;
    CBitmap* bmp = new CBitmap();
    CBitmap* pOldBitmap;
    bmp->CreateCompatibleBitmap(&dc, img->width, img->height);
    pOldBitmap = memDC.SelectObject(bmp);
    CvvImage cvImage; // you will need OpenCV_2.2.0- to use CvvImage 
    cvImage.CopyOf(img);
    cvImage.Show(memDC.m_hDC, 0, 0, img->width, img->height, 0, 0);
    cvImage.Destroy();
    memDC.SelectObject(pOldBitmap);
    memDC.DeleteDC();
    dc.DeleteDC();
    return bmp;
}
基于此,您可以通过如下方式调用它来实现您的目标:
cv::Mat aMat;
CBitmap *aCBitmap = IplImageToCBitmap((IplImage*) &aMat);

第一个将Mat转换为CImage,然后附加到CBitmap

void Mat2CImage(Mat *mat, CImage &img) {
    if (!mat || mat->empty())
        MessageBox(L"Error convert Mat to CImage", L"error", MB_OK);
    int nBPP = mat->channels() * 8;
    img.Create(mat->cols, mat->rows, nBPP);
    if (nBPP == 8)
    {
        static RGBQUAD pRGB[256];
        for (int i = 0; i < 256; i++)
            pRGB[i].rgbBlue = pRGB[i].rgbGreen = pRGB[i].rgbRed = i;
        img.SetColorTable(0, 256, pRGB);
    }
    uchar* psrc = mat->data;
    uchar* pdst = (uchar*)img.GetBits();
    int imgPitch = img.GetPitch();
    for (int y = 0; y < mat->rows; y++)
    {
        memcpy(pdst, psrc, mat->cols*mat->channels());//mat->step is incorrect for those images created by roi (sub-images!)
        psrc += mat->step;
        pdst += imgPitch;
    }
    return;
} 

///////使用

Mat mat_img;
CImage image;
Mat2CImage(&mat_img,image)
CBitmap bitmap;
bitmap.Attach(image.Detach());

//——使用位图//完成后

bitmap.Detach();

相关内容

  • 没有找到相关文章

最新更新