diff --git a/doc/CMakeLists.txt b/doc/CMakeLists.txt index 70f4809d22..c42c3b1bb1 100644 --- a/doc/CMakeLists.txt +++ b/doc/CMakeLists.txt @@ -17,7 +17,7 @@ if(BUILD_DOCS AND HAVE_SPHINX) set(OPTIONAL_DOC_LIST "") - set(OPENCV2_BASE_MODULES core imgproc highgui video calib3d features2d objdetect ml flann gpu photo stitching nonfree contrib legacy) + set(OPENCV2_BASE_MODULES core imgproc highgui video calib3d features2d objdetect ml flann gpu photo stitching nonfree contrib legacy bioinspired) # build lists of modules to be documented set(OPENCV2_MODULES "") @@ -122,4 +122,4 @@ if(BUILD_DOCS AND HAVE_SPHINX) install(FILES "${f}" DESTINATION "${OPENCV_DOC_INSTALL_PATH}" OPTIONAL) endforeach() -endif() \ No newline at end of file +endif() diff --git a/doc/tutorials/contrib/retina_model/images/retina_TreeHdr_retina.jpg b/doc/tutorials/bioinspired/retina_model/images/retina_TreeHdr_retina.jpg similarity index 100% rename from doc/tutorials/contrib/retina_model/images/retina_TreeHdr_retina.jpg rename to doc/tutorials/bioinspired/retina_model/images/retina_TreeHdr_retina.jpg diff --git a/doc/tutorials/contrib/retina_model/images/retina_TreeHdr_small.jpg b/doc/tutorials/bioinspired/retina_model/images/retina_TreeHdr_small.jpg similarity index 100% rename from doc/tutorials/contrib/retina_model/images/retina_TreeHdr_small.jpg rename to doc/tutorials/bioinspired/retina_model/images/retina_TreeHdr_small.jpg diff --git a/doc/tutorials/contrib/retina_model/images/studentsSample_input.jpg b/doc/tutorials/bioinspired/retina_model/images/studentsSample_input.jpg similarity index 100% rename from doc/tutorials/contrib/retina_model/images/studentsSample_input.jpg rename to doc/tutorials/bioinspired/retina_model/images/studentsSample_input.jpg diff --git a/doc/tutorials/contrib/retina_model/images/studentsSample_magno.jpg b/doc/tutorials/bioinspired/retina_model/images/studentsSample_magno.jpg similarity index 100% rename from doc/tutorials/contrib/retina_model/images/studentsSample_magno.jpg rename to doc/tutorials/bioinspired/retina_model/images/studentsSample_magno.jpg diff --git a/doc/tutorials/contrib/retina_model/images/studentsSample_parvo.jpg b/doc/tutorials/bioinspired/retina_model/images/studentsSample_parvo.jpg similarity index 100% rename from doc/tutorials/contrib/retina_model/images/studentsSample_parvo.jpg rename to doc/tutorials/bioinspired/retina_model/images/studentsSample_parvo.jpg diff --git a/doc/tutorials/contrib/retina_model/retina_model.rst b/doc/tutorials/bioinspired/retina_model/retina_model.rst similarity index 96% rename from doc/tutorials/contrib/retina_model/retina_model.rst rename to doc/tutorials/bioinspired/retina_model/retina_model.rst index 86e13e7324..32081dfd28 100644 --- a/doc/tutorials/contrib/retina_model/retina_model.rst +++ b/doc/tutorials/bioinspired/retina_model/retina_model.rst @@ -107,14 +107,16 @@ This retina filter code includes the research contributions of phd/research coll Code tutorial ============= -Please refer to the original tutorial source code in file *opencv_folder/samples/cpp/tutorial_code/contrib/retina_tutorial.cpp*. +Please refer to the original tutorial source code in file *opencv_folder/samples/cpp/tutorial_code/bioinspired/retina_tutorial.cpp*. -To compile it, assuming OpenCV is correctly installed, use the following command. It requires the opencv_core *(cv::Mat and friends objects management)*, opencv_highgui *(display and image/video read)* and opencv_contrib *(Retina description)* libraries to compile. +**Note :** do not forget that the retina model is included in the following namespace : *cv::bioinspired*. + +To compile it, assuming OpenCV is correctly installed, use the following command. It requires the opencv_core *(cv::Mat and friends objects management)*, opencv_highgui *(display and image/video read)* and opencv_bioinspired *(Retina description)* libraries to compile. .. code-block:: cpp // compile - gcc retina_tutorial.cpp -o Retina_tuto -lopencv_core -lopencv_highgui -lopencv_contrib + gcc retina_tutorial.cpp -o Retina_tuto -lopencv_core -lopencv_highgui -lopencv_bioinspired // Run commands : add 'log' as a last parameter to apply a spatial log sampling (simulates retina sampling) // run on webcam @@ -128,7 +130,7 @@ To compile it, assuming OpenCV is correctly installed, use the following command Here is a code explanation : -Retina definition is present in the contrib package and a simple include allows to use it +Retina definition is present in the bioinspired package and a simple include allows to use it. You can rather use the specific header : *opencv2/bioinspired.hpp* if you prefer but then include the other required openv modules : *opencv2/core.hpp* and *opencv2/highgui.hpp* .. code-block:: cpp @@ -229,20 +231,20 @@ Once all input parameters are processed, a first image should have been loaded, return -1; } -Now, everything is ready to run the retina model. I propose here to allocate a retina instance and to manage the eventual log sampling option. The Retina constructor expects at least a cv::Size object that shows the input data size that will have to be managed. One can activate other options such as color and its related color multiplexing strategy (here Bayer multiplexing is chosen using enum cv::RETINA_COLOR_BAYER). If using log sampling, the image reduction factor (smaller output images) and log sampling strengh can be adjusted. +Now, everything is ready to run the retina model. I propose here to allocate a retina instance and to manage the eventual log sampling option. The Retina constructor expects at least a cv::Size object that shows the input data size that will have to be managed. One can activate other options such as color and its related color multiplexing strategy (here Bayer multiplexing is chosen using *enum cv::bioinspired::RETINA_COLOR_BAYER*). If using log sampling, the image reduction factor (smaller output images) and log sampling strengh can be adjusted. .. code-block:: cpp // pointer to a retina object - cv::Ptr myRetina; + cv::Ptr myRetina; // if the last parameter is 'log', then activate log sampling (favour foveal vision and subsamples peripheral vision) if (useLogSampling) { - myRetina = cv::createRetina(inputFrame.size(), true, cv::RETINA_COLOR_BAYER, true, 2.0, 10.0); + myRetina = cv::bioinspired::createRetina(inputFrame.size(), true, cv::bioinspired::RETINA_COLOR_BAYER, true, 2.0, 10.0); } else// -> else allocate "classical" retina : - myRetina = cv::createRetina(inputFrame.size()); + myRetina = cv::bioinspired::createRetina(inputFrame.size()); Once done, the proposed code writes a default xml file that contains the default parameters of the retina. This is useful to make your own config using this template. Here generated template xml file is called *RetinaDefaultParameters.xml*. diff --git a/doc/tutorials/bioinspired/retina_model/retina_model.rst~ b/doc/tutorials/bioinspired/retina_model/retina_model.rst~ new file mode 100644 index 0000000000..50bdcbb629 --- /dev/null +++ b/doc/tutorials/bioinspired/retina_model/retina_model.rst~ @@ -0,0 +1,418 @@ +.. _Retina_Model: + +Discovering the human retina and its use for image processing +************************************************************* + +Goal +===== + +I present here a model of human retina that shows some interesting properties for image preprocessing and enhancement. +In this tutorial you will learn how to: + +.. container:: enumeratevisibleitemswithsquare + + + discover the main two channels outing from your retina + + + see the basics to use the retina model + + + discover some parameters tweaks + + +General overview +================ + +The proposed model originates from Jeanny Herault's research [herault2010]_ at `Gipsa `_. It is involved in image processing applications with `Listic `_ (code maintainer and user) lab. This is not a complete model but it already present interesting properties that can be involved for enhanced image processing experience. The model allows the following human retina properties to be used : + +* spectral whitening that has 3 important effects: high spatio-temporal frequency signals canceling (noise), mid-frequencies details enhancement and low frequencies luminance energy reduction. This *all in one* property directly allows visual signals cleaning of classical undesired distortions introduced by image sensors and input luminance range. + +* local logarithmic luminance compression allows details to be enhanced even in low light conditions. + +* decorrelation of the details information (Parvocellular output channel) and transient information (events, motion made available at the Magnocellular output channel). + +The first two points are illustrated below : + +In the figure below, the OpenEXR image sample *CrissyField.exr*, a High Dynamic Range image is shown. In order to make it visible on this web-page, the original input image is linearly rescaled to the classical image luminance range [0-255] and is converted to 8bit/channel format. Such strong conversion hides many details because of too strong local contrasts. Furthermore, noise energy is also strong and pollutes visual information. + +.. image:: images/retina_TreeHdr_small.jpg + :alt: A High dynamic range image linearly rescaled within range [0-255]. + :align: center + +In the following image, applying the ideas proposed in [benoit2010]_, as your retina does, local luminance adaptation, spatial noise removal and spectral whitening work together and transmit accurate information on lower range 8bit data channels. On this picture, noise in significantly removed, local details hidden by strong luminance contrasts are enhanced. Output image keeps its naturalness and visual content is enhanced. Color processing is based on the color multiplexing/demultiplexing method proposed in [chaix2007]_. + +.. image:: images/retina_TreeHdr_retina.jpg + :alt: A High dynamic range image compressed within range [0-255] using the retina. + :align: center + + +*Note :* image sample can be downloaded from the `OpenEXR website `_. Regarding this demonstration, before retina processing, input image has been linearly rescaled within 0-255 keeping its channels float format. 5% of its histogram ends has been cut (mostly removes wrong HDR pixels). Check out the sample *opencv/samples/cpp/OpenEXRimages_HighDynamicRange_Retina_toneMapping.cpp* for similar processing. The following demonstration will only consider classical 8bit/channel images. + +The retina model output channels +================================ + +The retina model presents two outputs that benefit from the above cited behaviors. + +* The first one is called the Parvocellular channel. It is mainly active in the foveal retina area (high resolution central vision with color sensitive photo-receptors), its aim is to provide accurate color vision for visual details remaining static on the retina. On the other hand objects moving on the retina projection are blurred. + +* The second well known channel is the Magnocellular channel. It is mainly active in the retina peripheral vision and send signals related to change events (motion, transient events, etc.). These outing signals also help visual system to focus/center retina on 'transient'/moving areas for more detailed analysis thus improving visual scene context and object classification. + +**NOTE :** regarding the proposed model, contrary to the real retina, we apply these two channels on the entire input images using the same resolution. This allows enhanced visual details and motion information to be extracted on all the considered images... but remember, that these two channels are complementary. For example, if Magnocellular channel gives strong energy in an area, then, the Parvocellular channel is certainly blurred there since there is a transient event. + +As an illustration, we apply in the following the retina model on a webcam video stream of a dark visual scene. In this visual scene, captured in an amphitheater of the university, some students are moving while talking to the teacher. + +In this video sequence, because of the dark ambiance, signal to noise ratio is low and color artifacts are present on visual features edges because of the low quality image capture tool-chain. + +.. image:: images/studentsSample_input.jpg + :alt: an input video stream extract sample + :align: center + +Below is shown the retina foveal vision applied on the entire image. In the used retina configuration, global luminance is preserved and local contrasts are enhanced. Also, signal to noise ratio is improved : since high frequency spatio-temporal noise is reduced, enhanced details are not corrupted by any enhanced noise. + +.. image:: images/studentsSample_parvo.jpg + :alt: the retina Parvocellular output. Enhanced details, luminance adaptation and noise removal. A processing tool for image analysis. + :align: center + +Below is the output of the Magnocellular output of the retina model. Its signals are strong where transient events occur. Here, a student is moving at the bottom of the image thus generating high energy. The remaining of the image is static however, it is corrupted by a strong noise. Here, the retina filters out most of the noise thus generating low false motion area 'alarms'. This channel can be used as a transient/moving areas detector : it would provide relevant information for a low cost segmentation tool that would highlight areas in which an event is occurring. + +.. image:: images/studentsSample_magno.jpg + :alt: the retina Magnocellular output. Enhanced transient signals (motion, etc.). A preprocessing tool for event detection. + :align: center + +Retina use case +=============== + +This model can be used basically for spatio-temporal video effects but also in the aim of : + +* performing texture analysis with enhanced signal to noise ratio and enhanced details robust against input images luminance ranges (check out the Parvocellular retina channel output) + +* performing motion analysis also taking benefit of the previously cited properties. + +Literature +========== +For more information, refer to the following papers : + +.. [benoit2010] 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 + +* Please have a look at the reference work of Jeanny Herault that you can read in his book : + +.. [herault2010] 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. + +This retina filter code includes the research contributions of phd/research collegues from which code has been redrawn by the author : + +* take a look at the *retinacolor.hpp* module to discover Brice Chaix de Lavarene phD color mosaicing/demosaicing and his reference paper: + +.. [chaix2007] B. Chaix de Lavarene, D. Alleysson, B. Durette, J. Herault (2007). "Efficient demosaicing through recursive filtering", IEEE International Conference on Image Processing ICIP 2007 + +* take a look at *imagelogpolprojection.hpp* to discover retina spatial log sampling which originates from Barthelemy Durette phd with Jeanny Herault. A Retina / V1 cortex projection is also proposed and originates from Jeanny's discussions. More informations in the above cited Jeanny Heraults's book. + +Code tutorial +============= + +Please refer to the original tutorial source code in file *opencv_folder/samples/cpp/tutorial_code/bioinspired/retina_tutorial.cpp*. + +**Note :** do not forget that the retina model is included in the following namespace : *cv::bioinspired*. + +To compile it, assuming OpenCV is correctly installed, use the following command. It requires the opencv_core *(cv::Mat and friends objects management)*, opencv_highgui *(display and image/video read)* and opencv_bioinspired *(Retina description)* libraries to compile. + +.. code-block:: cpp + + // compile + gcc retina_tutorial.cpp -o Retina_tuto -lopencv_core -lopencv_highgui -lopencv_bioinspired + + // Run commands : add 'log' as a last parameter to apply a spatial log sampling (simulates retina sampling) + // run on webcam + ./Retina_tuto -video + // run on video file + ./Retina_tuto -video myVideo.avi + // run on an image + ./Retina_tuto -image myPicture.jpg + // run on an image with log sampling + ./Retina_tuto -image myPicture.jpg log + +Here is a code explanation : + +Retina definition is present in the bioinspired package and a simple include allows to use it. You can rather use the specific header : *opencv2/bioinspired.hpp* if you prefer but then include the other required openv modules : *opencv2/core.hpp* and *opencv2/highgui.hpp* + +.. code-block:: cpp + + #include "opencv2/opencv.hpp" + +Provide user some hints to run the program with a help function + +.. code-block:: cpp + + // the help procedure + static void help(std::string errorMessage) + { + std::cout<<"Program init error : "< you can use this to fine tune parameters and load them if you save to file 'RetinaSpecificParameters.xml'"<= 3) + { + std::cout<<"RetinaDemo: processing image "<>inputFrame; + }else + { + // bad command parameter + help("bad command parameter"); + return -1; + } + +Once all input parameters are processed, a first image should have been loaded, if not, display error and stop program : + +.. code-block:: cpp + + if (inputFrame.empty()) + { + help("Input media could not be loaded, aborting"); + return -1; + } + +Now, everything is ready to run the retina model. I propose here to allocate a retina instance and to manage the eventual log sampling option. The Retina constructor expects at least a cv::Size object that shows the input data size that will have to be managed. One can activate other options such as color and its related color multiplexing strategy (here Bayer multiplexing is chosen using *enum cv::bioinspired::RETINA_COLOR_BAYER*). If using log sampling, the image reduction factor (smaller output images) and log sampling strengh can be adjusted. + +.. code-block:: cpp + + // pointer to a retina object + cv::Ptr myRetina; + + // if the last parameter is 'log', then activate log sampling (favour foveal vision and subsamples peripheral vision) + if (useLogSampling) + { + myRetina = cv::bioinspired::createRetina(inputFrame.size(), true, cv::bioinspired::RETINA_COLOR_BAYER, true, 2.0, 10.0); + } + else// -> else allocate "classical" retina : + myRetina = cv::bioinspired::createRetina(inputFrame.size()); + +Once done, the proposed code writes a default xml file that contains the default parameters of the retina. This is useful to make your own config using this template. Here generated template xml file is called *RetinaDefaultParameters.xml*. + +.. code-block:: cpp + + // save default retina parameters file in order to let you see this and maybe modify it and reload using method "setup" + myRetina->write("RetinaDefaultParameters.xml"); + +In the following line, the retina attempts to load another xml file called *RetinaSpecificParameters.xml*. If you created it and introduced your own setup, it will be loaded, in the other case, default retina parameters are used. + +.. code-block:: cpp + + // load parameters if file exists + myRetina->setup("RetinaSpecificParameters.xml"); + +It is not required here but just to show it is possible, you can reset the retina buffers to zero to force it to forget past events. + +.. code-block:: cpp + + // reset all retina buffers (imagine you close your eyes for a long time) + myRetina->clearBuffers(); + +Now, it is time to run the retina ! First create some output buffers ready to receive the two retina channels outputs + +.. code-block:: cpp + + // declare retina output buffers + cv::Mat retinaOutput_parvo; + cv::Mat retinaOutput_magno; + +Then, run retina in a loop, load new frames from video sequence if necessary and get retina outputs back to dedicated buffers. + +.. code-block:: cpp + + // processing loop with no stop condition + while(true) + { + // if using video stream, then, grabbing a new frame, else, input remains the same + if (videoCapture.isOpened()) + videoCapture>>inputFrame; + + // run retina filter on the loaded input frame + myRetina->run(inputFrame); + // Retrieve and display retina output + myRetina->getParvo(retinaOutput_parvo); + myRetina->getMagno(retinaOutput_magno); + cv::imshow("retina input", inputFrame); + cv::imshow("Retina Parvo", retinaOutput_parvo); + cv::imshow("Retina Magno", retinaOutput_magno); + cv::waitKey(10); + } + +That's done ! But if you want to secure the system, take care and manage Exceptions. The retina can throw some when it sees irrelevant data (no input frame, wrong setup, etc.). +Then, i recommend to surround all the retina code by a try/catch system like this : + +.. code-block:: cpp + + try{ + // pointer to a retina object + cv::Ptr myRetina; + [---] + // processing loop with no stop condition + while(true) + { + [---] + } + + }catch(cv::Exception e) + { + std::cerr<<"Error using Retina : "< + +Once done open the configuration file *RetinaDefaultParameters.xml* generated by the demo and let's have a look at it. + +.. code-block:: cpp + + + + + 1 + 1 + 7.5e-01 + 9.0e-01 + 5.7e-01 + 0.01 + 0.5 + 7. + 7.5e-01 + + 1 + 0. + 0. + 7. + 2.0e+00 + 9.5e-01 + 0. + 7. + + +Here are some hints but actually, the best parameter setup depends more on what you want to do with the retina rather than the images input that you give to retina. Apart from the more specific case of High Dynamic Range images (HDR) that require more specific setup for specific luminance compression objective, the retina behaviors should be rather stable from content to content. Note that OpenCV is able to manage such HDR format thanks to the OpenEXR images compatibility. + +Then, if the application target requires details enhancement prior to specific image processing, you need to know if mean luminance information is required or not. If not, the the retina can cancel or significantly reduce its energy thus giving more visibility to higher spatial frequency details. + + +Basic parameters +---------------- + +The most simple parameters are the following : + +* **colorMode** : let the retina process color information (if 1) or gray scale images (if 0). In this last case, only the first channel of the input will be processed. + +* **normaliseOutput** : each channel has this parameter, if value is 1, then the considered channel output is rescaled between 0 and 255. Take care in this case at the Magnocellular output level (motion/transient channel detection). Residual noise will also be rescaled ! + +**Note :** using color requires color channels multiplexing/demultipexing which requires more processing. You can expect much faster processing using gray levels : it would require around 30 product per pixel for all the retina processes and it has recently been parallelized for multicore architectures. + +Photo-receptors parameters +-------------------------- + +The following parameters act on the entry point of the retina - photo-receptors - and impact all the following processes. These sensors are low pass spatio-temporal filters that smooth temporal and spatial data and also adjust there sensitivity to local luminance thus improving details extraction and high frequency noise canceling. + +* **photoreceptorsLocalAdaptationSensitivity** between 0 and 1. Values close to 1 allow high luminance log compression effect at the photo-receptors level. Values closer to 0 give a more linear sensitivity. Increased alone, it can burn the *Parvo (details channel)* output image. If adjusted in collaboration with **ganglionCellsSensitivity** images can be very contrasted whatever the local luminance there is... at the price of a naturalness decrease. + +* **photoreceptorsTemporalConstant** this setups the temporal constant of the low pass filter effect at the entry of the retina. High value lead to strong temporal smoothing effect : moving objects are blurred and can disappear while static object are favored. But when starting the retina processing, stable state is reached lately. + +* **photoreceptorsSpatialConstant** specifies the spatial constant related to photo-receptors low pass filter effect. This parameters specify the minimum allowed spatial signal period allowed in the following. Typically, this filter should cut high frequency noise. Then a 0 value doesn't cut anything noise while higher values start to cut high spatial frequencies and more and more lower frequencies... Then, do not go to high if you wanna see some details of the input images ! A good compromise for color images is 0.53 since this won't affect too much the color spectrum. Higher values would lead to gray and blurred output images. + +Horizontal cells parameters +--------------------------- + +This parameter set tunes the neural network connected to the photo-receptors, the horizontal cells. It modulates photo-receptors sensitivity and completes the processing for final spectral whitening (part of the spatial band pass effect thus favoring visual details enhancement). + +* **horizontalCellsGain** here is a critical parameter ! If you are not interested by the mean luminance and focus on details enhancement, then, set to zero. But if you want to keep some environment luminance data, let some low spatial frequencies pass into the system and set a higher value (<1). + +* **hcellsTemporalConstant** similar to photo-receptors, this acts on the temporal constant of a low pass temporal filter that smooths input data. Here, a high value generates a high retina after effect while a lower value makes the retina more reactive. This value should be lower than **photoreceptorsTemporalConstant** to limit strong retina after effects. + +* **hcellsSpatialConstant** is the spatial constant of the low pass filter of these cells filter. It specifies the lowest spatial frequency allowed in the following. Visually, a high value leads to very low spatial frequencies processing and leads to salient halo effects. Lower values reduce this effect but the limit is : do not go lower than the value of **photoreceptorsSpatialConstant**. Those 2 parameters actually specify the spatial band-pass of the retina. + +**NOTE** after the processing managed by the previous parameters, input data is cleaned from noise and luminance in already partly enhanced. The following parameters act on the last processing stages of the two outing retina signals. + +Parvo (details channel) dedicated parameter +------------------------------------------- + +* **ganglionCellsSensitivity** specifies the strength of the final local adaptation occurring at the output of this details dedicated channel. Parameter values remain between 0 and 1. Low value tend to give a linear response while higher values enforces the remaining low contrasted areas. + +**Note :** this parameter can correct eventual burned images by favoring low energetic details of the visual scene, even in bright areas. + +IPL Magno (motion/transient channel) parameters +----------------------------------------------- + +Once image information is cleaned, this channel acts as a high pass temporal filter that only selects signals related to transient signals (events, motion, etc.). A low pass spatial filter smooths extracted transient data and a final logarithmic compression enhances low transient events thus enhancing event sensitivity. + +* **parasolCells_beta** generally set to zero, can be considered as an amplifier gain at the entry point of this processing stage. Generally set to 0. + +* **parasolCells_tau** the temporal smoothing effect that can be added + +* **parasolCells_k** the spatial constant of the spatial filtering effect, set it at a high value to favor low spatial frequency signals that are lower subject to residual noise. + +* **amacrinCellsTemporalCutFrequency** specifies the temporal constant of the high pass filter. High values let slow transient events to be selected. + +* **V0CompressionParameter** specifies the strength of the log compression. Similar behaviors to previous description but here it enforces sensitivity of transient events. + +* **localAdaptintegration_tau** generally set to 0, no real use here actually + +* **localAdaptintegration_k** specifies the size of the area on which local adaptation is performed. Low values lead to short range local adaptation (higher sensitivity to noise), high values secure log compression. diff --git a/doc/tutorials/contrib/table_of_content_contrib/images/retina_TreeHdr_small.jpg b/doc/tutorials/bioinspired/table_of_content_bioinspired/images/retina_TreeHdr_small.jpg similarity index 100% rename from doc/tutorials/contrib/table_of_content_contrib/images/retina_TreeHdr_small.jpg rename to doc/tutorials/bioinspired/table_of_content_bioinspired/images/retina_TreeHdr_small.jpg diff --git a/doc/tutorials/bioinspired/table_of_content_bioinspired/table_of_content_bioinspired.rst b/doc/tutorials/bioinspired/table_of_content_bioinspired/table_of_content_bioinspired.rst new file mode 100644 index 0000000000..88869e98f9 --- /dev/null +++ b/doc/tutorials/bioinspired/table_of_content_bioinspired/table_of_content_bioinspired.rst @@ -0,0 +1,36 @@ +.. _Table-Of-Content-Bioinspired: + +*bioinspired* module. Algorithms inspired from biological models +---------------------------------------------------------------- + +Here you will learn how to use additional modules of OpenCV defined in the "bioinspired" module. + + .. include:: ../../definitions/tocDefinitions.rst + ++ + .. tabularcolumns:: m{100pt} m{300pt} + .. cssclass:: toctableopencv + + =============== ====================================================== + |RetinaDemoImg| **Title:** :ref:`Retina_Model` + + *Compatibility:* > OpenCV 2.4 + + *Author:* |Author_AlexB| + + You will learn how to process images and video streams with a model of retina filter for details enhancement, spatio-temporal noise removal, luminance correction and spatio-temporal events detection. + + =============== ====================================================== + + .. |RetinaDemoImg| image:: images/retina_TreeHdr_small.jpg + :height: 90pt + :width: 90pt + + .. raw:: latex + + \pagebreak + +.. toctree:: + :hidden: + + ../retina_model/retina_model diff --git a/doc/tutorials/contrib/table_of_content_contrib/table_of_content_contrib.rst b/doc/tutorials/bioinspired/table_of_content_bioinspired/table_of_content_bioinspired.rst~ similarity index 100% rename from doc/tutorials/contrib/table_of_content_contrib/table_of_content_contrib.rst rename to doc/tutorials/bioinspired/table_of_content_bioinspired/table_of_content_bioinspired.rst~ diff --git a/doc/tutorials/tutorials.rst b/doc/tutorials/tutorials.rst index cbc51c1956..07bc515d53 100644 --- a/doc/tutorials/tutorials.rst +++ b/doc/tutorials/tutorials.rst @@ -156,17 +156,17 @@ As always, we would be happy to hear your comments and receive your contribution :width: 80pt :alt: gpu icon -* :ref:`Table-Of-Content-Contrib` +* :ref:`Table-Of-Content-Bioinspired` .. tabularcolumns:: m{100pt} m{300pt} .. cssclass:: toctableopencv - =========== ======================================================= - |Contrib| Discover additional contribution to OpenCV. + ============= ======================================================= + |Bioinspired| Algorithms inspired from biological models. - =========== ======================================================= + ============= ======================================================= - .. |Contrib| image:: images/retina.jpg + .. |Bioinspired| image:: images/retina.jpg :height: 80pt :width: 80pt :alt: gpu icon @@ -219,6 +219,6 @@ As always, we would be happy to hear your comments and receive your contribution objdetect/table_of_content_objdetect/table_of_content_objdetect ml/table_of_content_ml/table_of_content_ml gpu/table_of_content_gpu/table_of_content_gpu - contrib/table_of_content_contrib/table_of_content_contrib + bioinspired/table_of_content_bioinspired/table_of_content_bioinspired ios/table_of_content_ios/table_of_content_ios general/table_of_content_general/table_of_content_general diff --git a/include/opencv2/opencv.hpp b/include/opencv2/opencv.hpp index 020a45373a..3b96bdd368 100644 --- a/include/opencv2/opencv.hpp +++ b/include/opencv2/opencv.hpp @@ -52,6 +52,7 @@ #include "opencv2/calib3d.hpp" #include "opencv2/highgui.hpp" #include "opencv2/contrib.hpp" +#include "opencv2/bioinspired.hpp" #include "opencv2/ml.hpp" #endif diff --git a/modules/bioinspired/CMakeLists.txt b/modules/bioinspired/CMakeLists.txt new file mode 100644 index 0000000000..a27ad73d06 --- /dev/null +++ b/modules/bioinspired/CMakeLists.txt @@ -0,0 +1,2 @@ +set(the_description "Biologically inspired algorithms") +ocv_define_module(bioinspired opencv_core OPTIONAL opencv_highgui) diff --git a/modules/bioinspired/doc/bioinspired.rst b/modules/bioinspired/doc/bioinspired.rst new file mode 100644 index 0000000000..6bffcdcf28 --- /dev/null +++ b/modules/bioinspired/doc/bioinspired.rst @@ -0,0 +1,10 @@ +******************************************************************** +bioinspired. Biologically inspired vision models and derivated tools +******************************************************************** + +The module provides biological visual systems models (human visual system and others). It also provides derivated objects that take advantage of those bio-inspired models. + +.. toctree:: + :maxdepth: 2 + + Human retina documentation diff --git a/modules/contrib/doc/retina/images/retinaInput.jpg b/modules/bioinspired/doc/retina/images/retinaInput.jpg similarity index 100% rename from modules/contrib/doc/retina/images/retinaInput.jpg rename to modules/bioinspired/doc/retina/images/retinaInput.jpg diff --git a/modules/contrib/doc/retina/images/retinaOutput_default.jpg b/modules/bioinspired/doc/retina/images/retinaOutput_default.jpg similarity index 100% rename from modules/contrib/doc/retina/images/retinaOutput_default.jpg rename to modules/bioinspired/doc/retina/images/retinaOutput_default.jpg diff --git a/modules/contrib/doc/retina/images/retinaOutput_realistic.jpg b/modules/bioinspired/doc/retina/images/retinaOutput_realistic.jpg similarity index 100% rename from modules/contrib/doc/retina/images/retinaOutput_realistic.jpg rename to modules/bioinspired/doc/retina/images/retinaOutput_realistic.jpg diff --git a/modules/contrib/doc/retina/index.rst b/modules/bioinspired/doc/retina/index.rst similarity index 88% rename from modules/contrib/doc/retina/index.rst rename to modules/bioinspired/doc/retina/index.rst index 5671df77cd..608a93542d 100644 --- a/modules/contrib/doc/retina/index.rst +++ b/modules/bioinspired/doc/retina/index.rst @@ -7,6 +7,8 @@ Retina ====== .. ocv:class:: Retina : public Algorithm +**Note** : do not forget that the retina model is included in the following namespace : *cv::bioinspired*. + Introduction ++++++++++++ @@ -17,7 +19,7 @@ Class which provides the main controls to the Gipsa/Listic labs human retina mo * peripheral vision for sensitive transient signals detection (motion and events) : the magnocellular pathway. From a general point of view, this filter whitens the image spectrum and corrects luminance thanks to local adaptation. An other important property is its hability to filter out spatio-temporal noise while enhancing details. -This model originates from Jeanny Herault work [Herault2010]_. It has been involved in Alexandre Benoit phd and his current research [Benoit2010]_ (he currently maintains this module within OpenCV). It includes the work of other Jeanny's phd student such as [Chaix2007]_ and the log polar transformations of Barthelemy Durette described in Jeanny's book. +This model originates from Jeanny Herault work [Herault2010]_. It has been involved in Alexandre Benoit phd and his current research [Benoit2010]_, [Strat2013]_ (he currently maintains this module within OpenCV). It includes the work of other Jeanny's phd student such as [Chaix2007]_ and the log polar transformations of Barthelemy Durette described in Jeanny's book. **NOTES :** @@ -55,15 +57,20 @@ As observed in this preliminary demo, the retina can be settled up with various Here is an overview of the abstract Retina interface, allocate one instance with the *createRetina* functions.:: + namespace cv{namespace bioinspired{ + class Retina : public Algorithm { public: // parameters setup instance struct RetinaParameters; // this class is detailled later - // main method for input frame processing + // main method for input frame processing (all use method, can also perform High Dynamic Range tone mapping) void run (InputArray inputImage); + // specific method aiming at correcting luminance only (faster High Dynamic Range tone mapping) + void applyFastToneMapping(InputArray inputImage, OutputArray outputToneMappedImage) + // output buffers retreival methods // -> foveal color vision details channel with luminance and noise correction void getParvo (OutputArray retinaOutput_parvo); @@ -99,7 +106,7 @@ Here is an overview of the abstract Retina interface, allocate one instance with // Allocators cv::Ptr createRetina (Size inputSize); cv::Ptr createRetina (Size inputSize, const bool colorMode, RETINA_COLORSAMPLINGMETHOD colorSamplingMethod=RETINA_COLOR_BAYER, const bool useRetinaLogSampling=false, const double reductionFactor=1.0, const double samplingStrenght=10.0); - + }} // cv and bioinspired namespaces end Description +++++++++++ @@ -120,12 +127,20 @@ Use : this model can be used basically for spatio-temporal video effects but als * performing motion analysis also taking benefit of the previously cited properties (check out the magnocellular retina channel output, by using the provided **getMagno** methods) +* general image/video sequence description using either one or both channels. An example of the use of Retina in a Bag of Words approach is given in [Strat2013]_. + Literature ========== For more information, refer to the following papers : +* Model description : + .. [Benoit2010] 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 +* Model use in a Bag of Words approach : + +.. [Strat2013] Strat S., Benoit A., Lambert P., "Retina enhanced SIFT descriptors for video indexing", CBMI2013, Veszprém, Hungary, 2013. + * Please have a look at the reference work of Jeanny Herault that you can read in his book : .. [Herault2010] 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. @@ -138,6 +153,10 @@ This retina filter code includes the research contributions of phd/research coll * take a look at *imagelogpolprojection.hpp* to discover retina spatial log sampling which originates from Barthelemy Durette phd with Jeanny Herault. A Retina / V1 cortex projection is also proposed and originates from Jeanny's discussions. More informations in the above cited Jeanny Heraults's book. +* Meylan&al work on HDR tone mapping that is implemented as a specific method within the model : + +.. [Meylan2007] L. Meylan , D. Alleysson, S. Susstrunk, "A Model of Retinal Local Adaptation for the Tone Mapping of Color Filter Array Images", Journal of Optical Society of America, A, Vol. 24, N 9, September, 1st, 2007, pp. 2807-2816 + Demos and experiments ! ======================= @@ -161,12 +180,14 @@ Take a look at the provided C++ examples provided with OpenCV : Then, take a HDR image using bracketing with your camera and generate an OpenEXR image and then process it using the demo. - Typical use, supposing that you have the OpenEXR image *memorial.exr* (present in the samples/cpp/ folder) + Typical use, supposing that you have the OpenEXR image such as *memorial.exr* (present in the samples/cpp/ folder) - **OpenCVReleaseFolder/bin/OpenEXRimages_HighDynamicRange_Retina_toneMapping memorial.exr** + **OpenCVReleaseFolder/bin/OpenEXRimages_HighDynamicRange_Retina_toneMapping memorial.exr [optionnal: 'fast']** Note that some sliders are made available to allow you to play with luminance compression. + If not using the 'fast' option, then, tone mapping is performed using the full retina model [Benoit2010]_. It includes spectral whitening that allows luminance energy to be reduced. When using the 'fast' option, then, a simpler method is used, it is an adaptation of the algorithm presented in [Meylan2007]_. This method gives also good results and is faster to process but it sometimes requires some more parameters adjustement. + Methods description =================== @@ -176,8 +197,8 @@ Here are detailled the main methods to control the retina model Ptr::createRetina +++++++++++++++++++++++++ -.. ocv:function:: Ptr createRetina(Size inputSize) -.. ocv:function:: Ptr createRetina(Size inputSize, const bool colorMode, RETINA_COLORSAMPLINGMETHOD colorSamplingMethod = RETINA_COLOR_BAYER, const bool useRetinaLogSampling = false, const double reductionFactor = 1.0, const double samplingStrenght = 10.0 ) +.. ocv:function:: Ptr createRetina(Size inputSize) +.. ocv:function:: Ptr createRetina(Size inputSize, const bool colorMode, cv::bioinspired::RETINA_COLORSAMPLINGMETHOD colorSamplingMethod = cv::bioinspired::RETINA_COLOR_BAYER, const bool useRetinaLogSampling = false, const double reductionFactor = 1.0, const double samplingStrenght = 10.0 ) Constructors from standardized interfaces : retreive a smart pointer to a Retina instance @@ -185,11 +206,11 @@ Ptr::createRetina :param colorMode: the chosen processing mode : with or without color processing :param colorSamplingMethod: specifies which kind of color sampling will be used : - * RETINA_COLOR_RANDOM: each pixel position is either R, G or B in a random choice + * cv::bioinspired::RETINA_COLOR_RANDOM: each pixel position is either R, G or B in a random choice - * RETINA_COLOR_DIAGONAL: color sampling is RGBRGBRGB..., line 2 BRGBRGBRG..., line 3, GBRGBRGBR... + * cv::bioinspired::RETINA_COLOR_DIAGONAL: color sampling is RGBRGBRGB..., line 2 BRGBRGBRG..., line 3, GBRGBRGBR... - * RETINA_COLOR_BAYER: standard bayer sampling + * cv::bioinspired::RETINA_COLOR_BAYER: standard bayer sampling :param useRetinaLogSampling: activate retina log sampling, if true, the 2 following parameters can be used :param reductionFactor: only usefull if param useRetinaLogSampling=true, specifies the reduction factor of the output frame (as the center (fovea) is high resolution and corners can be underscaled, then a reduction of the output is allowed without precision leak @@ -275,7 +296,7 @@ Retina::printSetup Outputs a string showing the used parameters setup - :return: a string which contains formatted parameters information + :return: a string which contains formated parameters information Retina::run +++++++++++ @@ -286,6 +307,18 @@ Retina::run :param inputImage: the input Mat image to be processed, can be gray level or BGR coded in any format (from 8bit to 16bits) +Retina::applyFastToneMapping +++++++++++++++++++++++++++++ + +.. ocv:function:: void Retina::applyFastToneMapping(InputArray inputImage, OutputArray outputToneMappedImage) + + Method which processes an image in the aim to correct its luminance : correct backlight problems, enhance details in shadows. This method is designed to perform High Dynamic Range image tone mapping (compress >8bit/pixel images to 8bit/pixel). This is a simplified version of the Retina Parvocellular model (simplified version of the run/getParvo methods call) since it does not include the spatio-temporal filter modelling the Outer Plexiform Layer of the retina that performs spectral whitening and many other stuff. However, it works great for tone mapping and in a faster way. + + Check the demos and experiments section to see examples and the way to perform tone mapping using the original retina model and the method. + + :param inputImage: the input image to process (should be coded in float format : CV_32F, CV_32FC1, CV_32F_C3, CV_32F_C4, the 4th channel won't be considered). + :param outputToneMappedImage: the output 8bit/channel tone mapped image (CV_8U or CV_8UC3 format). + Retina::setColorSaturation ++++++++++++++++++++++++++ diff --git a/modules/bioinspired/include/opencv2/bioinspired.hpp b/modules/bioinspired/include/opencv2/bioinspired.hpp new file mode 100644 index 0000000000..5f2f8644d2 --- /dev/null +++ b/modules/bioinspired/include/opencv2/bioinspired.hpp @@ -0,0 +1,50 @@ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef __OPENCV_BIOINSPIRED_HPP__ +#define __OPENCV_BIOINSPIRED_HPP__ + +#include "opencv2/core.hpp" +#include "opencv2/bioinspired/retina.hpp" +#include "opencv2/bioinspired/retinafasttonemapping.hpp" + +#endif diff --git a/modules/bioinspired/include/opencv2/bioinspired/bioinspired.hpp b/modules/bioinspired/include/opencv2/bioinspired/bioinspired.hpp new file mode 100644 index 0000000000..40be2854eb --- /dev/null +++ b/modules/bioinspired/include/opencv2/bioinspired/bioinspired.hpp @@ -0,0 +1,48 @@ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/bioinspired.hpp" diff --git a/modules/contrib/include/opencv2/contrib/retina.hpp b/modules/bioinspired/include/opencv2/bioinspired/retina.hpp similarity index 91% rename from modules/contrib/include/opencv2/contrib/retina.hpp rename to modules/bioinspired/include/opencv2/bioinspired/retina.hpp index 579c15d1dc..4b4c19f90a 100644 --- a/modules/contrib/include/opencv2/contrib/retina.hpp +++ b/modules/bioinspired/include/opencv2/bioinspired/retina.hpp @@ -6,12 +6,12 @@ ** copy or use the software. ** ** - ** HVStools : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. + ** bioinspired : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. ** Use: extract still images & image sequences features, from contours details to motion spatio-temporal features, etc. for high level visual scene analysis. Also contribute to image enhancement/compression such as tone mapping. ** ** Maintainers : Listic lab (code author current affiliation & applications) and Gipsa Lab (original research origins & applications) ** - ** Creation - enhancement process 2007-2011 + ** Creation - enhancement process 2007-2013 ** Author: Alexandre Benoit (benoit.alexandre.vision@gmail.com), LISTIC lab, Annecy le vieux, France ** ** Theses algorithm have been developped by Alexandre BENOIT since his thesis with Alice Caplier at Gipsa-Lab (www.gipsa-lab.inpg.fr) and the research he pursues at LISTIC Lab (www.listic.univ-savoie.fr). @@ -32,7 +32,7 @@ ** Copyright (C) 2000-2008, Intel Corporation, all rights reserved. ** Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved. ** - ** For Human Visual System tools (hvstools) + ** For Human Visual System tools (bioinspired) ** Copyright (C) 2007-2011, LISTIC Lab, Annecy le Vieux and GIPSA Lab, Grenoble, France, all rights reserved. ** ** Third party copyrights are property of their respective owners. @@ -62,8 +62,8 @@ ** the use of this software, even if advised of the possibility of such damage. *******************************************************************************/ -#ifndef __OPENCV_CONTRIB_RETINA_HPP__ -#define __OPENCV_CONTRIB_RETINA_HPP__ +#ifndef __OPENCV_BIOINSPIRED_RETINA_HPP__ +#define __OPENCV_BIOINSPIRED_RETINA_HPP__ /* * Retina.hpp @@ -73,13 +73,12 @@ */ #include "opencv2/core.hpp" // for all OpenCV core functionalities access, including cv::Exception support -#include -namespace cv -{ -enum RETINA_COLORSAMPLINGMETHOD -{ +namespace cv{ +namespace bioinspired{ + +enum { RETINA_COLOR_RANDOM, //!< each pixel position is either R, G or B in a random choice RETINA_COLOR_DIAGONAL,//!< color sampling is RGBRGBRGB..., line 2 BRGBRGBRG..., line 3, GBRGBRGBR... RETINA_COLOR_BAYER//!< standard bayer sampling @@ -241,6 +240,14 @@ public: */ virtual void run(InputArray inputImage)=0; + /** + * method that applies a luminance correction (initially High Dynamic Range (HDR) tone mapping) using only the 2 local adaptation stages of the retina parvo channel : photoreceptors level and ganlion cells level. Spatio temporal filtering is applied but limited to temporal smoothing and eventually high frequencies attenuation. This is a lighter method than the one available using the regular run method. It is then faster but it does not include complete temporal filtering nor retina spectral whitening. Then, it can have a more limited effect on images with a very high dynamic range. This is an adptation of the original still image HDR tone mapping algorithm of David Alleyson, Sabine Susstruck and Laurence Meylan's work, please cite: + * -> Meylan L., Alleysson D., and Susstrunk S., A Model of Retinal Local Adaptation for the Tone Mapping of Color Filter Array Images, Journal of Optical Society of America, A, Vol. 24, N 9, September, 1st, 2007, pp. 2807-2816 + @param inputImage the input image to process RGB or gray levels + @param outputToneMappedImage the output tone mapped image + */ + virtual void applyFastToneMapping(InputArray inputImage, OutputArray outputToneMappedImage)=0; + /** * accessor of the details channel of the retina (models foveal vision) * @param retinaOutput_parvo : the output buffer (reallocated if necessary), this output is rescaled for standard 8bits image processing use in OpenCV @@ -295,8 +302,9 @@ public: virtual void activateContoursProcessing(const bool activate)=0; }; CV_EXPORTS Ptr createRetina(Size inputSize); -CV_EXPORTS Ptr createRetina(Size inputSize, const bool colorMode, RETINA_COLORSAMPLINGMETHOD colorSamplingMethod=RETINA_COLOR_BAYER, const bool useRetinaLogSampling=false, const double reductionFactor=1.0, const double samplingStrenght=10.0); +CV_EXPORTS Ptr createRetina(Size inputSize, const bool colorMode, int colorSamplingMethod=RETINA_COLOR_BAYER, const bool useRetinaLogSampling=false, const double reductionFactor=1.0, const double samplingStrenght=10.0); + } -#endif /* __OPENCV_CONTRIB_RETINA_HPP__ */ - +} +#endif /* __OPENCV_BIOINSPIRED_RETINA_HPP__ */ diff --git a/modules/bioinspired/include/opencv2/bioinspired/retinafasttonemapping.hpp b/modules/bioinspired/include/opencv2/bioinspired/retinafasttonemapping.hpp new file mode 100644 index 0000000000..6c83f885c8 --- /dev/null +++ b/modules/bioinspired/include/opencv2/bioinspired/retinafasttonemapping.hpp @@ -0,0 +1,121 @@ + +/*#****************************************************************************** + ** IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. + ** + ** By downloading, copying, installing or using the software you agree to this license. + ** If you do not agree to this license, do not download, install, + ** copy or use the software. + ** + ** + ** bioinspired : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. + ** + ** Maintainers : Listic lab (code author current affiliation & applications) and Gipsa Lab (original research origins & applications) + ** + ** Creation - enhancement process 2007-2013 + ** Author: Alexandre Benoit (benoit.alexandre.vision@gmail.com), LISTIC lab, Annecy le vieux, France + ** + ** Theses algorithm have been developped by Alexandre BENOIT since his thesis with Alice Caplier at Gipsa-Lab (www.gipsa-lab.inpg.fr) and the research he pursues at LISTIC Lab (www.listic.univ-savoie.fr). + ** Refer to the following research paper for more information: + ** 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 + ** This work have been carried out thanks to Jeanny Herault who's research and great discussions are the basis of all this work, please take a look at his book: + ** 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. + ** + ** + ** + ** + ** + ** This class is based on image processing tools of the author and already used within the Retina class (this is the same code as method retina::applyFastToneMapping, but in an independent class, it is ligth from a memory requirement point of view). It implements an adaptation of the efficient tone mapping algorithm propose by David Alleyson, Sabine Susstruck and Laurence Meylan's work, please cite: + ** -> Meylan L., Alleysson D., and Susstrunk S., A Model of Retinal Local Adaptation for the Tone Mapping of Color Filter Array Images, Journal of Optical Society of America, A, Vol. 24, N 9, September, 1st, 2007, pp. 2807-2816 + ** + ** + ** License Agreement + ** For Open Source Computer Vision Library + ** + ** Copyright (C) 2000-2008, Intel Corporation, all rights reserved. + ** Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved. + ** + ** For Human Visual System tools (bioinspired) + ** Copyright (C) 2007-2011, LISTIC Lab, Annecy le Vieux and GIPSA Lab, Grenoble, France, all rights reserved. + ** + ** Third party copyrights are property of their respective owners. + ** + ** Redistribution and use in source and binary forms, with or without modification, + ** are permitted provided that the following conditions are met: + ** + ** * Redistributions of source code must retain the above copyright notice, + ** this list of conditions and the following disclaimer. + ** + ** * Redistributions in binary form must reproduce the above copyright notice, + ** this list of conditions and the following disclaimer in the documentation + ** and/or other materials provided with the distribution. + ** + ** * The name of the copyright holders may not be used to endorse or promote products + ** derived from this software without specific prior written permission. + ** + ** This software is provided by the copyright holders and contributors "as is" and + ** any express or implied warranties, including, but not limited to, the implied + ** warranties of merchantability and fitness for a particular purpose are disclaimed. + ** In no event shall the Intel Corporation or contributors be liable for any direct, + ** indirect, incidental, special, exemplary, or consequential damages + ** (including, but not limited to, procurement of substitute goods or services; + ** loss of use, data, or profits; or business interruption) however caused + ** and on any theory of liability, whether in contract, strict liability, + ** or tort (including negligence or otherwise) arising in any way out of + ** the use of this software, even if advised of the possibility of such damage. + *******************************************************************************/ + +#ifndef __OPENCV_BIOINSPIRED_RETINAFASTTONEMAPPING_HPP__ +#define __OPENCV_BIOINSPIRED_RETINAFASTTONEMAPPING_HPP__ + +/* + * retinafasttonemapping.hpp + * + * Created on: May 26, 2013 + * Author: Alexandre Benoit + */ + +#include "opencv2/core.hpp" // for all OpenCV core functionalities access, including cv::Exception support + +namespace cv{ +namespace bioinspired{ + +/** + * @class RetinaFastToneMappingImpl a wrapper class which allows the tone mapping algorithm of Meylan&al(2007) to be used with OpenCV. + * This algorithm is already implemented in thre Retina class (retina::applyFastToneMapping) but used it does not require all the retina model to be allocated. This allows a light memory use for low memory devices (smartphones, etc. + * As a summary, these are the model properties: + * => 2 stages of local luminance adaptation with a different local neighborhood for each. + * => first stage models the retina photorecetors local luminance adaptation + * => second stage models th ganglion cells local information adaptation + * => compared to the initial publication, this class uses spatio-temporal low pass filters instead of spatial only filters. + * ====> this can help noise robustness and temporal stability for video sequence use cases. + * for more information, read to the following papers : + * Meylan L., Alleysson D., and Susstrunk S., A Model of Retinal Local Adaptation for the Tone Mapping of Color Filter Array Images, Journal of Optical Society of America, A, Vol. 24, N 9, September, 1st, 2007, pp. 2807-2816Benoit 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 + * regarding spatio-temporal filter and the bigger retina model : + * 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. + */ +class CV_EXPORTS RetinaFastToneMapping : public Algorithm +{ +public: + + /** + * method that applies a luminance correction (initially High Dynamic Range (HDR) tone mapping) using only the 2 local adaptation stages of the retina parvocellular channel : photoreceptors level and ganlion cells level. Spatio temporal filtering is applied but limited to temporal smoothing and eventually high frequencies attenuation. This is a lighter method than the one available using the regular retina::run method. It is then faster but it does not include complete temporal filtering nor retina spectral whitening. Then, it can have a more limited effect on images with a very high dynamic range. This is an adptation of the original still image HDR tone mapping algorithm of David Alleyson, Sabine Susstruck and Laurence Meylan's work, please cite: + * -> Meylan L., Alleysson D., and Susstrunk S., A Model of Retinal Local Adaptation for the Tone Mapping of Color Filter Array Images, Journal of Optical Society of America, A, Vol. 24, N 9, September, 1st, 2007, pp. 2807-2816 + @param inputImage the input image to process RGB or gray levels + @param outputToneMappedImage the output tone mapped image + */ + virtual void applyFastToneMapping(InputArray inputImage, OutputArray outputToneMappedImage)=0; + + /** + * setup method that updates tone mapping behaviors by adjusing the local luminance computation area + * @param photoreceptorsNeighborhoodRadius the first stage local adaptation area + * @param ganglioncellsNeighborhoodRadius the second stage local adaptation area + * @param meanLuminanceModulatorK the factor applied to modulate the meanLuminance information (default is 1, see reference paper) + */ + virtual void setup(const float photoreceptorsNeighborhoodRadius=3.f, const float ganglioncellsNeighborhoodRadius=1.f, const float meanLuminanceModulatorK=1.f)=0; +}; + +CV_EXPORTS Ptr createRetinaFastToneMapping(Size inputSize); + +} +} +#endif /* __OPENCV_BIOINSPIRED_RETINAFASTTONEMAPPING_HPP__ */ diff --git a/modules/contrib/src/basicretinafilter.cpp b/modules/bioinspired/src/basicretinafilter.cpp similarity index 98% rename from modules/contrib/src/basicretinafilter.cpp rename to modules/bioinspired/src/basicretinafilter.cpp index 020b8f04e1..7e7b467faa 100644 --- a/modules/contrib/src/basicretinafilter.cpp +++ b/modules/bioinspired/src/basicretinafilter.cpp @@ -6,7 +6,7 @@ ** copy or use the software. ** ** -** HVStools : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. +** bioinspired : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. ** Use: extract still images & image sequences features, from contours details to motion spatio-temporal features, etc. for high level visual scene analysis. Also contribute to image enhancement/compression such as tone mapping. ** ** Maintainers : Listic lab (code author current affiliation & applications) and Gipsa Lab (original research origins & applications) @@ -32,7 +32,7 @@ ** Copyright (C) 2000-2008, Intel Corporation, all rights reserved. ** Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved. ** -** For Human Visual System tools (hvstools) +** For Human Visual System tools (bioinspired) ** Copyright (C) 2007-2011, LISTIC Lab, Annecy le Vieux and GIPSA Lab, Grenoble, France, all rights reserved. ** ** Third party copyrights are property of their respective owners. @@ -72,7 +72,8 @@ namespace cv { - +namespace bioinspired +{ // @author Alexandre BENOIT, benoit.alexandre.vision@gmail.com, LISTIC : www.listic.univ-savoie.fr Gipsa-Lab, France: www.gipsa-lab.inpg.fr/ ////////////////////////////////////////////////////////// @@ -883,4 +884,5 @@ void BasicRetinaFilter::_verticalAnticausalFilter_Irregular_multGain(float *outp } } -} +}// end of namespace bioinspired +}// end of namespace cv diff --git a/modules/contrib/src/basicretinafilter.hpp b/modules/bioinspired/src/basicretinafilter.hpp similarity index 98% rename from modules/contrib/src/basicretinafilter.hpp rename to modules/bioinspired/src/basicretinafilter.hpp index a2ece415db..323bff9408 100644 --- a/modules/contrib/src/basicretinafilter.hpp +++ b/modules/bioinspired/src/basicretinafilter.hpp @@ -6,7 +6,7 @@ ** copy or use the software. ** ** -** HVStools : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. +** bioinspired : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. ** Use: extract still images & image sequences features, from contours details to motion spatio-temporal features, etc. for high level visual scene analysis. Also contribute to image enhancement/compression such as tone mapping. ** ** Maintainers : Listic lab (code author current affiliation & applications) and Gipsa Lab (original research origins & applications) @@ -32,7 +32,7 @@ ** Copyright (C) 2000-2008, Intel Corporation, all rights reserved. ** Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved. ** -** For Human Visual System tools (hvstools) +** For Human Visual System tools (bioinspired) ** Copyright (C) 2007-2011, LISTIC Lab, Annecy le Vieux and GIPSA Lab, Grenoble, France, all rights reserved. ** ** Third party copyrights are property of their respective owners. @@ -113,6 +113,8 @@ //#define __BASIC_RETINA_ELEMENT_DEBUG namespace cv +{ +namespace bioinspired { class BasicRetinaFilter { @@ -287,7 +289,7 @@ namespace cv * @param maxInputValue: the maximum amplitude value measured after local adaptation processing (c.f. function runFilter_LocalAdapdation & runFilter_LocalAdapdation_autonomous) * @param meanLuminance: the a priori meann luminance of the input data (should be 128 for 8bits images but can vary greatly in case of High Dynamic Range Images (HDRI) */ - void setV0CompressionParameterToneMapping(const float v0, const float maxInputValue, const float meanLuminance=128.0f){ _v0=v0*maxInputValue; _localLuminanceFactor=1.0f; _localLuminanceAddon=meanLuminance*_v0; _maxInputValue=maxInputValue;}; + void setV0CompressionParameterToneMapping(const float v0, const float maxInputValue, const float meanLuminance=128.0f){ _v0=v0*maxInputValue; _localLuminanceFactor=1.0f; _localLuminanceAddon=meanLuminance*v0; _maxInputValue=maxInputValue;}; /** * update compression parameters while keeping v0 parameter value @@ -650,7 +652,6 @@ namespace cv }; -} +}// end of namespace bioinspired +}// end of namespace cv #endif - - diff --git a/modules/contrib/src/imagelogpolprojection.cpp b/modules/bioinspired/src/imagelogpolprojection.cpp similarity index 98% rename from modules/contrib/src/imagelogpolprojection.cpp rename to modules/bioinspired/src/imagelogpolprojection.cpp index 22f5214e7c..0a4c1ed0de 100644 --- a/modules/contrib/src/imagelogpolprojection.cpp +++ b/modules/bioinspired/src/imagelogpolprojection.cpp @@ -6,7 +6,7 @@ ** copy or use the software. ** ** -** HVStools : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. +** bioinspired : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. ** Use: extract still images & image sequences features, from contours details to motion spatio-temporal features, etc. for high level visual scene analysis. Also contribute to image enhancement/compression such as tone mapping. ** ** Maintainers : Listic lab (code author current affiliation & applications) and Gipsa Lab (original research origins & applications) @@ -32,7 +32,7 @@ ** Copyright (C) 2000-2008, Intel Corporation, all rights reserved. ** Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved. ** -** For Human Visual System tools (hvstools) +** For Human Visual System tools (bioinspired) ** Copyright (C) 2007-2011, LISTIC Lab, Annecy le Vieux and GIPSA Lab, Grenoble, France, all rights reserved. ** ** Third party copyrights are property of their respective owners. @@ -72,7 +72,8 @@ namespace cv { - +namespace bioinspired +{ // constructor ImageLogPolProjection::ImageLogPolProjection(const unsigned int nbRows, const unsigned int nbColumns, const PROJECTIONTYPE projection, const bool colorModeCapable) :BasicRetinaFilter(nbRows, nbColumns), @@ -446,4 +447,5 @@ std::valarray &ImageLogPolProjection::runProjection(const std::valarray &MagnoRetinaFilter::runFilter(const std::valarray +namespace cv +{ + +// special function to get pointer to constant valarray elements, since +// simple &arr[0] does not compile on VS2005/VS2008. +template inline const T* get_data(const std::valarray& arr) +{ return &((std::valarray&)arr)[0]; } + +} + +#endif diff --git a/modules/contrib/src/retina.cpp b/modules/bioinspired/src/retina.cpp similarity index 89% rename from modules/contrib/src/retina.cpp rename to modules/bioinspired/src/retina.cpp index de752c024c..2ec7286bcd 100644 --- a/modules/contrib/src/retina.cpp +++ b/modules/bioinspired/src/retina.cpp @@ -6,7 +6,7 @@ ** copy or use the software. ** ** - ** HVStools : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. + ** bioinspired : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. ** Use: extract still images & image sequences features, from contours details to motion spatio-temporal features, etc. for high level visual scene analysis. Also contribute to image enhancement/compression such as tone mapping. ** ** Maintainers : Listic lab (code author current affiliation & applications) and Gipsa Lab (original research origins & applications) @@ -32,7 +32,7 @@ ** Copyright (C) 2000-2008, Intel Corporation, all rights reserved. ** Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved. ** - ** For Human Visual System tools (hvstools) + ** For Human Visual System tools (bioinspired) ** Copyright (C) 2007-2011, LISTIC Lab, Annecy le Vieux and GIPSA Lab, Grenoble, France, all rights reserved. ** ** Third party copyrights are property of their respective owners. @@ -72,9 +72,12 @@ #include "retinafilter.hpp" #include #include +#include namespace cv { +namespace bioinspired +{ class RetinaImpl : public Retina { @@ -94,7 +97,7 @@ public: * @param reductionFactor: only usefull if param useRetinaLogSampling=true, specifies the reduction factor of the output frame (as the center (fovea) is high resolution and corners can be underscaled, then a reduction of the output is allowed without precision leak * @param samplingStrenght: only usefull if param useRetinaLogSampling=true, specifies the strenght of the log scale that is applied */ - RetinaImpl(Size inputSize, const bool colorMode, RETINA_COLORSAMPLINGMETHOD colorSamplingMethod=RETINA_COLOR_BAYER, const bool useRetinaLogSampling=false, const double reductionFactor=1.0, const double samplingStrenght=10.0); + RetinaImpl(Size inputSize, const bool colorMode, int colorSamplingMethod=RETINA_COLOR_BAYER, const bool useRetinaLogSampling=false, const double reductionFactor=1.0, const double samplingStrenght=10.0); virtual ~RetinaImpl(); /** @@ -196,6 +199,14 @@ public: */ void run(InputArray inputImage); + /** + * method that applies a luminance correction (initially High Dynamic Range (HDR) tone mapping) using only the 2 local adaptation stages of the retina parvo channel : photoreceptors level and ganlion cells level. Spatio temporal filtering is applied but limited to temporal smoothing and eventually high frequencies attenuation. This is a lighter method than the one available using the regular run method. It is then faster but it does not include complete temporal filtering nor retina spectral whitening. This is an adptation of the original still image HDR tone mapping algorithm of David Alleyson, Sabine Susstruck and Laurence Meylan's work, please cite: + * -> Meylan L., Alleysson D., and Susstrunk S., A Model of Retinal Local Adaptation for the Tone Mapping of Color Filter Array Images, Journal of Optical Society of America, A, Vol. 24, N 9, September, 1st, 2007, pp. 2807-2816 + @param inputImage the input image to process RGB or gray levels + @param outputToneMappedImage the output tone mapped image + */ + void applyFastToneMapping(InputArray inputImage, OutputArray outputToneMappedImage); + /** * accessor of the details channel of the retina (models foveal vision) * @param retinaOutput_parvo : the output buffer (reallocated if necessary), this output is rescaled for standard 8bits image processing use in OpenCV @@ -253,14 +264,17 @@ private: // Parameteres setup members RetinaParameters _retinaParameters; // structure of parameters - // Retina model related modules + // Retina model related modules std::valarray _inputBuffer; //!< buffer used to convert input cv::Mat to internal retina buffers format (valarrays) // pointer to retina model RetinaFilter* _retinaFilter; //!< the pointer to the retina module, allocated with instance construction + //! private method called by constructors, gathers their parameters and use them in a unified way + void _init(const Size inputSize, const bool colorMode, int colorSamplingMethod=RETINA_COLOR_BAYER, const bool useRetinaLogSampling=false, const double reductionFactor=1.0, const double samplingStrenght=10.0); + /** - * exports a valarray buffer outing from HVStools objects to a cv::Mat in CV_8UC1 (gray level picture) or CV_8UC3 (color) format + * exports a valarray buffer outing from bioinspired objects to a cv::Mat in CV_8UC1 (gray level picture) or CV_8UC3 (color) format * @param grayMatrixToConvert the valarray to export to OpenCV * @param nbRows : the number of rows of the valarray flatten matrix * @param nbColumns : the number of rows of the valarray flatten matrix @@ -270,22 +284,20 @@ private: void _convertValarrayBuffer2cvMat(const std::valarray &grayMatrixToConvert, const unsigned int nbRows, const unsigned int nbColumns, const bool colorMode, OutputArray outBuffer); /** - * + * convert a cv::Mat to a valarray buffer in float format * @param inputMatToConvert : the OpenCV cv::Mat that has to be converted to gray or RGB valarray buffer that will be processed by the retina model * @param outputValarrayMatrix : the output valarray * @return the input image color mode (color=true, gray levels=false) */ - bool _convertCvMat2ValarrayBuffer(InputArray inputMatToConvert, std::valarray &outputValarrayMatrix); - - //! private method called by constructors, gathers their parameters and use them in a unified way - void _init(const Size inputSize, const bool colorMode, RETINA_COLORSAMPLINGMETHOD colorSamplingMethod=RETINA_COLOR_BAYER, const bool useRetinaLogSampling=false, const double reductionFactor=1.0, const double samplingStrenght=10.0); + bool _convertCvMat2ValarrayBuffer(InputArray inputMatToConvert, std::valarray &outputValarrayMatrix); }; // smart pointers allocation : Ptr createRetina(Size inputSize){ return new RetinaImpl(inputSize); } -Ptr createRetina(Size inputSize, const bool colorMode, RETINA_COLORSAMPLINGMETHOD colorSamplingMethod, const bool useRetinaLogSampling, const double reductionFactor, const double samplingStrenght){return new RetinaImpl(inputSize, colorMode, colorSamplingMethod, useRetinaLogSampling, reductionFactor, samplingStrenght);} +Ptr createRetina(Size inputSize, const bool colorMode, int colorSamplingMethod, const bool useRetinaLogSampling, const double reductionFactor, const double samplingStrenght){return new RetinaImpl(inputSize, colorMode, colorSamplingMethod, useRetinaLogSampling, reductionFactor, samplingStrenght);} + // RetinaImpl code RetinaImpl::RetinaImpl(const cv::Size inputSz) @@ -294,7 +306,7 @@ RetinaImpl::RetinaImpl(const cv::Size inputSz) _init(inputSz, true, RETINA_COLOR_BAYER, false); } -RetinaImpl::RetinaImpl(const cv::Size inputSz, const bool colorMode, RETINA_COLORSAMPLINGMETHOD colorSamplingMethod, const bool useRetinaLogSampling, const double reductionFactor, const double samplingStrenght) +RetinaImpl::RetinaImpl(const cv::Size inputSz, const bool colorMode, int colorSamplingMethod, const bool useRetinaLogSampling, const double reductionFactor, const double samplingStrenght) { _retinaFilter = 0; _init(inputSz, colorMode, colorSamplingMethod, useRetinaLogSampling, reductionFactor, samplingStrenght); @@ -401,10 +413,10 @@ void RetinaImpl::setup(cv::FileStorage &fs, const bool applyDefaultSetupOnFailur printf("%s\n", printSetup().c_str()); } -void RetinaImpl::setup(cv::Retina::RetinaParameters newConfiguration) +void RetinaImpl::setup(Retina::RetinaParameters newConfiguration) { // simply copy structures - memcpy(&_retinaParameters, &newConfiguration, sizeof(cv::Retina::RetinaParameters)); + memcpy(&_retinaParameters, &newConfiguration, sizeof(Retina::RetinaParameters)); // apply setup setupOPLandIPLParvoChannel(_retinaParameters.OPLandIplParvo.colorMode, _retinaParameters.OPLandIplParvo.normaliseOutput, _retinaParameters.OPLandIplParvo.photoreceptorsLocalAdaptationSensitivity, _retinaParameters.OPLandIplParvo.photoreceptorsTemporalConstant, _retinaParameters.OPLandIplParvo.photoreceptorsSpatialConstant, _retinaParameters.OPLandIplParvo.horizontalCellsGain, _retinaParameters.OPLandIplParvo.hcellsTemporalConstant, _retinaParameters.OPLandIplParvo.hcellsSpatialConstant, _retinaParameters.OPLandIplParvo.ganglionCellsSensitivity); setupIPLMagnoChannel(_retinaParameters.IplMagno.normaliseOutput, _retinaParameters.IplMagno.parasolCells_beta, _retinaParameters.IplMagno.parasolCells_tau, _retinaParameters.IplMagno.parasolCells_k, _retinaParameters.IplMagno.amacrinCellsTemporalCutFrequency,_retinaParameters.IplMagno.V0CompressionParameter, _retinaParameters.IplMagno.localAdaptintegration_tau, _retinaParameters.IplMagno.localAdaptintegration_k); @@ -526,6 +538,27 @@ void RetinaImpl::run(InputArray inputMatToConvert) throw cv::Exception(-1, "RetinaImpl cannot be applied, wrong input buffer size", "RetinaImpl::run", "RetinaImpl.h", 0); } +void RetinaImpl::applyFastToneMapping(InputArray inputImage, OutputArray outputToneMappedImage) +{ + // first convert input image to the compatible format : + const bool colorMode = _convertCvMat2ValarrayBuffer(inputImage.getMat(), _inputBuffer); + const unsigned int nbPixels=_retinaFilter->getOutputNBrows()*_retinaFilter->getOutputNBcolumns(); + + // process tone mapping + if (colorMode) + { + std::valarray imageOutput(nbPixels*3); + _retinaFilter->runRGBToneMapping(_inputBuffer, imageOutput, true, _retinaParameters.OPLandIplParvo.photoreceptorsLocalAdaptationSensitivity, _retinaParameters.OPLandIplParvo.ganglionCellsSensitivity); + _convertValarrayBuffer2cvMat(imageOutput, _retinaFilter->getOutputNBrows(), _retinaFilter->getOutputNBcolumns(), true, outputToneMappedImage); + }else + { + std::valarray imageOutput(nbPixels); + _retinaFilter->runGrayToneMapping(_inputBuffer, imageOutput, _retinaParameters.OPLandIplParvo.photoreceptorsLocalAdaptationSensitivity, _retinaParameters.OPLandIplParvo.ganglionCellsSensitivity); + _convertValarrayBuffer2cvMat(imageOutput, _retinaFilter->getOutputNBrows(), _retinaFilter->getOutputNBcolumns(), false, outputToneMappedImage); + } + +} + void RetinaImpl::getParvo(OutputArray retinaOutput_parvo) { if (_retinaFilter->getColorMode()) @@ -580,11 +613,11 @@ const Mat RetinaImpl::getParvoRAW() const { } // private method called by constructirs -void RetinaImpl::_init(const cv::Size inputSz, const bool colorMode, RETINA_COLORSAMPLINGMETHOD colorSamplingMethod, const bool useRetinaLogSampling, const double reductionFactor, const double samplingStrenght) +void RetinaImpl::_init(const cv::Size inputSz, const bool colorMode, int colorSamplingMethod, const bool useRetinaLogSampling, const double reductionFactor, const double samplingStrenght) { // basic error check if (inputSz.height*inputSz.width <= 0) - throw cv::Exception(-1, "Bad retina size setup : size height and with must be superior to zero", "RetinaImpl::setup", "RetinaImpl.h", 0); + throw cv::Exception(-1, "Bad retina size setup : size height and with must be superior to zero", "RetinaImpl::setup", "Retina.cpp", 0); unsigned int nbPixels=inputSz.height*inputSz.width; // resize buffers if size does not match @@ -596,7 +629,7 @@ void RetinaImpl::_init(const cv::Size inputSz, const bool colorMode, RETINA_COLO _retinaFilter = new RetinaFilter(inputSz.height, inputSz.width, colorMode, colorSamplingMethod, useRetinaLogSampling, reductionFactor, samplingStrenght); // prepare the default parameter XML file with default setup - setup(_retinaParameters); + setup(_retinaParameters); // init retina _retinaFilter->clearAllBuffers(); @@ -623,7 +656,8 @@ void RetinaImpl::_convertValarrayBuffer2cvMat(const std::valarray &grayMa } }else { - const unsigned int doubleNBpixels=_retinaFilter->getOutputNBpixels()*2; + const unsigned int nbPixels=nbColumns*nbRows; + const unsigned int doubleNBpixels=nbColumns*nbRows*2; outBuffer.create(cv::Size(nbColumns, nbRows), CV_8UC3); Mat outMat = outBuffer.getMat(); for (unsigned int i=0;i &grayMa cv::Point2d pixel(j,i); cv::Vec3b pixelValues; pixelValues[2]=(unsigned char)*(valarrayPTR); - pixelValues[1]=(unsigned char)*(valarrayPTR+_retinaFilter->getOutputNBpixels()); + pixelValues[1]=(unsigned char)*(valarrayPTR+nbPixels); pixelValues[0]=(unsigned char)*(valarrayPTR+doubleNBpixels); outMat.at(pixel)=pixelValues; @@ -656,15 +690,16 @@ bool RetinaImpl::_convertCvMat2ValarrayBuffer(InputArray inputMat, std::valarray typedef float T; // define here the target pixel format, here, float const int dsttype = DataType::depth; // output buffer is float format - + const unsigned int nbPixels=inputMat.getMat().rows*inputMat.getMat().cols; + const unsigned int doubleNBpixels=inputMat.getMat().rows*inputMat.getMat().cols*2; if(imageNumberOfChannels==4) { // create a cv::Mat table (for RGBA planes) cv::Mat planes[4] = { - cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[_retinaFilter->getInputNBpixels()*2]), - cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[_retinaFilter->getInputNBpixels()]), + cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[doubleNBpixels]), + cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[nbPixels]), cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[0]) }; planes[3] = cv::Mat(inputMatToConvert.size(), dsttype); // last channel (alpha) does not point on the valarray (not usefull in our case) @@ -676,8 +711,8 @@ bool RetinaImpl::_convertCvMat2ValarrayBuffer(InputArray inputMat, std::valarray // create a cv::Mat table (for RGB planes) cv::Mat planes[] = { - cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[_retinaFilter->getInputNBpixels()*2]), - cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[_retinaFilter->getInputNBpixels()]), + cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[doubleNBpixels]), + cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[nbPixels]), cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[0]) }; // split color cv::Mat in 3 planes... it fills valarray directely @@ -701,5 +736,5 @@ void RetinaImpl::activateMovingContoursProcessing(const bool activate){_retinaFi void RetinaImpl::activateContoursProcessing(const bool activate){_retinaFilter->activateContoursProcessing(activate);} -} // end of namespace cv - +}// end of namespace bioinspired +}// end of namespace cv diff --git a/modules/contrib/src/retinacolor.cpp b/modules/bioinspired/src/retinacolor.cpp similarity index 98% rename from modules/contrib/src/retinacolor.cpp rename to modules/bioinspired/src/retinacolor.cpp index 92cba47af5..3fbc553852 100644 --- a/modules/contrib/src/retinacolor.cpp +++ b/modules/bioinspired/src/retinacolor.cpp @@ -6,7 +6,7 @@ ** copy or use the software. ** ** -** HVStools : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. +** bioinspired : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. ** Use: extract still images & image sequences features, from contours details to motion spatio-temporal features, etc. for high level visual scene analysis. Also contribute to image enhancement/compression such as tone mapping. ** ** Maintainers : Listic lab (code author current affiliation & applications) and Gipsa Lab (original research origins & applications) @@ -32,7 +32,7 @@ ** Copyright (C) 2000-2008, Intel Corporation, all rights reserved. ** Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved. ** -** For Human Visual System tools (hvstools) +** For Human Visual System tools (bioinspired) ** Copyright (C) 2007-2011, LISTIC Lab, Annecy le Vieux and GIPSA Lab, Grenoble, France, all rights reserved. ** ** Third party copyrights are property of their respective owners. @@ -73,14 +73,15 @@ namespace cv { - +namespace bioinspired +{ // init static values static float _LMStoACr1Cr2[]={1.0, 1.0, 0.0, 1.0, -1.0, 0.0, -0.5, -0.5, 1.0}; //static double _ACr1Cr2toLMS[]={0.5, 0.5, 0.0, 0.5, -0.5, 0.0, 0.5, 0.0, 1.0}; static float _LMStoLab[]={0.5774f, 0.5774f, 0.5774f, 0.4082f, 0.4082f, -0.8165f, 0.7071f, -0.7071f, 0.f}; // constructor/desctructor -RetinaColor::RetinaColor(const unsigned int NBrows, const unsigned int NBcolumns, const RETINA_COLORSAMPLINGMETHOD samplingMethod) +RetinaColor::RetinaColor(const unsigned int NBrows, const unsigned int NBcolumns, const int samplingMethod) :BasicRetinaFilter(NBrows, NBcolumns, 3), _colorSampling(NBrows*NBcolumns), _RGBmosaic(NBrows*NBcolumns*3), @@ -720,4 +721,5 @@ void RetinaColor::_applyImageColorSpaceConversion(const std::valarray &in } } -} +}// end of namespace bioinspired +}// end of namespace cv diff --git a/modules/contrib/src/retinacolor.hpp b/modules/bioinspired/src/retinacolor.hpp similarity index 97% rename from modules/contrib/src/retinacolor.hpp rename to modules/bioinspired/src/retinacolor.hpp index ff4a12e408..3fb6be8f9e 100644 --- a/modules/contrib/src/retinacolor.hpp +++ b/modules/bioinspired/src/retinacolor.hpp @@ -6,7 +6,7 @@ ** copy or use the software. ** ** -** HVStools : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. +** bioinspired : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. ** Use: extract still images & image sequences features, from contours details to motion spatio-temporal features, etc. for high level visual scene analysis. Also contribute to image enhancement/compression such as tone mapping. ** ** Maintainers : Listic lab (code author current affiliation & applications) and Gipsa Lab (original research origins & applications) @@ -32,7 +32,7 @@ ** Copyright (C) 2000-2008, Intel Corporation, all rights reserved. ** Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved. ** -** For Human Visual System tools (hvstools) +** For Human Visual System tools (bioinspired) ** Copyright (C) 2007-2011, LISTIC Lab, Annecy le Vieux and GIPSA Lab, Grenoble, France, all rights reserved. ** ** Third party copyrights are property of their respective owners. @@ -85,7 +85,8 @@ namespace cv { - +namespace bioinspired +{ class RetinaColor: public BasicRetinaFilter { public: @@ -99,7 +100,7 @@ namespace cv * @param NBcolumns: number of columns of the input image * @param samplingMethod: the chosen color sampling method */ - RetinaColor(const unsigned int NBrows, const unsigned int NBcolumns, const RETINA_COLORSAMPLINGMETHOD samplingMethod=RETINA_COLOR_DIAGONAL); + RetinaColor(const unsigned int NBrows, const unsigned int NBcolumns, const int samplingMethod=RETINA_COLOR_BAYER); /** * standard destructor @@ -219,7 +220,7 @@ namespace cv protected: // private functions - RETINA_COLORSAMPLINGMETHOD _samplingMethod; + int _samplingMethod; bool _saturateColors; float _colorSaturationValue; // links to parent buffers (more convienient names @@ -382,8 +383,7 @@ namespace cv #endif }; -} +}// end of namespace bioinspired +}// end of namespace cv #endif /*RETINACOLOR_HPP_*/ - - diff --git a/modules/bioinspired/src/retinafasttonemapping.cpp b/modules/bioinspired/src/retinafasttonemapping.cpp new file mode 100644 index 0000000000..468bedb9a1 --- /dev/null +++ b/modules/bioinspired/src/retinafasttonemapping.cpp @@ -0,0 +1,316 @@ + +/*#****************************************************************************** + ** IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. + ** + ** By downloading, copying, installing or using the software you agree to this license. + ** If you do not agree to this license, do not download, install, + ** copy or use the software. + ** + ** + ** bioinspired : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. + ** + ** Maintainers : Listic lab (code author current affiliation & applications) and Gipsa Lab (original research origins & applications) + ** + ** Creation - enhancement process 2007-2013 + ** Author: Alexandre Benoit (benoit.alexandre.vision@gmail.com), LISTIC lab, Annecy le vieux, France + ** + ** Theses algorithm have been developped by Alexandre BENOIT since his thesis with Alice Caplier at Gipsa-Lab (www.gipsa-lab.inpg.fr) and the research he pursues at LISTIC Lab (www.listic.univ-savoie.fr). + ** Refer to the following research paper for more information: + ** 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 + ** This work have been carried out thanks to Jeanny Herault who's research and great discussions are the basis of all this work, please take a look at his book: + ** 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. + ** + ** + ** This class is based on image processing tools of the author and already used within the Retina class (this is the same code as method retina::applyFastToneMapping, but in an independent class, it is ligth from a memory requirement point of view). It implements an adaptation of the efficient tone mapping algorithm propose by David Alleyson, Sabine Susstruck and Laurence Meylan's work, please cite: + ** -> Meylan L., Alleysson D., and Susstrunk S., A Model of Retinal Local Adaptation for the Tone Mapping of Color Filter Array Images, Journal of Optical Society of America, A, Vol. 24, N 9, September, 1st, 2007, pp. 2807-2816 + ** + ** + ** License Agreement + ** For Open Source Computer Vision Library + ** + ** Copyright (C) 2000-2008, Intel Corporation, all rights reserved. + ** Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved. + ** + ** For Human Visual System tools (bioinspired) + ** Copyright (C) 2007-2011, LISTIC Lab, Annecy le Vieux and GIPSA Lab, Grenoble, France, all rights reserved. + ** + ** Third party copyrights are property of their respective owners. + ** + ** Redistribution and use in source and binary forms, with or without modification, + ** are permitted provided that the following conditions are met: + ** + ** * Redistributions of source code must retain the above copyright notice, + ** this list of conditions and the following disclaimer. + ** + ** * Redistributions in binary form must reproduce the above copyright notice, + ** this list of conditions and the following disclaimer in the documentation + ** and/or other materials provided with the distribution. + ** + ** * The name of the copyright holders may not be used to endorse or promote products + ** derived from this software without specific prior written permission. + ** + ** This software is provided by the copyright holders and contributors "as is" and + ** any express or implied warranties, including, but not limited to, the implied + ** warranties of merchantability and fitness for a particular purpose are disclaimed. + ** In no event shall the Intel Corporation or contributors be liable for any direct, + ** indirect, incidental, special, exemplary, or consequential damages + ** (including, but not limited to, procurement of substitute goods or services; + ** loss of use, data, or profits; or business interruption) however caused + ** and on any theory of liability, whether in contract, strict liability, + ** or tort (including negligence or otherwise) arising in any way out of + ** the use of this software, even if advised of the possibility of such damage. + *******************************************************************************/ + +/* + * retinafasttonemapping.cpp + * + * Created on: May 26, 2013 + * Author: Alexandre Benoit + */ + +#include "precomp.hpp" +#include "basicretinafilter.hpp" +#include "retinacolor.hpp" +#include +#include +#include + +namespace cv +{ +namespace bioinspired +{ +/** + * @class RetinaFastToneMappingImpl a wrapper class which allows the tone mapping algorithm of Meylan&al(2007) to be used with OpenCV. + * This algorithm is already implemented in thre Retina class (retina::applyFastToneMapping) but used it does not require all the retina model to be allocated. This allows a light memory use for low memory devices (smartphones, etc. + * As a summary, these are the model properties: + * => 2 stages of local luminance adaptation with a different local neighborhood for each. + * => first stage models the retina photorecetors local luminance adaptation + * => second stage models th ganglion cells local information adaptation + * => compared to the initial publication, this class uses spatio-temporal low pass filters instead of spatial only filters. + * ====> this can help noise robustness and temporal stability for video sequence use cases. + * for more information, read to the following papers : + * Meylan L., Alleysson D., and Susstrunk S., A Model of Retinal Local Adaptation for the Tone Mapping of Color Filter Array Images, Journal of Optical Society of America, A, Vol. 24, N 9, September, 1st, 2007, pp. 2807-2816Benoit 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 + * regarding spatio-temporal filter and the bigger retina model : + * 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. + */ + +class RetinaFastToneMappingImpl : public RetinaFastToneMapping +{ +public: + /** + * constructor + * @param imageInput: the size of the images to process + */ + RetinaFastToneMappingImpl(Size imageInput) + { + unsigned int nbPixels=imageInput.height*imageInput.width; + + // basic error check + if (nbPixels <= 0) + throw cv::Exception(-1, "Bad retina size setup : size height and with must be superior to zero", "RetinaImpl::setup", "retinafasttonemapping.cpp", 0); + + // resize buffers + _inputBuffer.resize(nbPixels*3); // buffer supports gray images but also 3 channels color buffers... (larger is better...) + _imageOutput.resize(nbPixels*3); + _temp2.resize(nbPixels); + // allocate the main filter with 2 setup sets properties (one for each low pass filter + _multiuseFilter = new BasicRetinaFilter(imageInput.height, imageInput.width, 2); + // allocate the color manager (multiplexer/demultiplexer + _colorEngine = new RetinaColor(imageInput.height, imageInput.width); + // setup filter behaviors with default values + setup(); + } + + /** + * basic destructor + */ + virtual ~RetinaFastToneMappingImpl(){}; + + /** + * method that applies a luminance correction (initially High Dynamic Range (HDR) tone mapping) using only the 2 local adaptation stages of the retina parvocellular channel : photoreceptors level and ganlion cells level. Spatio temporal filtering is applied but limited to temporal smoothing and eventually high frequencies attenuation. This is a lighter method than the one available using the regular retina::run method. It is then faster but it does not include complete temporal filtering nor retina spectral whitening. Then, it can have a more limited effect on images with a very high dynamic range. This is an adptation of the original still image HDR tone mapping algorithm of David Alleyson, Sabine Susstruck and Laurence Meylan's work, please cite: + * -> Meylan L., Alleysson D., and Susstrunk S., A Model of Retinal Local Adaptation for the Tone Mapping of Color Filter Array Images, Journal of Optical Society of America, A, Vol. 24, N 9, September, 1st, 2007, pp. 2807-2816 + @param inputImage the input image to process RGB or gray levels + @param outputToneMappedImage the output tone mapped image + */ + virtual void applyFastToneMapping(InputArray inputImage, OutputArray outputToneMappedImage) + { + // first convert input image to the compatible format : + const bool colorMode = _convertCvMat2ValarrayBuffer(inputImage.getMat(), _inputBuffer); + + // process tone mapping + if (colorMode) + { + _runRGBToneMapping(_inputBuffer, _imageOutput, true); + _convertValarrayBuffer2cvMat(_imageOutput, _multiuseFilter->getNBrows(), _multiuseFilter->getNBcolumns(), true, outputToneMappedImage); + }else + { + _runGrayToneMapping(_inputBuffer, _imageOutput); + _convertValarrayBuffer2cvMat(_imageOutput, _multiuseFilter->getNBrows(), _multiuseFilter->getNBcolumns(), false, outputToneMappedImage); + } + + } + + /** + * setup method that updates tone mapping behaviors by adjusing the local luminance computation area + * @param photoreceptorsNeighborhoodRadius the first stage local adaptation area + * @param ganglioncellsNeighborhoodRadius the second stage local adaptation area + * @param meanLuminanceModulatorK the factor applied to modulate the meanLuminance information (default is 1, see reference paper) + */ + virtual void setup(const float photoreceptorsNeighborhoodRadius=3.f, const float ganglioncellsNeighborhoodRadius=1.f, const float meanLuminanceModulatorK=1.f) + { + // setup the spatio-temporal properties of each filter + _meanLuminanceModulatorK = meanLuminanceModulatorK; + _multiuseFilter->setV0CompressionParameter(1.f, 255.f, 128.f); + _multiuseFilter->setLPfilterParameters(0.f, 0.f, photoreceptorsNeighborhoodRadius, 1); + _multiuseFilter->setLPfilterParameters(0.f, 0.f, ganglioncellsNeighborhoodRadius, 2); + } + +private: + // a filter able to perform local adaptation and low pass spatio-temporal filtering + cv::Ptr _multiuseFilter; + cv::Ptr _colorEngine; + + //!< buffer used to convert input cv::Mat to internal retina buffers format (valarrays) + std::valarray _inputBuffer; + std::valarray _imageOutput; + std::valarray _temp2; + float _meanLuminanceModulatorK; + + +void _convertValarrayBuffer2cvMat(const std::valarray &grayMatrixToConvert, const unsigned int nbRows, const unsigned int nbColumns, const bool colorMode, OutputArray outBuffer) +{ + // fill output buffer with the valarray buffer + const float *valarrayPTR=get_data(grayMatrixToConvert); + if (!colorMode) + { + outBuffer.create(cv::Size(nbColumns, nbRows), CV_8U); + Mat outMat = outBuffer.getMat(); + for (unsigned int i=0;i(pixel)=(unsigned char)*(valarrayPTR++); + } + } + }else + { + const unsigned int nbPixels=nbColumns*nbRows; + const unsigned int doubleNBpixels=nbColumns*nbRows*2; + outBuffer.create(cv::Size(nbColumns, nbRows), CV_8UC3); + Mat outMat = outBuffer.getMat(); + for (unsigned int i=0;i(pixel)=pixelValues; + } + } + } +} + +bool _convertCvMat2ValarrayBuffer(InputArray inputMat, std::valarray &outputValarrayMatrix) +{ + const Mat inputMatToConvert=inputMat.getMat(); + // first check input consistency + if (inputMatToConvert.empty()) + throw cv::Exception(-1, "RetinaImpl cannot be applied, input buffer is empty", "RetinaImpl::run", "RetinaImpl.h", 0); + + // retreive color mode from image input + int imageNumberOfChannels = inputMatToConvert.channels(); + + // convert to float AND fill the valarray buffer + typedef float T; // define here the target pixel format, here, float + const int dsttype = DataType::depth; // output buffer is float format + + const unsigned int nbPixels=inputMat.getMat().rows*inputMat.getMat().cols; + const unsigned int doubleNBpixels=inputMat.getMat().rows*inputMat.getMat().cols*2; + + if(imageNumberOfChannels==4) + { + // create a cv::Mat table (for RGBA planes) + cv::Mat planes[4] = + { + cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[doubleNBpixels]), + cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[nbPixels]), + cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[0]) + }; + planes[3] = cv::Mat(inputMatToConvert.size(), dsttype); // last channel (alpha) does not point on the valarray (not usefull in our case) + // split color cv::Mat in 4 planes... it fills valarray directely + cv::split(Mat_ >(inputMatToConvert), planes); + } + else if (imageNumberOfChannels==3) + { + // create a cv::Mat table (for RGB planes) + cv::Mat planes[] = + { + cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[doubleNBpixels]), + cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[nbPixels]), + cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[0]) + }; + // split color cv::Mat in 3 planes... it fills valarray directely + cv::split(cv::Mat_ >(inputMatToConvert), planes); + } + else if(imageNumberOfChannels==1) + { + // create a cv::Mat header for the valarray + cv::Mat dst(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[0]); + inputMatToConvert.convertTo(dst, dsttype); + } + else + CV_Error(Error::StsUnsupportedFormat, "input image must be single channel (gray levels), bgr format (color) or bgra (color with transparency which won't be considered"); + + return imageNumberOfChannels>1; // return bool : false for gray level image processing, true for color mode +} + + + // run the initilized retina filter in order to perform gray image tone mapping, after this call all retina outputs are updated + void _runGrayToneMapping(const std::valarray &grayImageInput, std::valarray &grayImageOutput) + { + // apply tone mapping on the multiplexed image + // -> photoreceptors local adaptation (large area adaptation) + _multiuseFilter->runFilter_LPfilter(grayImageInput, grayImageOutput, 0); // compute low pass filtering modeling the horizontal cells filtering to acess local luminance + _multiuseFilter->setV0CompressionParameterToneMapping(1.f, grayImageOutput.max(), _meanLuminanceModulatorK*grayImageOutput.sum()/(float)_multiuseFilter->getNBpixels()); + _multiuseFilter->runFilter_LocalAdapdation(grayImageInput, grayImageOutput, _temp2); // adapt contrast to local luminance + + // -> ganglion cells local adaptation (short area adaptation) + _multiuseFilter->runFilter_LPfilter(_temp2, grayImageOutput, 1); // compute low pass filtering (high cut frequency (remove spatio-temporal noise) + _multiuseFilter->setV0CompressionParameterToneMapping(1.f, _temp2.max(), _meanLuminanceModulatorK*grayImageOutput.sum()/(float)_multiuseFilter->getNBpixels()); + _multiuseFilter->runFilter_LocalAdapdation(_temp2, grayImageOutput, grayImageOutput); // adapt contrast to local luminance + + } + + // run the initilized retina filter in order to perform color tone mapping, after this call all retina outputs are updated + void _runRGBToneMapping(const std::valarray &RGBimageInput, std::valarray &RGBimageOutput, const bool useAdaptiveFiltering) + { + // multiplex the image with the color sampling method specified in the constructor + _colorEngine->runColorMultiplexing(RGBimageInput); + + // apply tone mapping on the multiplexed image + _runGrayToneMapping(_colorEngine->getMultiplexedFrame(), RGBimageOutput); + + // demultiplex tone maped image + _colorEngine->runColorDemultiplexing(RGBimageOutput, useAdaptiveFiltering, _multiuseFilter->getMaxInputValue());//_ColorEngine->getMultiplexedFrame());//_ParvoRetinaFilter->getPhotoreceptorsLPfilteringOutput()); + + // rescaling result between 0 and 255 + _colorEngine->normalizeRGBOutput_0_maxOutputValue(255.0); + + // return the result + RGBimageOutput=_colorEngine->getDemultiplexedColorFrame(); + } + +}; + +CV_EXPORTS Ptr createRetinaFastToneMapping(Size inputSize) +{ + return new RetinaFastToneMappingImpl(inputSize); +} + +}// end of namespace bioinspired +}// end of namespace cv diff --git a/modules/contrib/src/retinafilter.cpp b/modules/bioinspired/src/retinafilter.cpp similarity index 96% rename from modules/contrib/src/retinafilter.cpp rename to modules/bioinspired/src/retinafilter.cpp index 4cf6019f57..e1e24c89bf 100644 --- a/modules/contrib/src/retinafilter.cpp +++ b/modules/bioinspired/src/retinafilter.cpp @@ -6,7 +6,7 @@ ** copy or use the software. ** ** -** HVStools : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. +** bioinspired : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. ** Use: extract still images & image sequences features, from contours details to motion spatio-temporal features, etc. for high level visual scene analysis. Also contribute to image enhancement/compression such as tone mapping. ** ** Maintainers : Listic lab (code author current affiliation & applications) and Gipsa Lab (original research origins & applications) @@ -32,7 +32,7 @@ ** Copyright (C) 2000-2008, Intel Corporation, all rights reserved. ** Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved. ** -** For Human Visual System tools (hvstools) +** For Human Visual System tools (bioinspired) ** Copyright (C) 2007-2011, LISTIC Lab, Annecy le Vieux and GIPSA Lab, Grenoble, France, all rights reserved. ** ** Third party copyrights are property of their respective owners. @@ -72,9 +72,11 @@ #include namespace cv +{ +namespace bioinspired { // standard constructor without any log sampling of the input frame - RetinaFilter::RetinaFilter(const unsigned int sizeRows, const unsigned int sizeColumns, const bool colorMode, const RETINA_COLORSAMPLINGMETHOD samplingMethod, const bool useRetinaLogSampling, const double reductionFactor, const double samplingStrenght) + RetinaFilter::RetinaFilter(const unsigned int sizeRows, const unsigned int sizeColumns, const bool colorMode, const int samplingMethod, const bool useRetinaLogSampling, const double reductionFactor, const double samplingStrenght) : _retinaParvoMagnoMappedFrame(0), _retinaParvoMagnoMapCoefTable(0), @@ -375,21 +377,15 @@ namespace cv // apply tone mapping on the multiplexed image // -> photoreceptors local adaptation (large area adaptation) _photoreceptorsPrefilter.runFilter_LPfilter(grayImageInput, grayImageOutput, 2); // compute low pass filtering modeling the horizontal cells filtering to acess local luminance - _photoreceptorsPrefilter.setV0CompressionParameterToneMapping(PhotoreceptorsCompression, grayImageOutput.sum()/(float)_photoreceptorsPrefilter.getNBpixels()); + _photoreceptorsPrefilter.setV0CompressionParameterToneMapping(1.f-PhotoreceptorsCompression, grayImageOutput.max(), 1.f*grayImageOutput.sum()/(float)_photoreceptorsPrefilter.getNBpixels()); _photoreceptorsPrefilter.runFilter_LocalAdapdation(grayImageInput, grayImageOutput, temp2); // adapt contrast to local luminance - // high pass filter - //_spatiotemporalLPfilter(_localBuffer, _filterOutput, 2); // compute low pass filtering (high cut frequency (remove spatio-temporal noise) - - //for (unsigned int i=0;i<_NBpixels;++i) - // _localBuffer[i]-= _filterOutput[i]/2.0; - // -> ganglion cells local adaptation (short area adaptation) _photoreceptorsPrefilter.runFilter_LPfilter(temp2, grayImageOutput, 1); // compute low pass filtering (high cut frequency (remove spatio-temporal noise) - _photoreceptorsPrefilter.setV0CompressionParameterToneMapping(ganglionCellsCompression, temp2.max(), temp2.sum()/(float)_photoreceptorsPrefilter.getNBpixels()); + _photoreceptorsPrefilter.setV0CompressionParameterToneMapping(1.f-ganglionCellsCompression, temp2.max(), 1.f*temp2.sum()/(float)_photoreceptorsPrefilter.getNBpixels()); _photoreceptorsPrefilter.runFilter_LocalAdapdation(temp2, grayImageOutput, grayImageOutput); // adapt contrast to local luminance - } + // run the initilized retina filter in order to perform color tone mapping, after this call all retina outputs are updated void RetinaFilter::runRGBToneMapping(const std::valarray &RGBimageInput, std::valarray &RGBimageOutput, const bool useAdaptiveFiltering, const float PhotoreceptorsCompression, const float ganglionCellsCompression) { @@ -526,4 +522,5 @@ namespace cv return true; } -} +}// end of namespace bioinspired +}// end of namespace cv diff --git a/modules/contrib/src/retinafilter.hpp b/modules/bioinspired/src/retinafilter.hpp similarity index 98% rename from modules/contrib/src/retinafilter.hpp rename to modules/bioinspired/src/retinafilter.hpp index 7fa2a078c8..3e204885fc 100644 --- a/modules/contrib/src/retinafilter.hpp +++ b/modules/bioinspired/src/retinafilter.hpp @@ -6,7 +6,7 @@ ** copy or use the software. ** ** -** HVStools : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. +** bioinspired : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. ** Use: extract still images & image sequences features, from contours details to motion spatio-temporal features, etc. for high level visual scene analysis. Also contribute to image enhancement/compression such as tone mapping. ** ** Maintainers : Listic lab (code author current affiliation & applications) and Gipsa Lab (original research origins & applications) @@ -32,7 +32,7 @@ ** Copyright (C) 2000-2008, Intel Corporation, all rights reserved. ** Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved. ** -** For Human Visual System tools (hvstools) +** For Human Visual System tools (bioinspired) ** Copyright (C) 2007-2011, LISTIC Lab, Annecy le Vieux and GIPSA Lab, Grenoble, France, all rights reserved. ** ** Third party copyrights are property of their respective owners. @@ -110,7 +110,8 @@ //#define __RETINADEBUG // define RETINADEBUG to display debug data namespace cv { - +namespace bioinspired +{ // retina class that process the 3 outputs of the retina filtering stages class RetinaFilter//: public BasicRetinaFilter { @@ -126,7 +127,7 @@ public: * @param reductionFactor: only usefull if param useRetinaLogSampling=true, specifies the reduction factor of the output frame (as the center (fovea) is high resolution and corners can be underscaled, then a reduction of the output is allowed without precision leak * @param samplingStrenght: only usefull if param useRetinaLogSampling=true, specifies the strenght of the log scale that is applied */ - RetinaFilter(const unsigned int sizeRows, const unsigned int sizeColumns, const bool colorMode=false, const RETINA_COLORSAMPLINGMETHOD samplingMethod=RETINA_COLOR_BAYER, const bool useRetinaLogSampling=false, const double reductionFactor=1.0, const double samplingStrenght=10.0); + RetinaFilter(const unsigned int sizeRows, const unsigned int sizeColumns, const bool colorMode=false, const int samplingMethod=RETINA_COLOR_BAYER, const bool useRetinaLogSampling=false, const double reductionFactor=1.0, const double samplingStrenght=10.0); /** * standard destructor @@ -541,9 +542,7 @@ private: }; -} +}// end of namespace bioinspired +}// end of namespace cv + #endif /*RETINACLASSES_H_*/ - - - - diff --git a/modules/contrib/src/templatebuffer.hpp b/modules/bioinspired/src/templatebuffer.hpp similarity index 98% rename from modules/contrib/src/templatebuffer.hpp rename to modules/bioinspired/src/templatebuffer.hpp index 21414b4da7..827eb709fa 100644 --- a/modules/contrib/src/templatebuffer.hpp +++ b/modules/bioinspired/src/templatebuffer.hpp @@ -6,7 +6,7 @@ ** copy or use the software. ** ** -** HVStools : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. +** bioinspired : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab. ** Use: extract still images & image sequences features, from contours details to motion spatio-temporal features, etc. for high level visual scene analysis. Also contribute to image enhancement/compression such as tone mapping. ** ** Maintainers : Listic lab (code author current affiliation & applications) and Gipsa Lab (original research origins & applications) @@ -32,7 +32,7 @@ ** Copyright (C) 2000-2008, Intel Corporation, all rights reserved. ** Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved. ** -** For Human Visual System tools (hvstools) +** For Human Visual System tools (bioinspired) ** Copyright (C) 2007-2011, LISTIC Lab, Annecy le Vieux and GIPSA Lab, Grenoble, France, all rights reserved. ** ** Third party copyrights are property of their respective owners. @@ -71,6 +71,12 @@ #include +//#define __TEMPLATEBUFFERDEBUG //define TEMPLATEBUFFERDEBUG in order to display debug information + +namespace cv +{ +namespace bioinspired +{ //// If a parallelization method is available then, you should define MAKE_PARALLEL, in the other case, the classical serial code will be used #define MAKE_PARALLEL // ==> then include required includes @@ -101,10 +107,6 @@ public: }; #endif -//#define __TEMPLATEBUFFERDEBUG //define TEMPLATEBUFFERDEBUG in order to display debug information - -namespace cv -{ /** * @class TemplateBuffer * @brief this class is a simple template memory buffer which contains basic functions to get information on or normalize the buffer content @@ -548,8 +550,6 @@ namespace cv return std::fabs(x); } -} +}// end of namespace bioinspired +}// end of namespace cv #endif - - - diff --git a/modules/bioinspired/test/test_main.cpp b/modules/bioinspired/test/test_main.cpp new file mode 100644 index 0000000000..6b24993447 --- /dev/null +++ b/modules/bioinspired/test/test_main.cpp @@ -0,0 +1,3 @@ +#include "test_precomp.hpp" + +CV_TEST_MAIN("cv") diff --git a/modules/bioinspired/test/test_precomp.cpp b/modules/bioinspired/test/test_precomp.cpp new file mode 100644 index 0000000000..5956e13e3e --- /dev/null +++ b/modules/bioinspired/test/test_precomp.cpp @@ -0,0 +1 @@ +#include "test_precomp.hpp" diff --git a/modules/bioinspired/test/test_precomp.hpp b/modules/bioinspired/test/test_precomp.hpp new file mode 100644 index 0000000000..b1672149ab --- /dev/null +++ b/modules/bioinspired/test/test_precomp.hpp @@ -0,0 +1,16 @@ +#ifdef __GNUC__ +# pragma GCC diagnostic ignored "-Wmissing-declarations" +# if defined __clang__ || defined __APPLE__ +# pragma GCC diagnostic ignored "-Wmissing-prototypes" +# pragma GCC diagnostic ignored "-Wextra" +# endif +#endif + +#ifndef __OPENCV_TEST_PRECOMP_HPP__ +#define __OPENCV_TEST_PRECOMP_HPP__ + +#include "opencv2/ts.hpp" +#include "opencv2/bioinspired.hpp" +#include + +#endif diff --git a/modules/contrib/doc/contrib.rst b/modules/contrib/doc/contrib.rst index 798d38d5bb..de14d33efe 100644 --- a/modules/contrib/doc/contrib.rst +++ b/modules/contrib/doc/contrib.rst @@ -9,5 +9,4 @@ The module contains some recently added functionality that has not been stabiliz stereo FaceRecognizer Documentation - Retina Documentation openfabmap diff --git a/modules/contrib/include/opencv2/contrib.hpp b/modules/contrib/include/opencv2/contrib.hpp index be83152db5..75c6f3db0e 100644 --- a/modules/contrib/include/opencv2/contrib.hpp +++ b/modules/contrib/include/opencv2/contrib.hpp @@ -633,7 +633,6 @@ CV_EXPORTS_W void applyColorMap(InputArray src, OutputArray dst, int colormap); CV_EXPORTS bool initModule_contrib(); } -#include "opencv2/contrib/retina.hpp" #include "opencv2/contrib/openfabmap.hpp" #endif diff --git a/samples/cpp/CMakeLists.txt b/samples/cpp/CMakeLists.txt index ab4a0d06c6..bc2d5ee39a 100644 --- a/samples/cpp/CMakeLists.txt +++ b/samples/cpp/CMakeLists.txt @@ -5,7 +5,7 @@ SET(OPENCV_CPP_SAMPLES_REQUIRED_DEPS opencv_core opencv_flann opencv_imgproc opencv_highgui opencv_ml opencv_video opencv_objdetect opencv_photo opencv_nonfree opencv_softcascade - opencv_features2d opencv_calib3d opencv_legacy opencv_contrib opencv_stitching opencv_videostab) + opencv_features2d opencv_calib3d opencv_legacy opencv_contrib opencv_stitching opencv_videostab opencv_bioinspired) ocv_check_dependencies(${OPENCV_CPP_SAMPLES_REQUIRED_DEPS}) diff --git a/samples/cpp/OpenEXRimages_HighDynamicRange_Retina_toneMapping.cpp b/samples/cpp/OpenEXRimages_HighDynamicRange_Retina_toneMapping.cpp index 2117ede7b9..21de69cb98 100644 --- a/samples/cpp/OpenEXRimages_HighDynamicRange_Retina_toneMapping.cpp +++ b/samples/cpp/OpenEXRimages_HighDynamicRange_Retina_toneMapping.cpp @@ -10,8 +10,9 @@ #include #include -#include "opencv2/contrib.hpp" -#include "opencv2/highgui.hpp" +#include "opencv2/bioinspired.hpp" // retina based algorithms +#include "opencv2/imgproc.hpp" // cvCvtcolor function +#include "opencv2/highgui.hpp" // display static void help(std::string errorMessage) { @@ -127,7 +128,7 @@ static void drawPlot(const cv::Mat curve, const std::string figureTitle, const i normalize(imageInputRescaled, imageInputRescaled, 0.0, 255.0, cv::NORM_MINMAX); } - cv::Ptr retina; + cv::Ptr retina; int retinaHcellsGain; int localAdaptation_photoreceptors, localAdaptation_Gcells; static void callBack_updateRetinaParams(int, void*) @@ -175,6 +176,12 @@ static void drawPlot(const cv::Mat curve, const std::string figureTitle, const i } bool useLogSampling = !strcmp(argv[argc-1], "log"); // check if user wants retina log sampling processing + int chosenMethod=0; + if (!strcmp(argv[argc-1], "fast")) + { + chosenMethod=1; + std::cout<<"Using fast method (no spectral whithning), adaptation of Meylan&al 2008 method"< if the last parameter is 'log', then activate log sampling (favour foveal vision and subsamples peripheral vision) */ if (useLogSampling) - { - retina = cv::createRetina(inputImage.size(),true, cv::RETINA_COLOR_BAYER, true, 2.0, 10.0); + { + retina = cv::bioinspired::createRetina(inputImage.size(),true, cv::bioinspired::RETINA_COLOR_BAYER, true, 2.0, 10.0); } else// -> else allocate "classical" retina : - retina = cv::createRetina(inputImage.size()); + retina = cv::bioinspired::createRetina(inputImage.size()); - // save default retina parameters file in order to let you see this and maybe modify it and reload using method "setup" - retina->write("RetinaDefaultParameters.xml"); + // create a fast retina tone mapper (Meyla&al algorithm) + std::cout<<"Allocating fast tone mapper..."< fastToneMapper=createRetinaFastToneMapping(inputImage.size()); + std::cout<<"Fast tone mapper allocated"<activateMovingContoursProcessing(false); + // save default retina parameters file in order to let you see this and maybe modify it and reload using method "setup" + retina->write("RetinaDefaultParameters.xml"); + + // desactivate Magnocellular pathway processing (motion information extraction) since it is not usefull here + retina->activateMovingContoursProcessing(false); // declare retina output buffers cv::Mat retinaOutput_parvo; @@ -230,20 +242,19 @@ static void drawPlot(const cv::Mat curve, const std::string figureTitle, const i histogramClippingValue=0; // default value... updated with interface slider //inputRescaleMat = inputImage; //outputRescaleMat = imageInputRescaled; - cv::namedWindow("Retina input image (with cut edges histogram for basic pixels error avoidance)",1); - cv::createTrackbar("histogram edges clipping limit", "Retina input image (with cut edges histogram for basic pixels error avoidance)",&histogramClippingValue,50,callBack_rescaleGrayLevelMat); + cv::namedWindow("Processing configuration",1); + cv::createTrackbar("histogram edges clipping limit", "Processing configuration",&histogramClippingValue,50,callBack_rescaleGrayLevelMat); - cv::namedWindow("Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", 1); colorSaturationFactor=3; - cv::createTrackbar("Color saturation", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", &colorSaturationFactor,5,callback_saturateColors); + cv::createTrackbar("Color saturation", "Processing configuration", &colorSaturationFactor,5,callback_saturateColors); retinaHcellsGain=40; - cv::createTrackbar("Hcells gain", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping",&retinaHcellsGain,100,callBack_updateRetinaParams); + cv::createTrackbar("Hcells gain", "Processing configuration",&retinaHcellsGain,100,callBack_updateRetinaParams); localAdaptation_photoreceptors=197; localAdaptation_Gcells=190; - cv::createTrackbar("Ph sensitivity", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", &localAdaptation_photoreceptors,199,callBack_updateRetinaParams); - cv::createTrackbar("Gcells sensitivity", "Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", &localAdaptation_Gcells,199,callBack_updateRetinaParams); + cv::createTrackbar("Ph sensitivity", "Processing configuration", &localAdaptation_photoreceptors,199,callBack_updateRetinaParams); + cv::createTrackbar("Gcells sensitivity", "Processing configuration", &localAdaptation_Gcells,199,callBack_updateRetinaParams); ///////////////////////////////////////////// @@ -257,11 +268,28 @@ static void drawPlot(const cv::Mat curve, const std::string figureTitle, const i while(continueProcessing) { // run retina filter - retina->run(imageInputRescaled); - // Retrieve and display retina output - retina->getParvo(retinaOutput_parvo); - cv::imshow("Retina input image (with cut edges histogram for basic pixels error avoidance)", imageInputRescaled/255.0); - cv::imshow("Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", retinaOutput_parvo); + if (!chosenMethod) + { + retina->run(imageInputRescaled); + // Retrieve and display retina output + retina->getParvo(retinaOutput_parvo); + cv::imshow("Retina input image (with cut edges histogram for basic pixels error avoidance)", imageInputRescaled/255.0); + cv::imshow("Retina Parvocellular pathway output : 16bit=>8bit image retina tonemapping", retinaOutput_parvo); + cv::imwrite("HDRinput.jpg",imageInputRescaled/255.0); + cv::imwrite("RetinaToneMapping.jpg",retinaOutput_parvo); + } + else + { + // apply the simplified hdr tone mapping method + cv::Mat fastToneMappingOutput; + retina->applyFastToneMapping(imageInputRescaled, fastToneMappingOutput); + cv::imshow("Retina fast tone mapping output : 16bit=>8bit image retina tonemapping", fastToneMappingOutput); + } + /*cv::Mat fastToneMappingOutput_specificObject; + fastToneMapper->setup(3.f, 1.5f, 1.f); + fastToneMapper->applyFastToneMapping(imageInputRescaled, fastToneMappingOutput_specificObject); + cv::imshow("### Retina fast tone mapping output : 16bit=>8bit image retina tonemapping", fastToneMappingOutput_specificObject); +*/ cv::waitKey(10); } }catch(cv::Exception e) diff --git a/samples/cpp/OpenEXRimages_HighDynamicRange_Retina_toneMapping_video.cpp b/samples/cpp/OpenEXRimages_HighDynamicRange_Retina_toneMapping_video.cpp index a4b71391c4..64e93fa2bd 100644 --- a/samples/cpp/OpenEXRimages_HighDynamicRange_Retina_toneMapping_video.cpp +++ b/samples/cpp/OpenEXRimages_HighDynamicRange_Retina_toneMapping_video.cpp @@ -14,8 +14,9 @@ #include #include -#include "opencv2/contrib.hpp" -#include "opencv2/highgui.hpp" +#include "opencv2/bioinspired.hpp" // retina based algorithms +#include "opencv2/imgproc.hpp" // cvCvtcolor function +#include "opencv2/highgui.hpp" // display static void help(std::string errorMessage) { @@ -160,7 +161,7 @@ static void rescaleGrayLevelMat(const cv::Mat &inputMat, cv::Mat &outputMat, con } - cv::Ptr retina; + cv::Ptr retina; int retinaHcellsGain; int localAdaptation_photoreceptors, localAdaptation_Gcells; static void callBack_updateRetinaParams(int, void*) @@ -280,10 +281,10 @@ static void loadNewFrame(const std::string filenamePrototype, const int currentF */ if (useLogSampling) { - retina = cv::createRetina(inputImage.size(),true, cv::RETINA_COLOR_BAYER, true, 2.0, 10.0); + retina = cv::bioinspired::createRetina(inputImage.size(),true, cv::bioinspired::RETINA_COLOR_BAYER, true, 2.0, 10.0); } else// -> else allocate "classical" retina : - retina = cv::createRetina(inputImage.size()); + retina = cv::bioinspired::createRetina(inputImage.size()); // save default retina parameters file in order to let you see this and maybe modify it and reload using method "setup" retina->write("RetinaDefaultParameters.xml"); diff --git a/samples/cpp/retinaDemo.cpp b/samples/cpp/retinaDemo.cpp index ffade70f35..51e8408af3 100644 --- a/samples/cpp/retinaDemo.cpp +++ b/samples/cpp/retinaDemo.cpp @@ -9,7 +9,7 @@ #include #include -#include "opencv2/contrib.hpp" +#include "opencv2/bioinspired.hpp" #include "opencv2/highgui.hpp" static void help(std::string errorMessage) @@ -106,15 +106,15 @@ int main(int argc, char* argv[]) { try { // create a retina instance with default parameters setup, uncomment the initialisation you wanna test - cv::Ptr myRetina; + cv::Ptr myRetina; // if the last parameter is 'log', then activate log sampling (favour foveal vision and subsamples peripheral vision) if (useLogSampling) { - myRetina = cv::createRetina(inputFrame.size(), true, cv::RETINA_COLOR_BAYER, true, 2.0, 10.0); + myRetina = cv::bioinspired::createRetina(inputFrame.size(), true, cv::bioinspired::RETINA_COLOR_BAYER, true, 2.0, 10.0); } else// -> else allocate "classical" retina : - myRetina = cv::createRetina(inputFrame.size()); + myRetina = cv::bioinspired::createRetina(inputFrame.size()); // save default retina parameters file in order to let you see this and maybe modify it and reload using method "setup" myRetina->write("RetinaDefaultParameters.xml"); @@ -143,7 +143,8 @@ int main(int argc, char* argv[]) { cv::imshow("retina input", inputFrame); cv::imshow("Retina Parvo", retinaOutput_parvo); cv::imshow("Retina Magno", retinaOutput_magno); - cv::waitKey(10); + + cv::waitKey(5); } }catch(cv::Exception e) { diff --git a/samples/cpp/tutorial_code/contrib/retina_tutorial.cpp b/samples/cpp/tutorial_code/bioinspired/retina_tutorial.cpp similarity index 95% rename from samples/cpp/tutorial_code/contrib/retina_tutorial.cpp rename to samples/cpp/tutorial_code/bioinspired/retina_tutorial.cpp index 284bbf5d8d..994d881dec 100644 --- a/samples/cpp/tutorial_code/contrib/retina_tutorial.cpp +++ b/samples/cpp/tutorial_code/bioinspired/retina_tutorial.cpp @@ -9,7 +9,7 @@ #include #include -#include "opencv2/contrib.hpp" +#include "opencv2/bioinspired.hpp" #include "opencv2/highgui.hpp" static void help(std::string errorMessage) @@ -95,16 +95,16 @@ int main(int argc, char* argv[]) { try { // create a retina instance with default parameters setup, uncomment the initialisation you wanna test - cv::Ptr myRetina; + cv::Ptr myRetina; // if the last parameter is 'log', then activate log sampling (favour foveal vision and subsamples peripheral vision) if (useLogSampling) { - myRetina = cv::createRetina(inputFrame.size(), true, cv::RETINA_COLOR_BAYER, true, 2.0, 10.0); + myRetina = cv::bioinspired::createRetina(inputFrame.size(), true, cv::bioinspired::RETINA_COLOR_BAYER, true, 2.0, 10.0); } else// -> else allocate "classical" retina : { - myRetina = cv::createRetina(inputFrame.size()); + myRetina = cv::bioinspired::createRetina(inputFrame.size()); } // save default retina parameters file in order to let you see this and maybe modify it and reload using method "setup"