通用图像转为IplImage格式

FreeImage图像库是一个开源图像库,能够帮助我们快速实现图像的读取与转换操作,由于大部分做图像处理的人接触的比较多的还是OpenCV,这里给出一个通用的图像格式转为IplImage格式的代码实现。

#include "cv.h" #include "FreeImage.h" //通用图像加载函数,支持的图像有bmp,jpg,tif,png,gif,psd,pgm等等 FIBITMAP* GenericLoader(const char* filename,int flag=0) { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; fif = FreeImage_GetFileType(filename,0);//获取文件的类型标签 if(fif == FIF_UNKNOWN)//如果文件没有类型标签 { fif = FreeImage_GetFIFFromFilename(filename);//从文件名的后缀猜测文件类型 } //文件被该库支持 if(fif != FIF_UNKNOWN && FreeImage_FIFSupportsReading(fif)) { FIBITMAP* dib = FreeImage_Load(fif,filename,flag); return dib; } return NULL; } IplImage* pic2ipl(const char* filename) { FreeImage_Initialise(); FIBITMAP* dib = GenericLoader(filename); if(!dib) return NULL; int nClrUsed = FreeImage_GetColorsUsed(dib); int nBpp = FreeImage_GetBPP(dib); int height = FreeImage_GetHeight(dib); int width = FreeImage_GetWidth(dib); RGBQUAD* pPalette = FreeImage_GetPalette(dib); int nChannel=3; if(!nClrUsed && !pPalette) //无调色板图像处理 { IplImage* iplImg = cvCreateImage(cvSize(width,height),IPL_DEPTH_8U,nChannel); iplImg->origin = 1; for(int y=0;y<height;y++) { BYTE* pLine = (BYTE*)iplImg->imageData + y*iplImg->widthStep; BYTE* psrcLine = (BYTE*)FreeImage_GetScanLine(dib,y); for (int x=0;x<nChannel*width;x++) { *pLine++ = *psrcLine++; } } FreeImage_Unload(dib); FreeImage_DeInitialise(); return iplImg; } else if(pPalette)//索引图像处理 { IplImage* iplImg = cvCreateImage(cvSize(width,height),IPL_DEPTH_8U,nChannel); iplImg->origin = 1; BYTE intensity; BYTE* pIntensity = &intensity; for(int y=0;y<height;y++) { BYTE* pLine = (BYTE*)iplImg->imageData + y*iplImg->widthStep; for (int x=0;x<width;x++) { FreeImage_GetPixelIndex(dib,x,y,pIntensity); pLine[x*3] = pPalette[intensity].rgbBlue; pLine[x*3+1] = pPalette[intensity].rgbGreen; pLine[x*3+2] = pPalette[intensity].rgbRed; } } FreeImage_Unload(dib); FreeImage_DeInitialise(); return iplImg; } else { FreeImage_Unload(dib); FreeImage_DeInitialise(); return NULL; } }

 

输入文件名,通过FreeImage库参考中给出的例子函数GenericLoader可将各种格式的图像转为FIBITMAP格式,再利用pic2ipl函数

将中间格式FIBITMAP转为IplImage格式。

 

函数原型为:

IplImage* pic2ipl(const char* filename);

一旦使用完毕,需用cvReleaseImage释放资源。

 

你可能感兴趣的:(image,null,byte,图像处理)