HDR文件格式簡介及其讀寫函數


轉自:http://blog.csdn.net/lqhbupt/article/details/7828827

1、HDR簡介
HDR的全稱是High-DynamicRange(高動態范圍)。在此,我們先解釋一下什么是DynamicRange(動態范圍),動態范圍是指圖像中所包含的從“最亮”至“最暗”的比值,也就是圖像從“最亮”到“最暗”之間灰度划分的等級數;動態范圍越大,所能表示的層次越豐富,所包含的色彩空間也越廣。那高動態范圍(HDR)顧名思義就是從“最亮”到“最暗”可以達到非常高的比值。
在日常生活中我們經常遇到這樣的情況:突然從黑暗的房間中走到陽光下,眼睛會無法睜開;清晨陽光會穿透窗簾像光柱般照射入房間;反光度較高的物體在強光下會在周圍產生光暈。以上這些生活中隨處可見的現象在有HDR以前無法在3D世界中呈現!最大的原因就在於我們使用8~16bit的整數數據,使用8~16bit的整數數據是整個圖象處理失真的關鍵點,所以我們對以往的運算方法做了以下二方面的重大改進:
1、使用16bit、32bit的數據來提高像素數據的精度。既然繼續使用8bit的數據來記錄像素的特征不能滿足HDR數據所需要的高精度運算的要求,在這種情況下,我們考慮使用16bit、32bit的數據記錄來提高像素數據的精度都是可以的。使用了更多的數據來保存像素特征之后,無論是像素的對比度還是像素可以體現的色彩數目都有了巨大的提高。
2、圖象數據采用浮點數據。HDR真正的巨大變革來自於浮點數據的引入。我們可以采用浮點方式來處理和存放亮度數據,拋棄不准確的整數數據;同時計算機在引入浮點數據來存儲象素的各個參數並且在運算的全過程都使用浮點數據,這樣就可以有效的提高據的精確度。
那么采用HDR后動態范圍最大可以有多大呢?我們看如下的公式,就可以知道我們到底使用了HDR后動態值可以有多大,而動態值的大小直接表現了動態范圍的大小:DynamicRange=log10(Max Intensity / Min Intensity)。公式中intensity是指強度,我們對最大亮度除以最低亮度的結果取對數,得到的結果就是動態范圍的相對數值。根據公式計算,當我們在亮度通道使用8bit的的情況下,最高亮度255,最低亮度1。那么計算得出的動態范圍就是數值約為2.4,加上單位就是24dB。同理可以計算得出16bit的亮度通道的動態范圍是數值約是4.8,是使用8bit亮度通道的一倍。理論上在HDR模式下,動態范圍的數值最高可以到達76.8。在NVIDIA所使用的OpenEXR中表現出來的HDR動態范圍的數值最大值約有12.0,遠遠高出單純使用16bit亮度通道的所帶來的亮度體驗,這是采用了優秀算法的結果。OpenEXR所能實現的最大動態范圍已經超過了人眼的9,帶來了更加真實的視覺體驗。

2、HDRI文件格式介紹(OpenEXR、RadianceRGBE、FloatTIFF)
HDRI(High-DynamicRange Image)就是記錄采用了HDR技術的圖象數據文件。常用的HDRI文件有OpenEXR、RadianceRGBE、FloatTIFF三種格式。 
2.1 OpenEXR文件格式
OpenEXR是由工業光魔(IndustrialLight & Magic)開發的一種HDR標准。OpenEXR文件的擴展名為.exr,常見的OpenEXR文件是FP16(16bitFloat Point,也被稱為halfFloat Point)數據圖像文件,每個通道的數據類型是FP16,一共四個通道64bpp,每個通道1個bit位用來標志“指數”,5個bit用來存放指數的值,10個bit存放色度坐標(u,v)的尾數,其動態范圍從6.14× 10 ^ -5到6.41× 10 ^ 4。
在OpenEXR的算法里面共使用16bit來表示光照數據。雖然看起來和使用16bit亮度通道運算位數相同,但是OpenEXR巧妙的采用了1個bit位用來標志“指數”,5個bit用來存放指數的值,10個bit存放色度坐標的尾數。這樣就輕易的解決了浮點數值由於位數少而精度不高的問題。大大的拓寬的在FP16下的動態范圍。根據實際的計算結果:在正規化的情況下OpenEXR可以提供和人眼基本相同的動態范圍,最暗到最亮是0.00006103515625(6.14 ×10 ^ -5)到65504(6.41 ×10 ^ 4),動態范圍是9.03;非正規化條件下,OpenEXR可以提供從最暗到最亮的數值從0.000000059604644775390625(5.96 ×10 ^ -8 )到65504(6.41 ×10 ^ 4),化為動態范圍表示就是12。
下面是Still寫的OpenEXR讀寫代碼,保存的.exr文件采用Zips壓縮編碼。

