【转】OpenCV中IplImage 与 Gdiplus 中Bitmap之间的相互转换

// pIplImage 需要外部释放 Mosesyuan
 void CGeneral::BitmapToIplImage(Bitmap* pBitmap, IplImage* &pIplImg)
{
    if (!pBitmap)
    {
        return;
    }
    if(pIplImg)
    {
        cvReleaseImage(&pIplImg);
        pIplImg = NULL;
    }
    BitmapData bmpData;
    Rect rect(0,0,pBitmap->GetWidth(),pBitmap->GetHeight());
    pBitmap->LockBits(&rect, ImageLockModeRead, PixelFormat24bppRGB, &bmpData);
    IplImage* tempImg = cvCreateImage(cvSize(pBitmap->GetWidth(), pBitmap->GetHeight()), IPL_DEPTH_8U, 3);
    BYTE* temp = (bmpData.Stride>0)?((BYTE*)bmpData.Scan0):((BYTE*)bmpData.Scan0+bmpData.Stride*(bmpData.Height-1));
    memcpy(tempImg->imageData, temp, abs(bmpData.Stride)*bmpData.Height);
    pBitmap->UnlockBits(&bmpData);
    pIplImg = tempImg;
//判断Top-Down or Bottom-Up

    if (bmpData.Stride<0)       

        cvFlip(pIplImg, pIplImg);            
}
OpenCV中 IplImage 转 Gdiplus::Bitmap

// pBitmap 同样需要外部释放!!

void CGeneral::IplImageToBitmap(IplImage* pIplImg, Bitmap* &pBitmap)
{
    if(!pIplImg)
        return;       

    BITMAPINFOHEADER bmih;
    memset(&bmih, 0, sizeof(BITMAPINFOHEADER));
    bmih.biSize = sizeof(BITMAPINFOHEADER);
    bmih.biWidth = pIplImg->width;
    bmih.biHeight = pIplImg->height;
    bmih.biPlanes = 1;
    bmih.biBitCount = pIplImg->depth*pIplImg->nChannels;
    bmih.biSizeImage = pIplImg->imageSize;

    BYTE* pData=new BYTE[bmih.biSizeImage];
    memcpy(pData, pIplImg->imageDataOrigin, pIplImg->imageSize);

    if (pBitmap)
    {
        delete pBitmap;
        pBitmap = NULL;
    }
    pBitmap = Gdiplus::Bitmap::FromBITMAPINFO((BITMAPINFO*)&bmih, pData);

}
 

你可能感兴趣的:(UP)