OpenEXRimages_HDR_Retina_toneMapping.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. //============================================================================
  2. // Name : OpenEXRimages_HDR_Retina_toneMapping.cpp
  3. // Author : Alexandre Benoit (benoit.alexandre.vision@gmail.com)
  4. // Version : 0.1
  5. // Copyright : Alexandre Benoit, LISTIC Lab, july 2011
  6. // Description : HighDynamicRange retina tone mapping with the help of the Gipsa/Listic's retina in C++, Ansi-style
  7. //============================================================================
  8. #include <iostream>
  9. #include <cstring>
  10. #include "opencv2/bioinspired.hpp" // retina based algorithms
  11. #include "opencv2/imgproc.hpp" // cvCvtcolor function
  12. #include "opencv2/highgui.hpp" // display
  13. static void help(std::string errorMessage)
  14. {
  15. std::cout<<"Program init error : "<<errorMessage<<std::endl;
  16. std::cout<<"\nProgram call procedure : ./OpenEXRimages_HDR_Retina_toneMapping [OpenEXR image to process]"<<std::endl;
  17. std::cout<<"\t[OpenEXR image to process] : the input HDR image to process, must be an OpenEXR format, see http://www.openexr.com/ to get some samples or create your own using camera bracketing and Photoshop or equivalent software for OpenEXR image synthesis"<<std::endl;
  18. std::cout<<"\nExamples:"<<std::endl;
  19. std::cout<<"\t-Image processing : ./OpenEXRimages_HDR_Retina_toneMapping memorial.exr"<<std::endl;
  20. }
  21. // simple procedure for 1D curve tracing
  22. static void drawPlot(const cv::Mat curve, const std::string figureTitle, const int lowerLimit, const int upperLimit)
  23. {
  24. //std::cout<<"curve size(h,w) = "<<curve.size().height<<", "<<curve.size().width<<std::endl;
  25. cv::Mat displayedCurveImage = cv::Mat::ones(200, curve.size().height, CV_8U);
  26. cv::Mat windowNormalizedCurve;
  27. normalize(curve, windowNormalizedCurve, 0, 200, cv::NORM_MINMAX, CV_32F);
  28. displayedCurveImage = cv::Scalar::all(255); // set a white background
  29. int binW = cvRound((double)displayedCurveImage.cols/curve.size().height);
  30. for( int i = 0; i < curve.size().height; i++ )
  31. rectangle( displayedCurveImage, cv::Point(i*binW, displayedCurveImage.rows),
  32. cv::Point((i+1)*binW, displayedCurveImage.rows - cvRound(windowNormalizedCurve.at<float>(i))),
  33. cv::Scalar::all(0), -1, 8, 0 );
  34. rectangle( displayedCurveImage, cv::Point(0, 0),
  35. cv::Point((lowerLimit)*binW, 200),
  36. cv::Scalar::all(128), -1, 8, 0 );
  37. rectangle( displayedCurveImage, cv::Point(displayedCurveImage.cols, 0),
  38. cv::Point((upperLimit)*binW, 200),
  39. cv::Scalar::all(128), -1, 8, 0 );
  40. cv::imshow(figureTitle, displayedCurveImage);
  41. }
  42. /*
  43. * objective : get the gray level map of the input image and rescale it to the range [0-255]
  44. */
  45. static void rescaleGrayLevelMat(const cv::Mat &inputMat, cv::Mat &outputMat, const float histogramClippingLimit)
  46. {
  47. // adjust output matrix wrt the input size but single channel
  48. std::cout<<"Input image rescaling with histogram edges cutting (in order to eliminate bad pixels created during the HDR image creation) :"<<std::endl;
  49. //std::cout<<"=> image size (h,w,channels) = "<<inputMat.size().height<<", "<<inputMat.size().width<<", "<<inputMat.channels()<<std::endl;
  50. //std::cout<<"=> pixel coding (nbchannel, bytes per channel) = "<<inputMat.elemSize()/inputMat.elemSize1()<<", "<<inputMat.elemSize1()<<std::endl;
  51. // rescale between 0-255, keeping floating point values
  52. cv::normalize(inputMat, outputMat, 0.0, 255.0, cv::NORM_MINMAX);
  53. // extract a 8bit image that will be used for histogram edge cut
  54. cv::Mat intGrayImage;
  55. if (inputMat.channels()==1)
  56. {
  57. outputMat.convertTo(intGrayImage, CV_8U);
  58. }else
  59. {
  60. cv::Mat rgbIntImg;
  61. outputMat.convertTo(rgbIntImg, CV_8UC3);
  62. cvtColor(rgbIntImg, intGrayImage, cv::COLOR_BGR2GRAY);
  63. }
  64. // get histogram density probability in order to cut values under above edges limits (here 5-95%)... useful for HDR pixel errors cancellation
  65. cv::Mat dst, hist;
  66. int histSize = 256;
  67. calcHist(&intGrayImage, 1, 0, cv::Mat(), hist, 1, &histSize, 0);
  68. cv::Mat normalizedHist;
  69. normalize(hist, normalizedHist, 1, 0, cv::NORM_L1, CV_32F); // normalize histogram so that its sum equals 1
  70. double min_val, max_val;
  71. minMaxLoc(normalizedHist, &min_val, &max_val);
  72. //std::cout<<"Hist max,min = "<<max_val<<", "<<min_val<<std::endl;
  73. // compute density probability
  74. cv::Mat denseProb=cv::Mat::zeros(normalizedHist.size(), CV_32F);
  75. denseProb.at<float>(0)=normalizedHist.at<float>(0);
  76. int histLowerLimit=0, histUpperLimit=0;
  77. for (int i=1;i<normalizedHist.size().height;++i)
  78. {
  79. denseProb.at<float>(i)=denseProb.at<float>(i-1)+normalizedHist.at<float>(i);
  80. //std::cout<<normalizedHist.at<float>(i)<<", "<<denseProb.at<float>(i)<<std::endl;
  81. if ( denseProb.at<float>(i)<histogramClippingLimit)
  82. histLowerLimit=i;
  83. if ( denseProb.at<float>(i)<1-histogramClippingLimit)
  84. histUpperLimit=i;
  85. }
  86. // deduce min and max admitted gray levels
  87. float minInputValue = (float)histLowerLimit/histSize*255;
  88. float maxInputValue = (float)histUpperLimit/histSize*255;
  89. std::cout<<"=> Histogram limits "
  90. <<"\n\t"<<histogramClippingLimit*100<<"% index = "<<histLowerLimit<<" => normalizedHist value = "<<denseProb.at<float>(histLowerLimit)<<" => input gray level = "<<minInputValue
  91. <<"\n\t"<<(1-histogramClippingLimit)*100<<"% index = "<<histUpperLimit<<" => normalizedHist value = "<<denseProb.at<float>(histUpperLimit)<<" => input gray level = "<<maxInputValue
  92. <<std::endl;
  93. //drawPlot(denseProb, "input histogram density probability", histLowerLimit, histUpperLimit);
  94. drawPlot(normalizedHist, "input histogram", histLowerLimit, histUpperLimit);
  95. // rescale image range [minInputValue-maxInputValue] to [0-255]
  96. outputMat-=minInputValue;
  97. outputMat*=255.0/(maxInputValue-minInputValue);
  98. // cut original histogram and back project to original image
  99. cv::threshold( outputMat, outputMat, 255.0, 255.0, 2 ); //THRESH_TRUNC, clips values above 255
  100. cv::threshold( outputMat, outputMat, 0.0, 0.0, 3 ); //THRESH_TOZERO, clips values under 0
  101. }
  102. // basic callback method for interface management
  103. cv::Mat inputImage;
  104. cv::Mat imageInputRescaled;
  105. int histogramClippingValue;
  106. static void callBack_rescaleGrayLevelMat(int, void*)
  107. {
  108. std::cout<<"Histogram clipping value changed, current value = "<<histogramClippingValue<<std::endl;
  109. rescaleGrayLevelMat(inputImage, imageInputRescaled, (float)(histogramClippingValue/100.0));
  110. normalize(imageInputRescaled, imageInputRescaled, 0.0, 255.0, cv::NORM_MINMAX);
  111. }
  112. cv::Ptr<cv::bioinspired::Retina> retina;
  113. int retinaHcellsGain;
  114. int localAdaptation_photoreceptors, localAdaptation_Gcells;
  115. static void callBack_updateRetinaParams(int, void*)
  116. {
  117. retina->setupOPLandIPLParvoChannel(true, true, (float)(localAdaptation_photoreceptors/200.0), 0.5f, 0.43f, (float)retinaHcellsGain, 1.f, 7.f, (float)(localAdaptation_Gcells/200.0));
  118. }
  119. int colorSaturationFactor;
  120. static void callback_saturateColors(int, void*)
  121. {
  122. retina->setColorSaturation(true, (float)colorSaturationFactor);
  123. }
  124. int main(int argc, char* argv[]) {
  125. // welcome message
  126. std::cout<<"*********************************************************************************"<<std::endl;
  127. std::cout<<"* Retina demonstration for High Dynamic Range compression (tone-mapping) : demonstrates the use of a wrapper class of the Gipsa/Listic Labs retina model."<<std::endl;
  128. std::cout<<"* This retina model allows spatio-temporal image processing (applied on still images, video sequences)."<<std::endl;
  129. std::cout<<"* This demo focuses demonstration of the dynamic compression capabilities of the model"<<std::endl;
  130. std::cout<<"* => the main application is tone mapping of HDR images (i.e. see on a 8bit display a more than 8bits coded (up to 16bits) image with details in high and low luminance ranges"<<std::endl;
  131. std::cout<<"* The retina model still have the following properties:"<<std::endl;
  132. std::cout<<"* => It applies a spectral whithening (mid-frequency details enhancement)"<<std::endl;
  133. std::cout<<"* => high frequency spatio-temporal noise reduction"<<std::endl;
  134. std::cout<<"* => low frequency luminance to be reduced (luminance range compression)"<<std::endl;
  135. std::cout<<"* => local logarithmic luminance compression allows details to be enhanced in low light conditions\n"<<std::endl;
  136. std::cout<<"* for more information, reer to the following papers :"<<std::endl;
  137. std::cout<<"* Benoit A., Caplier A., Durette B., Herault, J., \"USING HUMAN VISUAL SYSTEM MODELING FOR BIO-INSPIRED LOW LEVEL IMAGE PROCESSING\", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773, DOI: http://dx.doi.org/10.1016/j.cviu.2010.01.011"<<std::endl;
  138. std::cout<<"* Vision: Images, Signals and Neural Networks: Models of Neural Processing in Visual Perception (Progress in Neural Processing),By: Jeanny Herault, ISBN: 9814273686. WAPI (Tower ID): 113266891."<<std::endl;
  139. std::cout<<"* => reports comments/remarks at benoit.alexandre.vision@gmail.com"<<std::endl;
  140. std::cout<<"* => more informations and papers at : http://sites.google.com/site/benoitalexandrevision/"<<std::endl;
  141. std::cout<<"*********************************************************************************"<<std::endl;
  142. std::cout<<"** WARNING : this sample requires OpenCV to be configured with OpenEXR support **"<<std::endl;
  143. std::cout<<"*********************************************************************************"<<std::endl;
  144. std::cout<<"*** You can use free tools to generate OpenEXR images from images sets : ***"<<std::endl;
  145. std::cout<<"*** => 1. take a set of photos from the same viewpoint using bracketing ***"<<std::endl;
  146. std::cout<<"*** => 2. generate an OpenEXR image with tools like qtpfsgui.sourceforge.net ***"<<std::endl;
  147. std::cout<<"*** => 3. apply tone mapping with this program ***"<<std::endl;
  148. std::cout<<"*********************************************************************************"<<std::endl;
  149. // basic input arguments checking
  150. if (argc<2)
  151. {
  152. help("bad number of parameter");
  153. return -1;
  154. }
  155. bool useLogSampling = !strcmp(argv[argc-1], "log"); // check if user wants retina log sampling processing
  156. int chosenMethod=0;
  157. if (!strcmp(argv[argc-1], "fast"))
  158. {
  159. chosenMethod=1;
  160. std::cout<<"Using fast method (no spectral whithning), adaptation of Meylan&al 2008 method"<<std::endl;
  161. }
  162. std::string inputImageName=argv[1];
  163. //////////////////////////////////////////////////////////////////////////////
  164. // checking input media type (still image, video file, live video acquisition)
  165. std::cout<<"RetinaDemo: processing image "<<inputImageName<<std::endl;
  166. // image processing case
  167. // declare the retina input buffer... that will be fed differently in regard of the input media
  168. inputImage = cv::imread(inputImageName, -1); // load image in RGB mode
  169. std::cout<<"=> image size (h,w) = "<<inputImage.size().height<<", "<<inputImage.size().width<<std::endl;
  170. if (!inputImage.total())
  171. {
  172. help("could not load image, program end");
  173. return -1;
  174. }
  175. // rescale between 0 and 1
  176. normalize(inputImage, inputImage, 0.0, 1.0, cv::NORM_MINMAX);
  177. cv::Mat gammaTransformedImage;
  178. cv::pow(inputImage, 1./5, gammaTransformedImage); // apply gamma curve: img = img ** (1./5)
  179. imshow("EXR image original image, 16bits=>8bits linear rescaling ", inputImage);
  180. imshow("EXR image with basic processing : 16bits=>8bits with gamma correction", gammaTransformedImage);
  181. if (inputImage.empty())
  182. {
  183. help("Input image could not be loaded, aborting");
  184. return -1;
  185. }
  186. //////////////////////////////////////////////////////////////////////////////
  187. // Program start in a try/catch safety context (Retina may throw errors)
  188. try
  189. {
  190. /* create a retina instance with default parameters setup, uncomment the initialisation you wanna test
  191. * -> if the last parameter is 'log', then activate log sampling (favour foveal vision and subsamples peripheral vision)
  192. */
  193. if (useLogSampling)
  194. {
  195. retina = cv::bioinspired::createRetina(inputImage.size(),true, cv::bioinspired::RETINA_COLOR_BAYER, true, 2.0, 10.0);
  196. }
  197. else// -> else allocate "classical" retina :
  198. retina = cv::bioinspired::createRetina(inputImage.size());
  199. // create a fast retina tone mapper (Meyla&al algorithm)
  200. std::cout<<"Allocating fast tone mapper..."<<std::endl;
  201. //cv::Ptr<cv::RetinaFastToneMapping> fastToneMapper=createRetinaFastToneMapping(inputImage.size());
  202. std::cout<<"Fast tone mapper allocated"<<std::endl;
  203. // save default retina parameters file in order to let you see this and maybe modify it and reload using method "setup"
  204. retina->write("RetinaDefaultParameters.xml");
  205. // desactivate Magnocellular pathway processing (motion information extraction) since it is not useful here
  206. retina->activateMovingContoursProcessing(false);
  207. // declare retina output buffers
  208. cv::Mat retinaOutput_parvo;
  209. /////////////////////////////////////////////
  210. // prepare displays and interactions
  211. histogramClippingValue=0; // default value... updated with interface slider
  212. //inputRescaleMat = inputImage;
  213. //outputRescaleMat = imageInputRescaled;
  214. cv::namedWindow("Processing configuration",1);
  215. cv::createTrackbar("histogram edges clipping limit", "Processing configuration",&histogramClippingValue,50,callBack_rescaleGrayLevelMat);
  216. colorSaturationFactor=3;
  217. cv::createTrackbar("Color saturation", "Processing configuration", &colorSaturationFactor,5,callback_saturateColors);
  218. retinaHcellsGain=40;
  219. cv::createTrackbar("Hcells gain", "Processing configuration",&retinaHcellsGain,100,callBack_updateRetinaParams);
  220. localAdaptation_photoreceptors=197;
  221. localAdaptation_Gcells=190;
  222. cv::createTrackbar("Ph sensitivity", "Processing configuration", &localAdaptation_photoreceptors,199,callBack_updateRetinaParams);
  223. cv::createTrackbar("Gcells sensitivity", "Processing configuration", &localAdaptation_Gcells,199,callBack_updateRetinaParams);
  224. /////////////////////////////////////////////
  225. // apply default parameters of user interaction variables
  226. rescaleGrayLevelMat(inputImage, imageInputRescaled, (float)histogramClippingValue/100);
  227. retina->setColorSaturation(true,(float)colorSaturationFactor);
  228. callBack_updateRetinaParams(1,NULL); // first call for default parameters setup
  229. // processing loop with stop condition
  230. bool continueProcessing=true;
  231. while(continueProcessing)
  232. {
  233. // run retina filter
  234. if (!chosenMethod)
  235. {
  236. retina->run(imageInputRescaled);
  237. // Retrieve and display retina output
  238. retina->getParvo(retinaOutput_parvo);
  239. cv::imshow("Retina input image (with cut edges histogram for basic pixels error avoidance)", imageInputRescaled/255.0);
  240. cv::imshow("Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", retinaOutput_parvo);
  241. cv::imwrite("HDRinput.jpg",imageInputRescaled/255.0);
  242. cv::imwrite("RetinaToneMapping.jpg",retinaOutput_parvo);
  243. }
  244. else
  245. {
  246. // apply the simplified hdr tone mapping method
  247. cv::Mat fastToneMappingOutput;
  248. retina->applyFastToneMapping(imageInputRescaled, fastToneMappingOutput);
  249. cv::imshow("Retina fast tone mapping output : 16bit=>8bit image retina tonemapping", fastToneMappingOutput);
  250. }
  251. /*cv::Mat fastToneMappingOutput_specificObject;
  252. fastToneMapper->setup(3.f, 1.5f, 1.f);
  253. fastToneMapper->applyFastToneMapping(imageInputRescaled, fastToneMappingOutput_specificObject);
  254. cv::imshow("### Retina fast tone mapping output : 16bit=>8bit image retina tonemapping", fastToneMappingOutput_specificObject);
  255. */
  256. cv::waitKey(10);
  257. }
  258. }catch(const cv::Exception& e)
  259. {
  260. std::cerr<<"Error using Retina : "<<e.what()<<std::endl;
  261. }
  262. // Program end message
  263. std::cout<<"Retina demo end"<<std::endl;
  264. return 0;
  265. }