[cpp] view plain copy print ?
 
  1. bool COpenExr::Load(const char fileName[], int& width, int& height, float** pixels)  
  2. {   
  3. std::vector<float> vecpixels;  
  4. if(!Load(fileName, width, height, vecpixels))  
  5. return false;  
  6.   
  7. int num = width * height * 3;  
  8. *pixels = new float[num];  
  9. if(NULL == *pixels)  
  10. return false;  
  11.   
  12. std::vector<float>::pointer ptr = &vecpixels[0];  
  13. memcpy(*pixels, ptr, num * 4);   
  14. return true;  
  15. }  
  16. bool COpenExr::Load(const char fileName[], int& width, int& height, std::vector<float> &pixels)  
  17. {  
  18. Imf::Array<Imf::Rgba> pixelsdata;  
  19. bool bLoad = loadImage(fileName, width, height, pixelsdata);  
  20. if(!bLoad) return false;  
  21. for(int y = 0; y < height; y++)  
  22. {  
  23. int i = y * width;  
  24. for(int x = 0; x < width; x++)  
  25. {  
  26. int j = i + x;  
  27. const Imf::Rgba &rp = pixelsdata[j];  
  28.   
  29. pixels.push_back( float(rp.r));  
  30. pixels.push_back( float(rp.g));  
  31. pixels.push_back( float(rp.b));   
  32. }  
  33. }  
  34. return true;  
  35. }  
  36. bool COpenExr::loadImage (const char fileName[], int& width, int& height, Imf::Array<Imf::Rgba>& pixels)  
  37. {  
  38. Imf::RgbaInputFile in (fileName);  
  39. Imath::Box2i dataWindow = in.dataWindow();  
  40. int dw, dh, dx, dy;  
  41. width = dw = dataWindow.max.x - dataWindow.min.x + 1;  
  42. height = dh = dataWindow.max.y - dataWindow.min.y + 1;  
  43. dx = dataWindow.min.x;  
  44. dy = dataWindow.min.y;  
  45. pixels.resizeErase (dw * dh);  
  46. in.setFrameBuffer (pixels - dx - dy * dw, 1, dw);  
  47. try  
  48. {  
  49. in.readPixels (dataWindow.min.y, dataWindow.max.y);  
  50. }catch (const exception &e)  
  51. {  
  52. std::cerr << e.what() << std::endl;  
  53. return false;  
  54. }  
  55. return true;  
  56. }  
  57. bool COpenExr::Save(const char fileName[], int width, int height, const float* pixels)  
  58. {  
  59. std::vector<float> vecpixels(pixels, pixels + width * height * 3);  
  60. return Save(fileName, width, height, vecpixels);  
  61. }  
  62. bool COpenExr::Save(const char fileName[], int width, int height, const std::vector<float> pixels)  
  63. {  
  64. Imf::Array<Imf::Rgba> pixelsdata;  
  65. pixelsdata.resizeErase(width * height);  
  66. for(int y = 0; y < height; y++)  
  67. {  
  68. int i = y * width;  
  69. for(int x = 0; x < width; x++)  
  70. {  
  71. int j = i + x;  
  72.   
  73. half r = pixels[j * 3 ];  
  74. half g = pixels[j * 3 + 1];  
  75. half b = pixels[j * 3 + 2];  
  76. pixelsdata[j] = Imf::Rgba(r, g, b);  
  77. }  
  78. }  
  79. return SaveImage(fileName, width, height, pixelsdata);  
  80. }  
  81. bool COpenExr::SaveImage(const char fileName[], int width, int height, const Imf::Array<Imf::Rgba> &pixels)  
  82. {  
  83. Imf::RgbaOutputFile file (fileName, width, height);  
  84. file.setFrameBuffer(pixels, 1, width);  
  85. try  
  86. {  
  87. file.writePixels(height);  
  88. }catch(const exception &e)  
  89. {  
  90. std::cerr<< e.what() <<std::endl;  
  91. return false;  
  92. }  
  93. return true;  
  94. }   

官方庫鏈接地址:http://www.openexr.com/

 

2.2 Radiance RGBE文件格式
RGBE文件的擴展名為.hdr,RGBE正式名稱為RadianceRGBE格式。這個本來是BR、FR等作為radiance材質的一種格式,也叫做radiancemap,后來成為流行的一種HDR格式。所謂E,就是指數。RadianceRGBE文件每個通道為8bitBYTE數據類型,4個通道一共是32bit。RGBE可以使用RLE壓縮編碼壓縮,也可以不壓縮。由文件頭、RGBE數據組成。
文件頭如下:
類型輸出格式
char programtype[16]; //#?Radiance/n#Generated by still/n
float gamma; //1.0
float exposure; //1.0
字符串常量//FORMAT=32-bit_rle_rgbe/n/n
int nWidth, int nHeight //-Y nHeight +X nWidth/n

