网上有将gif转为iplimg的版本,只是用惯了C++的接口,所以就写了个转Mat的版本,代码比较简单
一、读文件
1 int MatFun::gif2Mat(char* data, size_t dataSize, vector<Mat>& gifImgs, Mat& singleImg) 2 { 3 /* initialise 4 ->open memory 5 ->getImageType 6 ->load bitmaps 7 ->bitmaps to Mat 8 ->free all resource 9 */ 10 // condition1: data is not null 11 if (NULL == data || dataSize == 0) 12 return -1; 13 FreeImage_Initialise(); 14 FIMEMORY* memory = FreeImage_OpenMemory((BYTE*)data, dataSize); 15 if (NULL==memory) 16 { 17 FreeImage_DeInitialise(); //condition 2: memory is not null 18 } 19 20 FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(memory); 21 if (FIF_UNKNOWN == fif) //condition 3: type of image should be know 22 { 23 fprintf(stderr, "unknown type of image"); 24 if (NULL != memory) FreeImage_CloseMemory(memory); 25 FreeImage_DeInitialise(); 26 return -1; 27 } 28 else if (FIF_GIF != fif) //condition 4: type of image should be GIF 29 { 30 if (NULL != memory) FreeImage_CloseMemory(memory); 31 FreeImage_DeInitialise(); 32 return 0; 33 } 34 35 FIMULTIBITMAP * fiBmp = FreeImage_LoadMultiBitmapFromMemory(fif, memory, GIF_DEFAULT); 36 if (NULL==fiBmp) 37 { 38 if (NULL != memory) FreeImage_CloseMemory(memory); //condition 5: bitmaps is not null 39 FreeImage_DeInitialise(); 40 return -1; 41 } 42 43 int num = FreeImage_GetPageCount(fiBmp); 44 45 for (int i = 0; i < num; i++) 46 { 47 if (i==0 || i==2) 48 { 49 FIBITMAP *mfibmp = FreeImage_LockPage(fiBmp, i); 50 if (mfibmp) 51 { 52 Mat dst = bitMap2Mat(mfibmp, fif); 53 FreeImage_UnlockPage(fiBmp, mfibmp, false); 54 if (dst.empty()) 55 { 56 if (NULL != memory) FreeImage_CloseMemory(memory); 57 if (NULL != fiBmp) FreeImage_CloseMultiBitmap(fiBmp, GIF_DEFAULT); 58 FreeImage_DeInitialise(); 59 return -1; 60 } 61 gifImgs.push_back(dst); 62 dst.release(); 63 } 64 } 65 } 66 67 if (NULL != memory) 68 FreeImage_CloseMemory(memory); 69 if (NULL != fiBmp) 70 FreeImage_CloseMultiBitmap(fiBmp); 71 FreeImage_DeInitialise(); 72 73 return 0; 74 }
这部分其实功能很简单,代码里面大部分都是检查,实际执行就初始化、打开内存、内存中读bitmap这几步。
二、gif转Mat
Mat MatFun::bitMap2Mat(FIBITMAP* fiBmp, const FREE_IMAGE_FORMAT &fif) { if (NULL == fiBmp || FIF_GIF != fif) return Mat(); int width = FreeImage_GetWidth(fiBmp); int height = FreeImage_GetHeight(fiBmp); BYTE intensity; BYTE* pIntensity = &intensity; if(FreeImage_GetBPP(fiBmp) !=8) fiBmp = FreeImage_ConvertTo8Bits(fiBmp); //必须转化为8bit RGBQUAD* pixels = new RGBQUAD; pixels = FreeImage_GetPalette(fiBmp); Mat img=Mat::zeros(height, width, CV_8UC3); uchar* p; for (int i = 0; i < height; i++) { p = img.ptr<uchar>(i); for (int j = 0; j < width; j++) { FreeImage_GetPixelIndex(fiBmp, j, i, pIntensity); p[3 * j] = pixels[intensity].rgbBlue; p[3 * j + 1] = pixels[intensity].rgbGreen; p[3 * j + 2] = pixels[intensity].rgbRed; } } return img; }
具体的将byte像素转化为mat里面的像素值即可,注意rgb图像的Mat里是一个像素包含三通道的值,知道这点,代码就很好理解了。
利用FreeImage将gif图像转为opencv中的Mat,布布扣,bubuko.com
时间: 2024-10-24 02:57:14