此文章為了記錄我在使用libtiff庫中的一些問題而寫,將不斷補充。
libtiff庫是讀取和寫入tiff文件最主要的一個開源庫,但文檔寫的實在不敢恭維。相對資料也是異常稀少。
libtiff庫的安裝
libtiff庫的最新的最新版本可以從http://www.libtiff.org/下載,即可以編譯源碼也可以采用預先編譯好的二進制文件。
本人推薦使用預編譯版本,自己編譯容易缺少依賴庫,同時也可能出現一些莫名其妙的問題。
tiff文件的讀寫函數:
1 //獲取strip大小 2 tsize_t TIFFStripSize(TIFF *tif); 3 //讀取strip數據,buf緩沖區可由TIFFStripSize計算,size取-1代表讀取整個strip 7 tsize_t TIFFReadEncodedStrip(TIFF *tif, tstrip_t strip, tdata_t buf, tsize_t size);
將多色tiff文件分割
1 uint32 imageWidth, imageLength, TileWidth, TileLength, imageRowsPerStrip ; 2 uint16 imageCompression, imageSamplePerPixel ; 3 uint16 imagePlanarConfig, imagePhotoMetric, ResolutUnit, Orientation ; 4 uint16 bps ; 5 float X_Resolut, Y_Resolut ; 6 7 TIFF *tif_r, *tif_w ; 8 unsigned char *buf; 9 tstrip_t strip ; 10 11 tif_r = TIFFOpen("image_4plane.tif", "r"); 12 if (!tif_r) 13 { 14 error_handler("Open Tiff File Error!"); 15 return -1; 16 } 17 /* 讀取 TIFF 標籤 */ 18 TIFFGetField(tif_r, TIFFTAG_IMAGEWIDTH, &imageWidth); 19 TIFFGetField(tif_r, TIFFTAG_IMAGELENGTH, &imageLength); 20 21 TIFFGetField(tif_r, TIFFTAG_BITSPERSAMPLE, &bps); 22 TIFFGetField(tif_r, TIFFTAG_COMPRESSION, &imageCompression); 23 TIFFGetField(tif_r, TIFFTAG_PHOTOMETRIC, &imagePhotoMetric); 24 25 TIFFGetField(tif_r, TIFFTAG_SAMPLESPERPIXEL, &imageSamplePerPixel); 26 TIFFGetField(tif_r, TIFFTAG_ROWSPERSTRIP, &imageRowsPerStrip); 27 if (imageRowsPerStrip != 1) 28 { 29 error_handler("Rows Each Strip Is Not 1!"); 30 return -1; 31 } 32 33 TIFFGetField(tif_r, TIFFTAG_XRESOLUTION, &X_Resolut); 34 TIFFGetField(tif_r, TIFFTAG_YRESOLUTION, &Y_Resolut); 35 TIFFGetField(tif_r, TIFFTAG_RESOLUTIONUNIT, &ResolutUnit); 36 37 TIFFGetField(tif_r, TIFFTAG_PLANARCONFIG, &imagePlanarConfig); 38 TIFFGetField(tif_r, TIFFTAG_ORIENTATION, &Orientation); 39 40 int stripsize = TIFFStripSize(tif_r); 41 buf = (unsigned char *) malloc(stripsize) ; 42 if (!buf) 43 { 44 error_handler("Allocate Buffer Failed!"); 45 } 46 Mat ht_img(Size(imageWidth, imageLength),CV_8UC1,Scalar::all(0)); 47 const int color[7] = {0,1,2,3,4,5,6}; 48 unsigned char * pRow; 49 50 51 for (strip = 0; strip < TIFFNumberOfStrips(tif_r); strip++) 52 { 53 TIFFReadEncodedStrip(tif_r, strip, buf, (tsize_t) -1); 54 pRow = ht_img.ptr(strip); 55 for (int i_pixel = 0; i_pixel < imageWidth; i_pixel++) 56 { 57 pRow[i_pixel] = buf[i_pixel*imageSamplePerPixel + color[6]]; 58 } 59 } 60 imwrite("strip_out.tiff", ht_img); 61 62 free(buf); 63 TIFFClose(tif_r); 64 printf("Done!\n");
參考文獻:
1. libtiff庫的使用
http://darkranger.no-ip.org/archives/v5/document/develop/libtiff_tutorial.htm
2. 關於如何判斷一個tiff文件是tile或者是strip的說明
http://www.asmail.be/msg0054551721.html
