IplImage和Bitmap都是内存图形的表示方法,前者是OpenCV开源视觉库的,后者是GDI+的。如果在VC中使用OpenCV库的话,很可能会用到这两者的转换。
在网上搜索这两种格式转换的话,很有可能会搜索到有内存泄露的版本(比如 http://blog.csdn.net/jtujtujtu/article/details/3734722),因此在此提供了没有内存泄露的版本供大家参考。
【注意】使用GDI+的FromBITMAPINFO函数会导致内存泄露!
IplImage* Bitmap2IplImage(Bitmap* pBitmap) { if (!pBitmap) return NULL; int w = pBitmap->GetWidth(); int h = pBitmap->GetHeight(); BitmapData bmpData; Rect rect(0,0,w,h); pBitmap->LockBits(&rect, ImageLockModeRead, PixelFormat24bppRGB, &bmpData); BYTE* temp = (bmpData.Stride>0) ? ((BYTE*)bmpData.Scan0) : ((BYTE*)bmpData.Scan0 + bmpData.Stride*(h-1)); IplImage* pIplImg = cvCreateImage(cvSize(w, h), IPL_DEPTH_8U, 3); if (!pIplImg) { pBitmap->UnlockBits(&bmpData); return NULL; } memcpy(pIplImg->imageData, temp, abs(bmpData.Stride)*bmpData.Height); pBitmap->UnlockBits(&bmpData); //判断Top-Down or Bottom-Up if (bmpData.Stride<0) cvFlip(pIplImg, pIplImg); return pIplImg; }
// pBitmap 同样需要外部释放 Bitmap* IplImage2Bitmap(IplImage* pIplImg) { if(!pIplImg) return NULL; Bitmap *pBitmap = new Bitmap(pIplImg->width, pIplImg->height, PixelFormat24bppRGB); if (!pBitmap) return NULL; BitmapData bmpData; Rect rect(0, 0, pIplImg->width, pIplImg->height); pBitmap->LockBits(&rect, ImageLockModeWrite, PixelFormat24bppRGB, &bmpData); BYTE *pByte = (BYTE*)bmpData.Scan0; if (pIplImg->widthStep == bmpData.Stride) //likely memcpy(bmpData.Scan0, pIplImg->imageDataOrigin, pIplImg->imageSize); pBitmap->UnlockBits(&bmpData); return pBitmap; }