OpenEXRimages_HDR_Retina_toneMapping.cpp 15 KB

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