RGBE數據與HDRFP32(RGB)相互轉換公式如下:
1、rgbe->FP32(RGB)
如果e為0, R = G= B = 0.0,否則:
R = r * 2^(e – 128 - 8);
G = g * 2^(e – 128 - 8);
B = b * 2^(e – 128 - 8);

2、FP32(RGB)-> rgbe
v = max(R, G, B); 
如果v< 1e-32, r = g = b = e = 0, 否則:
將v用科學計算法表示成v = m * 2 ^ n ( 0 < m < 1):
r = R * m * 256.0/v; 
g = G * m * 256.0/v;
b = B * m * 256.0/v;
e = n + 128;

Still注:
1、我們一般說HDR采用FP32,指的是HDR圖象運算時候的內存數據類型,而RadianceRGBE文件采用8bitBYTE類型存儲HDR數據。也就是說打開RadianceRGBE文件,要使用上面的公式1將RadianceRGBE文件的8bitBYTE文件數據轉換為FP32的HDR內存數據進行運算;保存為RadianceRGBE文件時,要使用上面的公式2將HDR的FP32內存數據轉換為RadianceRGBE的8bitBYTE文件數據進行保存。同理,OpenEXR文件的讀寫也存在將其FP16的文件數據到HDR的 FP32圖象數據的轉換;而下面將要講的FloatTiff是不需要進行數據轉換,直接將HDR的FP 32圖象數據保存到TIFF
文件中即可。
2、Radiance有多種文件格式,其官方庫包含內容比較復雜,所以,實際的讀寫沒有使用其官方庫,而是使用了網絡上一個簡單的C語言讀寫類,Still並對其進行了部分修改(在文件頭寫入“Generatedby Still”)。

讀寫類鏈接地址:http://www.graphics.cornell.edu/~bjw/rgbe.html
官方庫鏈接地址:http://radsite.lbl.gov/radiance/

****************************************************************************************

rgbe.txt - description of interface 
rgbe.h - header file 
rgbe.c - C code 
Where can I find more information?
See "Real Pixels" by Greg Ward in Graphics Gems II .

*****************************************************************************************

Here's the minimal code for using these files. sampleminimal writing code: 
f = fopen(image_filename,"wb"); 
RGBE_WriteHeader(f,image_width,image_height,NULL); 
RGBE_WritePixels(f,image,image_width*image_height); 
fclose(f); 
For run length encoding instead of RGBE_WritePixels, useRGBE_WritePixels_RLE(f,image,image_width,image_height). sample minimal readingcode: 
f = fopen(image_filename,"rb"); 
RGBE_ReadHeader(f,&image_width,&image_height,NULL); 
image = (float *)malloc(sizeof(float)*3*image_width*image_height); 
RGBE_ReadPixels_RLE(f,image,image_width,image_height); 
fclose(f); 
******************************************************************************************

 

[cpp] view plain copy print ?
 
  1. //rgbe.h--header file  
  2. #ifndef _H_RGBE  
  3. #define _H_RGBE  
  4. /* THIS CODE CARRIES NO GUARANTEE OF USABILITY OR FITNESS FOR ANY PURPOSE. 
  5. * WHILE THE AUTHORS HAVE TRIED TO ENSURE THE PROGRAM WORKS CORRECTLY, 
  6. * IT IS STRICTLY USE AT YOUR OWN RISK. */  
  7. /* utility for reading and writing Ward's rgbe image format. 
  8. See rgbe.txt file for more details. 
  9. */  
  10. #include <stdio.h>  
  11. typedef struct {  
  12. int valid; /* indicate which fields are valid */  
  13. char programtype[16]; /* listed at beginning of file to identify it  
  14. * after "#?". defaults to "RGBE" */   
  15. float gamma; /* image has already been gamma corrected with  
  16. * given gamma. defaults to 1.0 (no correction) */  
  17. float exposure; /* a value of 1.0 in an image corresponds to 
  18. * <exposure> watts/steradian/m^2.  
  19. * defaults to 1.0 */  
  20. } rgbe_header_info;  
  21. /* flags indicating which fields in an rgbe_header_info are valid */  
  22. #define RGBE_VALID_PROGRAMTYPE 0x01  
  23. #define RGBE_VALID_GAMMA 0x02  
  24. #define RGBE_VALID_EXPOSURE 0x04  
  25. /* return codes for rgbe routines */  
  26. #define RGBE_RETURN_SUCCESS 0  
  27. #define RGBE_RETURN_FAILURE -1  
  28. /* read or write headers */  
  29. /* you may set rgbe_header_info to null if you want to */  
  30. int RGBE_WriteHeader(FILE *fp, int width, int height, rgbe_header_info *info);  
  31. int RGBE_ReadHeader(FILE *fp, int *width, int *height, rgbe_header_info *info);  
  32. /* read or write pixels */  
  33. /* can read or write pixels in chunks of any size including single pixels*/  
  34. int RGBE_WritePixels(FILE *fp, float *data, int numpixels);  
  35. int RGBE_ReadPixels(FILE *fp, float *data, int numpixels);  
  36. /* read or write run length encoded files */  
  37. /* must be called to read or write whole scanlines */  
  38. int RGBE_WritePixels_RLE(FILE *fp, float *data, int scanline_width,  
  39. int num_scanlines);  
  40. int RGBE_ReadPixels_RLE(FILE *fp, float *data, int scanline_width,  
  41. int num_scanlines);  
  42. #endif /* _H_RGBE */  

 

 

