转自:http://blog.csdn.net/hunnish/article/details/2947595#981474
在WINDOWS下经常要用到在MFC应用窗口中显示IPLIMAGE,因此BMP与IPLIMAGE的相互转换就会经常使用。本文给出两个转换函数,供参考!
/** 从BMP图像文件数据流中生成IPLIMAGE对象
*/
IplImage* GetIplFromBmp(BYTE* pBmp, DWORD size)
{
BYTE* p = pBmp;
BITMAPFILEHEADER fheader;
memcpy(&fheader, p, sizeof(BITMAPFILEHEADER));
BITMAPINFOHEADER bmphdr;
p += sizeof(BITMAPFILEHEADER);
memcpy(&bmphdr, p, sizeof(BITMAPINFOHEADER));
int w = bmphdr.biWidth;
int h = bmphdr.biHeight;
p = pBmp + fheader.bfOffBits;
//reverse(p, w, h);
IplImage* pIpl = cvCreateImage(cvSize(w,h),8,3);
memcpy(pIpl->imageData, p, w * h * 3 *sizeof(char));
return pIpl;
}
/** 从IPLIMAGE对象中生成BMP的图像文件流
*/
bool GetBmpFromIpl(IplImage* pIpl, BYTE* &pBmp, DWORD& size)
{
BITMAPFILEHEADER bfh = {0};
DWORD dwImageSize = 0;
DWORD dwBytesRead = 0;
int w = pIpl->width;
int l = ((w * 24 +31) & ~31) /8;
int h = pIpl->height;
dwImageSize = l * h;
bfh.bfType = (WORD)'M' << 8 | 'B'; //定义文件类
bfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); //定义文件头大小
bfh.bfSize = bfh.bfOffBits + dwImageSize; //文件大小
BITMAPINFOHEADER bih = {0};
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biWidth = pIpl->width;
bih.biHeight = pIpl->height;
bih.biPlanes = 1;
bih.biBitCount = 24;
bih.biCompression = BI_RGB;
bih.biSizeImage = 0;
bih.biXPelsPerMeter = 0;
bih.biYPelsPerMeter = 0;
bih.biClrUsed = 0;
bih.biClrImportant = 0;
size = bfh.bfSize;
pBmp = new BYTE[bfh.bfSize+1];
memset(pBmp, 0, bfh.bfSize + 1);
memcpy(pBmp, &bfh, sizeof(BITMAPFILEHEADER));
memcpy(pBmp+sizeof(BITMAPFILEHEADER), &bih, sizeof(BITMAPINFOHEADER));
BYTE* p = pBmp+sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER);
memcpy(p, (BYTE*)pIpl->imageData, dwImageSize);
return true;
}