从缓存中读取图像

参考blog:

http://blog.csdn.net/summersolstice/article/details/5134811

 

#include <cv.h>
#include <highgui.h>
#include <cstdio>
#include <cstdlib>
#include <sys/types.h>
#include <sys/stat.h>
#include <FreeImage.h>

IplImage* FIBITMAP2IplImage(FIBITMAP *dib)
{
	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;
	}

}

int main(int argc, char *argv[])
{
	FreeImage_Initialise();
	FREE_IMAGE_FORMAT format = FIF_UNKNOWN;
	FIBITMAP *bitmap = NULL;
	struct _stat file_stat;
	int length;
	length = _stat("c:\\lena.ppm", &file_stat);
	BYTE * bytes = (BYTE*)malloc(file_stat.st_size * sizeof(BYTE));
	FILE * handle = fopen("c:\\lena.ppm", "rb" );
	if(handle){
		fread( bytes, sizeof(BYTE),file_stat.st_size, handle );
		fclose(handle);

		FIMEMORY * memory = FreeImage_OpenMemory( bytes, file_stat.st_size );

		if ( !memory ) {
			return 1;
		}

		format = FreeImage_GetFileTypeFromMemory( memory, 0 );
		bitmap = FreeImage_LoadFromMemory( format, memory, 0 );

	}
	IplImage *pImg = FIBITMAP2IplImage(bitmap);
	cvNamedWindow("Test");
	cvShowImage("Test",pImg);
	cvWaitKey(0);
	FreeImage_DeInitialise();
	return 0;
}


 

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