[cpp] view plain copy print ?
 
  1. //rgbe.c -- C code  
  2. /* THIS CODE CARRIES NO GUARANTEE OF USABILITY OR FITNESS FOR ANY PURPOSE. 
  3. * WHILE THE AUTHORS HAVE TRIED TO ENSURE THE PROGRAM WORKS CORRECTLY, 
  4. * IT IS STRICTLY USE AT YOUR OWN RISK. */  
  5. #include "rgbe.h"  
  6. #include <math.h>  
  7. #include <malloc.h>  
  8. #include <string.h>  
  9. #include <ctype.h>  
  10. /* This file contains code to read and write four byte rgbe file format 
  11. developed by Greg Ward. It handles the conversions between rgbe and 
  12. pixels consisting of floats. The data is assumed to be an array of floats. 
  13. By default there are three floats per pixel in the order red, green, blue. 
  14. (RGBE_DATA_??? values control this.) Only the mimimal header reading and  
  15. writing is implemented. Each routine does error checking and will return 
  16. a status value as defined below. This code is intended as a skeleton so 
  17. feel free to modify it to suit your needs. 
  18. (Place notice here if you modified the code.) 
  19. posted to http://www.graphics.cornell.edu/~bjw/ 
  20. written by Bruce Walter (bjw@graphics.cornell.edu) 5/26/95 
  21. based on code written by Greg Ward 
  22. */  
  23. #ifdef _CPLUSPLUS  
  24. /* define if your compiler understands inline commands */  
  25. #define INLINE inline  
  26. #else  
  27. #define INLINE  
  28. #endif  
  29. /* offsets to red, green, and blue components in a data (float) pixel */  
  30. #define RGBE_DATA_RED 0  
  31. #define RGBE_DATA_GREEN 1  
  32. #define RGBE_DATA_BLUE 2  
  33. /* number of floats per pixel */  
  34. #define RGBE_DATA_SIZE 3  
  35. enum rgbe_error_codes {  
  36. rgbe_read_error,  
  37. rgbe_write_error,  
  38. rgbe_format_error,  
  39. rgbe_memory_error,  
  40. };  
  41. /* default error routine. change this to change error handling */  
  42. static int rgbe_error(int rgbe_error_code, char *msg)  
  43. {  
  44. switch (rgbe_error_code) {  
  45. case rgbe_read_error:  
  46. perror("RGBE read error");  
  47. break;  
  48. case rgbe_write_error:  
  49. perror("RGBE write error");  
  50. break;  
  51. case rgbe_format_error:  
  52. fprintf(stderr,"RGBE bad file format: %s/n",msg);  
  53. break;  
  54. default:  
  55. case rgbe_memory_error:  
  56. fprintf(stderr,"RGBE error: %s/n",msg);  
  57. }  
  58. return RGBE_RETURN_FAILURE;  
  59. }  
  60. /* standard conversion from float pixels to rgbe pixels */  
  61. /* note: you can remove the "inline"s if your compiler complains about it */  
  62. static INLINE void   
  63. float2rgbe(unsigned char rgbe[4], float red, float green, float blue)  
  64. {  
  65. float v;  
  66. int e;  
  67. v = red;  
  68. if (green > v) v = green;  
  69. if (blue > v) v = blue;  
  70. if (v < 1e-32) {  
  71. rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0;  
  72. }  
  73. else {  
  74. v = frexp(v,&e) * 256.0/v;  
  75. rgbe[0] = (unsigned char) (red * v);  
  76. rgbe[1] = (unsigned char) (green * v);  
  77. rgbe[2] = (unsigned char) (blue * v);  
  78. rgbe[3] = (unsigned char) (e + 128);  
  79. }  
  80. }  
  81. /* standard conversion from rgbe to float pixels */  
  82. /* note: Ward uses ldexp(col+0.5,exp-(128+8)). However we wanted pixels */  
  83. /* in the range [0,1] to map back into the range [0,1]. */  
  84. static INLINE void   
  85. rgbe2float(float *red, float *green, float *blue, unsigned char rgbe[4])  
  86. {  
  87. float f;  
  88. if (rgbe[3]) { /*nonzero pixel*/  
  89. f = ldexp(1.0,rgbe[3]-(int)(128+8));  
  90. *red = rgbe[0] * f;  
  91. *green = rgbe[1] * f;  
  92. *blue = rgbe[2] * f;  
  93. }  
  94. else  
  95. *red = *green = *blue = 0.0;  
  96. }  
  97. /* default minimal header. modify if you want more information in header */  
  98. int RGBE_WriteHeader(FILE *fp, int width, int height, rgbe_header_info *info)  
  99. {  
  100. char *programtype = "RGBE";  
  101. if (info && (info->valid & RGBE_VALID_PROGRAMTYPE))  
  102. programtype = info->programtype;  
  103. if (fprintf(fp,"#?%s/n",programtype) < 0)  
  104. return rgbe_error(rgbe_write_error,NULL);  
  105. /* The #? is to identify file type, the programtype is optional. */  
  106. if (info && (info->valid & RGBE_VALID_GAMMA)) {  
  107. if (fprintf(fp,"GAMMA=%g/n",info->gamma) < 0)  
  108. return rgbe_error(rgbe_write_error,NULL);  
  109. }  
  110. if (info && (info->valid & RGBE_VALID_EXPOSURE)) {  
  111. if (fprintf(fp,"EXPOSURE=%g/n",info->exposure) < 0)  
  112. return rgbe_error(rgbe_write_error,NULL);  
  113. }  
  114. if (fprintf(fp,"FORMAT=32-bit_rle_rgbe/n/n") < 0)  
  115. return rgbe_error(rgbe_write_error,NULL);  
  116. if (fprintf(fp, "-Y %d +X %d/n", height, width) < 0)  
  117. return rgbe_error(rgbe_write_error,NULL);  
  118. return RGBE_RETURN_SUCCESS;  
  119. }  
  120. /* minimal header reading. modify if you want to parse more information */  
  121. int RGBE_ReadHeader(FILE *fp, int *width, int *height, rgbe_header_info *info)  
  122. {  
  123. char buf[128];  
  124. int found_format;  
  125. float tempf;  
  126. int i;  
  127. found_format = 0;  
  128. if (info) {  
  129. info->valid = 0;  
  130. info->programtype[0] = 0;  
  131. info->gamma = info->exposure = 1.0;  
  132. }  
  133. if (fgets(buf,sizeof(buf)/sizeof(buf[0]),fp) == NULL)  
  134. return rgbe_error(rgbe_read_error,NULL);  
  135. if ((buf[0] != '#')||(buf[1] != '?')) {  
  136. /* if you want to require the magic token then uncomment the next line */  
  137. /*return rgbe_error(rgbe_format_error,"bad initial token"); */  
  138. }  
  139. else if (info) {  
  140. info->valid |= RGBE_VALID_PROGRAMTYPE;  
  141. for(i=0;i<sizeof(info->programtype)-1;i++) {  
  142. if ((buf[i+2] == 0) || isspace(buf[i+2]))  
  143. break;  
  144. info->programtype[i] = buf[i+2];  
  145. }  
  146. info->programtype[i] = 0;  
  147. if (fgets(buf,sizeof(buf)/sizeof(buf[0]),fp) == 0)  
  148. return rgbe_error(rgbe_read_error,NULL);  
  149. }  
  150. for(;;) {  
  151. if ((buf[0] == 0)||(buf[0] == '/n'))  
  152. return rgbe_error(rgbe_format_error,"no FORMAT specifier found");  
  153. else if (strcmp(buf,"FORMAT=32-bit_rle_rgbe/n") == 0)  
  154. break; /* format found so break out of loop */  
  155. else if (info && (sscanf(buf,"GAMMA=%g",&tempf) == 1)) {  
  156. info->gamma = tempf;  
  157. info->valid |= RGBE_VALID_GAMMA;  
  158. }  
  159. else if (info && (sscanf(buf,"EXPOSURE=%g",&tempf) == 1)) {  
  160. info->exposure = tempf;  
  161. info->valid |= RGBE_VALID_EXPOSURE;  
  162. }  
  163. if (fgets(buf,sizeof(buf)/sizeof(buf[0]),fp) == 0)  
  164. return rgbe_error(rgbe_read_error,NULL);  
  165. }  
  166. if (fgets(buf,sizeof(buf)/sizeof(buf[0]),fp) == 0)  
  167. return rgbe_error(rgbe_read_error,NULL);  
  168. if (strcmp(buf,"/n") != 0)  
  169. return rgbe_error(rgbe_format_error,  
  170. "missing blank line after FORMAT specifier");  
  171. if (fgets(buf,sizeof(buf)/sizeof(buf[0]),fp) == 0)  
  172. return rgbe_error(rgbe_read_error,NULL);  
  173. if (sscanf(buf,"-Y %d +X %d",height,width) < 2)  
  174. return rgbe_error(rgbe_format_error,"missing image size specifier");  
  175. return RGBE_RETURN_SUCCESS;  
  176. }  
  177. /* simple write routine that does not use run length encoding */  
  178. /* These routines can be made faster by allocating a larger buffer and 
  179. fread-ing and fwrite-ing the data in larger chunks */  
  180. int RGBE_WritePixels(FILE *fp, float *data, int numpixels)  
  181. {  
  182. unsigned char rgbe[4];  
  183. while (numpixels-- > 0) {  
  184. float2rgbe(rgbe,data[RGBE_DATA_RED],  
  185. data[RGBE_DATA_GREEN],data[RGBE_DATA_BLUE]);  
  186. data += RGBE_DATA_SIZE;  
  187. if (fwrite(rgbe, sizeof(rgbe), 1, fp) < 1)  
  188. return rgbe_error(rgbe_write_error,NULL);  
  189. }  
  190. return RGBE_RETURN_SUCCESS;  
  191. }  
  192. /* simple read routine. will not correctly handle run length encoding */  
  193. int RGBE_ReadPixels(FILE *fp, float *data, int numpixels)  
  194. {  
  195. unsigned char rgbe[4];  
  196. while(numpixels-- > 0) {  
  197. if (fread(rgbe, sizeof(rgbe), 1, fp) < 1)  
  198. return rgbe_error(rgbe_read_error,NULL);  
  199. rgbe2float(&data[RGBE_DATA_RED],&data[RGBE_DATA_GREEN],  
  200. &data[RGBE_DATA_BLUE],rgbe);  
  201. data += RGBE_DATA_SIZE;  
  202. }  
  203. return RGBE_RETURN_SUCCESS;  
  204. }  
  205. /* The code below is only needed for the run-length encoded files. */  
  206. /* Run length encoding adds considerable complexity but does */  
  207. /* save some space. For each scanline, each channel (r,g,b,e) is */  
  208. /* encoded separately for better compression. */  
  209. static int RGBE_WriteBytes_RLE(FILE *fp, unsigned char *data, int numbytes)  
  210. {  
  211. #define MINRUNLENGTH 4  
  212. int cur, beg_run, run_count, old_run_count, nonrun_count;  
  213. unsigned char buf[2];  
  214. cur = 0;  
  215. while(cur < numbytes) {  
  216. beg_run = cur;  
  217. /* find next run of length at least 4 if one exists */  
  218. run_count = old_run_count = 0;  
  219. while((run_count < MINRUNLENGTH) && (beg_run < numbytes)) {  
  220. beg_run += run_count;  
  221. old_run_count = run_count;  
  222. run_count = 1;  
  223. while( (beg_run + run_count < numbytes) && (run_count < 127)  
  224. && (data[beg_run] == data[beg_run + run_count]))  
  225. run_count++;  
  226. }  
  227. /* if data before next big run is a short run then write it as such */  
  228. if ((old_run_count > 1)&&(old_run_count == beg_run - cur)) {  
  229. buf[0] = 128 + old_run_count; /*write short run*/  
  230. buf[1] = data[cur];  
  231. if (fwrite(buf,sizeof(buf[0])*2,1,fp) < 1)  
  232. return rgbe_error(rgbe_write_error,NULL);  
  233. cur = beg_run;  
  234. }  
  235. /* write out bytes until we reach the start of the next run */  
  236. while(cur < beg_run) {  
  237. nonrun_count = beg_run - cur;  
  238. if (nonrun_count > 128)   
  239. nonrun_count = 128;  
  240. buf[0] = nonrun_count;  
  241. if (fwrite(buf,sizeof(buf[0]),1,fp) < 1)  
  242. return rgbe_error(rgbe_write_error,NULL);  
  243. if (fwrite(&data[cur],sizeof(data[0])*nonrun_count,1,fp) < 1)  
  244. return rgbe_error(rgbe_write_error,NULL);  
  245. cur += nonrun_count;  
  246. }  
  247. /* write out next run if one was found */  
  248. if (run_count >= MINRUNLENGTH) {  
  249. buf[0] = 128 + run_count;  
  250. buf[1] = data[beg_run];  
  251. if (fwrite(buf,sizeof(buf[0])*2,1,fp) < 1)  
  252. return rgbe_error(rgbe_write_error,NULL);  
  253. cur += run_count;  
  254. }  
  255. }  
  256. return RGBE_RETURN_SUCCESS;  
  257. #undef MINRUNLENGTH  
  258. }  
  259. int RGBE_WritePixels_RLE(FILE *fp, float *data, int scanline_width,  
  260. int num_scanlines)  
  261. {  
  262. unsigned char rgbe[4];  
  263. unsigned char *buffer;  
  264. int i, err;  
  265. if ((scanline_width < 8)||(scanline_width > 0x7fff))  
  266. /* run length encoding is not allowed so write flat*/  
  267. return RGBE_WritePixels(fp,data,scanline_width*num_scanlines);  
  268. buffer = (unsigned char *)malloc(sizeof(unsigned char)*4*scanline_width);  
  269. if (buffer == NULL)   
  270. /* no buffer space so write flat */  
  271. return RGBE_WritePixels(fp,data,scanline_width*num_scanlines);  
  272. while(num_scanlines-- > 0) {  
  273. rgbe[0] = 2;  
  274. rgbe[1] = 2;  
  275. rgbe[2] = scanline_width >> 8;  
  276. rgbe[3] = scanline_width & 0xFF;  
  277. if (fwrite(rgbe, sizeof(rgbe), 1, fp) < 1) {  
  278. free(buffer);  
  279. return rgbe_error(rgbe_write_error,NULL);  
  280. }  
  281. for(i=0;i<scanline_width;i++) {  
  282. float2rgbe(rgbe,data[RGBE_DATA_RED],  
  283. data[RGBE_DATA_GREEN],data[RGBE_DATA_BLUE]);  
  284. buffer[i] = rgbe[0];  
  285. buffer[i+scanline_width] = rgbe[1];  
  286. buffer[i+2*scanline_width] = rgbe[2];  
  287. buffer[i+3*scanline_width] = rgbe[3];  
  288. data += RGBE_DATA_SIZE;  
  289. }  
  290. /* write out each of the four channels separately run length encoded */  
  291. /* first red, then green, then blue, then exponent */  
  292. for(i=0;i<4;i++) {  
  293. if ((err = RGBE_WriteBytes_RLE(fp,&buffer[i*scanline_width],  
  294. scanline_width)) != RGBE_RETURN_SUCCESS) {  
  295. free(buffer);  
  296. return err;  
  297. }  
  298. }  
  299. }  
  300. free(buffer);  
  301. return RGBE_RETURN_SUCCESS;  
  302. }  
  303.   
  304. int RGBE_ReadPixels_RLE(FILE *fp, float *data, int scanline_width,  
  305. int num_scanlines)  
  306. {  
  307. unsigned char rgbe[4], *scanline_buffer, *ptr, *ptr_end;  
  308. int i, count;  
  309. unsigned char buf[2];  
  310. if ((scanline_width < 8)||(scanline_width > 0x7fff))  
  311. /* run length encoding is not allowed so read flat*/  
  312. return RGBE_ReadPixels(fp,data,scanline_width*num_scanlines);  
  313. scanline_buffer = NULL;  
  314. /* read in each successive scanline */  
  315. while(num_scanlines > 0) {  
  316. if (fread(rgbe,sizeof(rgbe),1,fp) < 1) {  
  317. free(scanline_buffer);  
  318. return rgbe_error(rgbe_read_error,NULL);  
  319. }  
  320. if ((rgbe[0] != 2)||(rgbe[1] != 2)||(rgbe[2] & 0x80)) {  
  321. /* this file is not run length encoded */  
  322. rgbe2float(&data[0],&data[1],&data[2],rgbe);  
  323. data += RGBE_DATA_SIZE;  
  324. free(scanline_buffer);  
  325. return RGBE_ReadPixels(fp,data,scanline_width*num_scanlines-1);  
  326. }  
  327. if ((((int)rgbe[2])<<8 | rgbe[3]) != scanline_width) {  
  328. free(scanline_buffer);  
  329. return rgbe_error(rgbe_format_error,"wrong scanline width");  
  330. }  
  331. if (scanline_buffer == NULL)  
  332. scanline_buffer = (unsigned char *)  
  333. malloc(sizeof(unsigned char)*4*scanline_width);  
  334. if (scanline_buffer == NULL)   
  335. return rgbe_error(rgbe_memory_error,"unable to allocate buffer space");  
  336.   
  337. ptr = &scanline_buffer[0];  
  338. /* read each of the four channels for the scanline into the buffer */  
  339. for(i=0;i<4;i++) {  
  340. ptr_end = &scanline_buffer[(i+1)*scanline_width];  
  341. while(ptr < ptr_end) {  
  342. if (fread(buf,sizeof(buf[0])*2,1,fp) < 1) {  
  343. free(scanline_buffer);  
  344. return rgbe_error(rgbe_read_error,NULL);  
  345. }  
  346. if (buf[0] > 128) {  
  347. /* a run of the same value */  
  348. count = buf[0]-128;  
  349. if ((count == 0)||(count > ptr_end - ptr)) {  
  350. free(scanline_buffer);  
  351. return rgbe_error(rgbe_format_error,"bad scanline data");  
  352. }  
  353. while(count-- > 0)  
  354. *ptr++ = buf[1];  
  355. }  
  356. else {  
  357. /* a non-run */  
  358. count = buf[0];  
  359. if ((count == 0)||(count > ptr_end - ptr)) {  
  360. free(scanline_buffer);  
  361. return rgbe_error(rgbe_format_error,"bad scanline data");  
  362. }  
  363. *ptr++ = buf[1];  
  364. if (--count > 0) {  
  365. if (fread(ptr,sizeof(*ptr)*count,1,fp) < 1) {  
  366. free(scanline_buffer);  
  367. return rgbe_error(rgbe_read_error,NULL);  
  368. }  
  369. ptr += count;  
  370. }  
  371. }  
  372. }  
  373. }  
  374. /* now convert data from buffer into floats */  
  375. for(i=0;i<scanline_width;i++) {  
  376. rgbe[0] = scanline_buffer[i];  
  377. rgbe[1] = scanline_buffer[i+scanline_width];  
  378. rgbe[2] = scanline_buffer[i+2*scanline_width];  
  379. rgbe[3] = scanline_buffer[i+3*scanline_width];  
  380. rgbe2float(&data[RGBE_DATA_RED],&data[RGBE_DATA_GREEN],  
  381. &data[RGBE_DATA_BLUE],rgbe);  
  382. data += RGBE_DATA_SIZE;  
  383. }  
  384. num_scanlines--;  
  385. }  
  386. free(scanline_buffer);  
  387. return RGBE_RETURN_SUCCESS;  
  388. }  


 

