1. 程式人生 > >opencv 開啟gif圖片

opencv 開啟gif圖片

我直接來全套把,不然很多新手不知道怎麼弄

1、首先下載FreeImage3160Win32.zip版本有可能不同,連結賞給你:下載地址點選開啟連結

2、開啟找到FreeImage.dll FreeImage.lib, FreeImage.h拷貝到專案中去。

3、開始使用在cpp中匯入靜態庫

#include "FreeImage.h"  
#pragma comment(lib,"FreeImage.lib")

下面的轉化程式碼我就拷貝一個他人的了,嘻嘻。節約時間

IplImage*  gif2ipl(const char* filename)
{
	FreeImage_Initialise();         //load the FreeImage function lib  
	FREE_IMAGE_FORMAT fif = FIF_GIF;
	FIBITMAP* fiBmp = FreeImage_Load(fif, filename, GIF_DEFAULT);
	FIMULTIBITMAP * pGIF = FreeImage_OpenMultiBitmap(fif, filename, 0, 1, 0, GIF_PLAYBACK);
	//  FIBITMAPINFO fiBmpInfo = getfiBmpInfo(fiBmp);  
	int gifImgCnt = FreeImage_GetPageCount(pGIF);
	FIBITMAP * pFrame;
	int width, height;
	width = FreeImage_GetWidth(fiBmp);
	height = FreeImage_GetHeight(fiBmp);
	IplImage * iplImg = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
	iplImg->origin = 1;//should set to 1-top-left structure(Windows bitmap style)  
	RGBQUAD* ptrPalette = new RGBQUAD; // = FreeImage_GetPalette(fiBmp);  
	BYTE intens;
	BYTE* pIntensity = &intens;
	cvNamedWindow("gif", 0);
	printf("gifImgCnt %d \n", gifImgCnt);
	for (int curFrame = 0; curFrame < gifImgCnt; curFrame++)
	{
		pFrame = FreeImage_LockPage(pGIF, curFrame);
		//ptrPalette = FreeImage_GetPalette(pFrame);  
		char * ptrImgDataPerLine;
		for (int i = 0; i < height; i++)
		{
			ptrImgDataPerLine = iplImg->imageData + i*iplImg->widthStep;
			for (int j = 0; j < width; j++)
			{
				//get the pixel index   
				//FreeImage_GetPixelIndex(pFrame,j,i,pIntensity);    
				FreeImage_GetPixelColor(pFrame, j, i, ptrPalette);
				ptrImgDataPerLine[3 * j] = ptrPalette->rgbBlue;
				ptrImgDataPerLine[3 * j + 1] = ptrPalette->rgbGreen;
				ptrImgDataPerLine[3 * j + 2] = ptrPalette->rgbRed;
				//ptrImgDataPerLine[3*j] = ptrPalette[intens].rgbBlue;  
				//ptrImgDataPerLine[3*j+1] = ptrPalette[intens].rgbGreen;  
				//ptrImgDataPerLine[3*j+2] = ptrPalette[intens].rgbRed;  
			}
		}

		printf("convert curFrame end %d \n", curFrame);
		cvShowImage("gif", iplImg);
		cvWaitKey(30);
		FreeImage_UnlockPage(pGIF, pFrame, 1);
	}
	FreeImage_Unload(fiBmp);
	FreeImage_DeInitialise();
	return iplImg;
}
接下來就是我們的呼叫了
IplImage *pImage = cvLoadImage("Verifycode.gif", CV_LOAD_IMAGE_UNCHANGED);
	if (pImage==NULL)
	{
		const char * ch = "Verifycode.gif";
		pImage = gif2ipl("Verifycode.gif");
	}

解釋一下上面的程式碼,我是從網路中下載來的圖,有可能是其他格式,如果打不開,說明是gif。

看來以後不能亂用他人的程式碼,得先自己寫一寫。這個程式碼有問題,記憶體沒有釋放完畢。也就是說你打開了一張圖,他會一直佔用哈哈 20141226

return前面加一條FreeImage_CloseMultiBitmap(pGIF, GIF_DEFAULT);

請注意了!