2.3 FloatTiff文件格式
Tiff文件的擴展名為.tif(.tiff),FloatTiff每個通道為FP32(32bit Float Point)類型,一共3個通道96bpp。用Tiff文件存儲HDR數據,直接將HDR的FP32保存到TIFF文件中,有官方庫可以利用。下面是Still寫的代碼樣例,HDR數據我采用的是LZW壓縮編碼: 

[cpp] view plain copy print ?
 
  1. bool CFloatTiff::Load(const char fileName[], int& width, int& height, float** pixels)  
  2. {  
  3. TIFF* fp = NULL;  
  4. if((fp = TIFFOpen(fileName, "r")) == NULL)  
  5. return false;  
  6.   
  7. //獲取信息  
  8. uint16 bps, spp, datatype, photometric, compression, planarconfig, fillorder;  
  9.   
  10. //每個通道占據的數據位數  
  11. if( (TIFFGetField(fp, TIFFTAG_BITSPERSAMPLE, &bps) == 0) || (bps != 32))  
  12. return false;  
  13. //每個象素的通道數目  
  14. if((TIFFGetField(fp, TIFFTAG_SAMPLESPERPIXEL, &spp) == 0) || (spp != 3))  
  15. return false;  
  16. //每個通道的數據類型  
  17. if((TIFFGetField(fp, TIFFTAG_SAMPLEFORMAT, &datatype) == 0) || (datatype != AMPLEFORMAT_IEEEFP))  
  18. return false;  
  19. //圖像的數據采用的顏色模型  
  20. if((TIFFGetField(fp, TIFFTAG_PHOTOMETRIC, &photometric) == 0) || (photometric != PHOTOMETRIC_RGB))  
  21. return false;  
  22. TIFFGetField(fp, TIFFTAG_IMAGEWIDTH, &width);  
  23. TIFFGetField(fp, TIFFTAG_IMAGELENGTH, &height);  
  24. int num = width * height * 3;  
  25. *pixels = new float[num];  
  26. if(NULL == *pixels)  
  27. return false;  
  28.   
  29. if( TIFFReadEncodedStrip(fp, 0, *pixels, width * height * 3 * 4) == -1)  
  30. return false;  
  31.   
  32. TIFFClose(fp);  
  33. return true;  
  34. }  
  35. bool CFloatTiff::Save(const char fileName[], int width, int height, const float* pixels)  
  36. {  
  37. if(NULL == pixels)  
  38. return false;  
  39.   
  40. TIFF *fp = NULL;  
  41.   
  42. if((fp = TIFFOpen(fileName, "w")) == NULL)  
  43. return false;  
  44. TIFFSetField(fp, TIFFTAG_IMAGEWIDTH, width);  
  45. TIFFSetField(fp, TIFFTAG_IMAGELENGTH, height);  
  46. TIFFSetField(fp, TIFFTAG_COMPRESSION, COMPRESSION_LZW);//COMPRESSION_DEFLATE;  
  47. TIFFSetField(fp, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);  
  48. TIFFSetField(fp, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);  
  49. TIFFSetField(fp, TIFFTAG_BITSPERSAMPLE, 32);  
  50. TIFFSetField(fp, TIFFTAG_SAMPLESPERPIXEL, 3);  
  51. TIFFSetField(fp, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_IEEEFP);  
  52. if(TIFFWriteEncodedStrip(fp, 0, const_cast<float*>(pixels), width * height * 3 * 4) == -1)  
  53. return false;  
  54. TIFFClose(fp);  
  55. return true;  
  56. }   

官方庫鏈接地址:http://www.remotesensing.org/libtiff/


Still注:
1、這篇文章的基礎知識大部分來自:《光與影的魔術棒——HDR技術解析》
http://www.cqumzh.cn/topic_show.php?tid=200271
2、這段時間工作比較忙,關於OpenEXR文件格式的詳細介紹需要翻譯相關文檔,而且這部分內容是05年接觸的,重新總結需要一些時間;還有HDR合成、ToneMapping方面的技術下次再奉上。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM