Merge remote-tracking branch 'origin/2.4' into merge-2.4
authorRoman Donchenko <roman.donchenko@itseez.com>
Tue, 13 Aug 2013 08:56:39 +0000 (12:56 +0400)
committerRoman Donchenko <roman.donchenko@itseez.com>
Tue, 13 Aug 2013 08:56:39 +0000 (12:56 +0400)
Conflicts:
modules/calib3d/doc/camera_calibration_and_3d_reconstruction.rst
modules/features2d/doc/common_interfaces_of_descriptor_extractors.rst
modules/features2d/doc/object_categorization.rst
modules/gpu/doc/camera_calibration_and_3d_reconstruction.rst
modules/gpu/doc/image_filtering.rst
modules/gpu/doc/image_processing.rst
modules/gpu/doc/video.rst
modules/imgproc/doc/miscellaneous_transformations.rst
modules/imgproc/doc/object_detection.rst
modules/imgproc/doc/structural_analysis_and_shape_descriptors.rst
modules/imgproc/src/samplers.cpp
modules/ml/doc/k_nearest_neighbors.rst
modules/nonfree/doc/feature_detection.rst
modules/ocl/include/opencv2/ocl/ocl.hpp
modules/photo/doc/inpainting.rst
modules/ts/include/opencv2/ts.hpp
platforms/scripts/camera_build.conf
samples/android/camera-calibration/AndroidManifest.xml

55 files changed:
1  2 
cmake/OpenCVDetectPython.cmake
modules/androidcamera/src/camera_activity.cpp
modules/bioinspired/doc/retina/index.rst
modules/calib3d/doc/camera_calibration_and_3d_reconstruction.rst
modules/contrib/doc/facerec/facerec_api.rst
modules/core/doc/basic_structures.rst
modules/core/doc/clustering.rst
modules/core/doc/drawing_functions.rst
modules/core/doc/operations_on_arrays.rst
modules/core/doc/xml_yaml_persistence.rst
modules/core/src/stat.cpp
modules/core/test/test_arithm.cpp
modules/features2d/doc/common_interfaces_of_descriptor_extractors.rst
modules/features2d/doc/common_interfaces_of_descriptor_matchers.rst
modules/features2d/doc/common_interfaces_of_feature_detectors.rst
modules/features2d/doc/feature_detection_and_description.rst
modules/features2d/doc/object_categorization.rst
modules/gpu/doc/object_detection.rst
modules/gpubgsegm/doc/background_segmentation.rst
modules/gpucodec/doc/videodec.rst
modules/gpucodec/doc/videoenc.rst
modules/gpufilters/doc/filtering.rst
modules/gpuimgproc/doc/color.rst
modules/gpuimgproc/doc/hough.rst
modules/gpuoptflow/doc/optflow.rst
modules/gpustereo/doc/stereo.rst
modules/highgui/doc/reading_and_writing_images_and_video.rst
modules/highgui/doc/user_interface.rst
modules/highgui/src/cap_dshow.cpp
modules/highgui/src/cap_ffmpeg_impl.hpp
modules/imgproc/doc/feature_detection.rst
modules/imgproc/doc/filtering.rst
modules/imgproc/doc/geometric_transformations.rst
modules/imgproc/doc/histograms.rst
modules/imgproc/doc/miscellaneous_transformations.rst
modules/imgproc/doc/object_detection.rst
modules/imgproc/doc/structural_analysis_and_shape_descriptors.rst
modules/imgproc/src/morph.cpp
modules/imgproc/src/samplers.cpp
modules/imgproc/src/smooth.cpp
modules/ml/doc/k_nearest_neighbors.rst
modules/ml/doc/support_vector_machines.rst
modules/nonfree/doc/feature_detection.rst
modules/objdetect/doc/cascade_classification.rst
modules/ocl/doc/image_processing.rst
modules/ocl/doc/object_detection.rst
modules/ocl/include/opencv2/ocl.hpp
modules/photo/doc/inpainting.rst
modules/stitching/doc/high_level.rst
modules/ts/CMakeLists.txt
modules/ts/include/opencv2/ts.hpp
modules/ts/include/opencv2/ts/ts_perf.hpp
modules/video/doc/motion_analysis_and_object_tracking.rst
platforms/scripts/camera_build.conf
samples/android/camera-calibration/AndroidManifest.xml

Simple merge
index 9c1ae57,0000000..242416b
mode 100644,000000..100644
--- /dev/null
@@@ -1,493 -1,0 +1,493 @@@
-    * : An example on retina tone mapping can be found at opencv_source_code/samples/cpp/OpenEXRimages_HighDynamicRange_Retina_toneMapping.cpp
-    * : An example on retina tone mapping on video input can be found at opencv_source_code/samples/cpp/OpenEXRimages_HighDynamicRange_Retina_toneMapping.cpp
-    * : A complete example illustrating the retina interface can be found at opencv_source_code/samples/cpp/retinaDemo.cpp
 +Retina : a Bio mimetic human retina model
 +*****************************************
 +
 +.. highlight:: cpp
 +
 +Retina
 +======
 +.. ocv:class:: Retina : public Algorithm
 +
 +**Note** : do not forget that the retina model is included in the following namespace : *cv::bioinspired*.
 +
 +Introduction
 +++++++++++++
 +
 +Class which provides the main controls to the Gipsa/Listic labs human  retina model. This is a non separable spatio-temporal filter modelling the two main retina information channels :
 +
 +* foveal vision for detailled color vision : the parvocellular pathway.
 +
 +* 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]_, [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 :**
 +
 +* For ease of use in computer vision applications, the two retina channels are applied homogeneously on all the input images. This does not follow the real retina topology but this can still be done using the log sampling capabilities proposed within the class.
 +
 +* Extend the retina description and code use in the tutorial/contrib section for complementary explanations.
 +
 +Preliminary illustration
 +++++++++++++++++++++++++
 +
 +As a preliminary presentation, let's start with a visual example. We propose to apply the filter on a low quality color jpeg image with backlight problems. Here is the considered input... *"Well, my eyes were able to see more that this strange black shadow..."*
 +
 +.. image:: images/retinaInput.jpg
 +   :alt: a low quality color jpeg image with backlight problems.
 +   :align: center
 +
 +Below, the retina foveal model applied on the entire image with default parameters. Here contours are enforced, halo effects are voluntary visible with this configuration. See parameters discussion below and increase horizontalCellsGain near 1 to remove them.
 +
 +.. image:: images/retinaOutput_default.jpg
 +   :alt: the retina foveal model applied on the entire image with default parameters. Here contours are enforced, luminance is corrected and halo effects are voluntary visible with this configuration, increase horizontalCellsGain near 1 to remove them.
 +   :align: center
 +
 +Below, a second retina foveal model output applied on the entire image with a parameters setup focused on naturalness perception. *"Hey, i now recognize my cat, looking at the mountains at the end of the day !"*. Here contours are enforced, luminance is corrected but halos are avoided with this configuration. The backlight effect is corrected and highlight details are still preserved. Then, even on a low quality jpeg image, if some luminance information remains, the retina is able to reconstruct a proper visual signal. Such configuration is also usefull for High Dynamic Range (*HDR*) images compression to 8bit images as discussed in [benoit2010]_ and in the demonstration codes discussed below.
 +As shown at the end of the page, parameters change from defaults are :
 +
 +* horizontalCellsGain=0.3
 +
 +* photoreceptorsLocalAdaptationSensitivity=ganglioncellsSensitivity=0.89.
 +
 +.. image:: images/retinaOutput_realistic.jpg
 +   :alt: the retina foveal model applied on the entire image with 'naturalness' parameters. Here contours are enforced but are avoided with this configuration, horizontalCellsGain is 0.3 and photoreceptorsLocalAdaptationSensitivity=ganglioncellsSensitivity=0.89.
 +   :align: center
 +
 +As observed in this preliminary demo, the retina can be settled up with various parameters, by default, as shown on the figure above, the retina strongly reduces mean luminance energy and enforces all details of the visual scene. Luminance energy and halo effects can be modulated (exagerated to cancelled as shown on the two examples). In order to use your own parameters, you can use at least one time the *write(String fs)* method which will write a proper XML file with all default parameters. Then, tweak it on your own and reload them at any time using method *setup(String fs)*. These methods update a *Retina::RetinaParameters* member structure that is described hereafter. XML parameters file samples are shown at the end of the page.
 +
 +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 (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);
 +    void getParvoRAW (OutputArray retinaOutput_parvo);// retreive original output buffers without any normalisation
 +    const Mat getParvoRAW () const;// retreive original output buffers without any normalisation
 +    // -> peripheral monochrome motion and events (transient information) channel
 +    void getMagno (OutputArray retinaOutput_magno);
 +    void getMagnoRAW (OutputArray retinaOutput_magno); // retreive original output buffers without any normalisation
 +    const Mat getMagnoRAW () const;// retreive original output buffers without any normalisation
 +
 +    // reset retina buffers... equivalent to closing your eyes for some seconds
 +    void clearBuffers ();
 +
 +    // retreive input and output buffers sizes
 +    Size getInputSize ();
 +    Size getOutputSize ();
 +
 +    // setup methods with specific parameters specification of global xml config file loading/write
 +    void setup (String retinaParameterFile="", const bool applyDefaultSetupOnFailure=true);
 +    void setup (FileStorage &fs, const bool applyDefaultSetupOnFailure=true);
 +    void setup (RetinaParameters newParameters);
 +    struct Retina::RetinaParameters getParameters ();
 +    const String printSetup ();
 +    virtual void write (String fs) const;
 +    virtual void write (FileStorage &fs) const;
 +    void setupOPLandIPLParvoChannel (const bool colorMode=true, const bool normaliseOutput=true, const float photoreceptorsLocalAdaptationSensitivity=0.7, const float photoreceptorsTemporalConstant=0.5, const float photoreceptorsSpatialConstant=0.53, const float horizontalCellsGain=0, const float HcellsTemporalConstant=1, const float HcellsSpatialConstant=7, const float ganglionCellsSensitivity=0.7);
 +    void setupIPLMagnoChannel (const bool normaliseOutput=true, const float parasolCells_beta=0, const float parasolCells_tau=0, const float parasolCells_k=7, const float amacrinCellsTemporalCutFrequency=1.2, const float V0CompressionParameter=0.95, const float localAdaptintegration_tau=0, const float localAdaptintegration_k=7);
 +    void setColorSaturation (const bool saturateColors=true, const float colorSaturationValue=4.0);
 +    void activateMovingContoursProcessing (const bool activate);
 +    void activateContoursProcessing (const bool activate);
 +  };
 +
 +    // Allocators
 +    cv::Ptr<Retina> createRetina (Size inputSize);
 +    cv::Ptr<Retina> 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
 +
 +.. Sample code::
 +
++   * An example on retina tone mapping can be found at opencv_source_code/samples/cpp/OpenEXRimages_HighDynamicRange_Retina_toneMapping.cpp
++   * An example on retina tone mapping on video input can be found at opencv_source_code/samples/cpp/OpenEXRimages_HighDynamicRange_Retina_toneMapping.cpp
++   * A complete example illustrating the retina interface can be found at opencv_source_code/samples/cpp/retinaDemo.cpp
 +
 +Description
 ++++++++++++
 +
 +Class which allows the `Gipsa <http://www.gipsa-lab.inpg.fr>`_ (preliminary work) / `Listic <http://www.listic.univ-savoie.fr>`_ (code maintainer and user) labs retina model to be used. This class allows human retina spatio-temporal image processing to be applied on still images, images sequences and video sequences. Briefly, here are the main human retina model properties:
 +
 +* spectral whithening (mid-frequency details enhancement)
 +
 +* high frequency spatio-temporal noise reduction (temporal noise and high frequency spatial noise are minimized)
 +
 +* low frequency luminance reduction (luminance range compression) : high luminance regions do not hide details in darker regions anymore
 +
 +* local logarithmic luminance compression allows details to be enhanced even in low light conditions
 +
 +Use : 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, by using the provided **getParvo** methods)
 +
 +* 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 <http://dx.doi.org/10.1016/j.cviu.2010.01.011>
 +
 +* 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.
 +
 +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.
 +
 +* 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 !
 +=======================
 +
 +**NOTE : Complementary to the following examples, have a look at the Retina tutorial in the tutorial/contrib section for complementary explanations.**
 +
 +Take a look at the provided C++ examples provided with OpenCV :
 +
 +* **samples/cpp/retinademo.cpp** shows how to use the retina module for details enhancement (Parvo channel output) and transient maps observation (Magno channel output). You can play with images, video sequences and webcam video.
 +    Typical uses are (provided your OpenCV installation is situated in folder *OpenCVReleaseFolder*)
 +
 +    * image processing : **OpenCVReleaseFolder/bin/retinademo -image myPicture.jpg**
 +
 +    * video processing : **OpenCVReleaseFolder/bin/retinademo -video myMovie.avi**
 +
 +    * webcam processing: **OpenCVReleaseFolder/bin/retinademo -video**
 +
 +   **Note :** This demo generates the file *RetinaDefaultParameters.xml* which contains the default parameters of the retina. Then, rename this as *RetinaSpecificParameters.xml*, adjust the parameters the way you want and reload the program to check the effect.
 +
 +
 +* **samples/cpp/OpenEXRimages_HighDynamicRange_Retina_toneMapping.cpp** shows how to use the retina to perform High Dynamic Range (HDR) luminance compression
 +
 +   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 such as *memorial.exr* (present in the samples/cpp/ folder)
 +
 +   **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
 +===================
 +
 +Here are detailled the main methods to control the retina model
 +
 +Ptr<Retina>::createRetina
 ++++++++++++++++++++++++++
 +
 +.. ocv:function:: Ptr<cv::bioinspired::Retina> createRetina(Size inputSize)
 +.. ocv:function:: Ptr<cv::bioinspired::Retina> 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
 +
 +    :param inputSize: the input frame size
 +    :param colorMode: the chosen processing mode : with or without color processing
 +    :param colorSamplingMethod: specifies which kind of color sampling will be used :
 +
 +        * cv::bioinspired::RETINA_COLOR_RANDOM: each pixel position is either R, G or B in a random choice
 +
 +        * cv::bioinspired::RETINA_COLOR_DIAGONAL: color sampling is RGBRGBRGB..., line 2 BRGBRGBRG..., line 3, GBRGBRGBR...
 +
 +        * 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
 +    :param samplingStrenght: only usefull if param useRetinaLogSampling=true, specifies the strenght of the log scale that is applied
 +
 +Retina::activateContoursProcessing
 +++++++++++++++++++++++++++++++++++
 +
 +.. ocv:function:: void Retina::activateContoursProcessing(const bool activate)
 +
 +    Activate/desactivate the Parvocellular pathway processing (contours information extraction), by default, it is activated
 +
 +    :param activate: true if Parvocellular (contours information extraction) output should be activated, false if not... if activated, the Parvocellular output can be retrieved using the **getParvo** methods
 +
 +Retina::activateMovingContoursProcessing
 +++++++++++++++++++++++++++++++++++++++++
 +
 +.. ocv:function:: void Retina::activateMovingContoursProcessing(const bool activate)
 +
 +    Activate/desactivate the Magnocellular pathway processing (motion information extraction), by default, it is activated
 +
 +    :param activate: true if Magnocellular output should be activated, false if not... if activated, the Magnocellular output can be retrieved using the **getMagno** methods
 +
 +Retina::clearBuffers
 +++++++++++++++++++++
 +
 +.. ocv:function:: void Retina::clearBuffers()
 +
 +    Clears all retina buffers (equivalent to opening the eyes after a long period of eye close ;o) whatchout the temporal transition occuring just after this method call.
 +
 +Retina::getParvo
 +++++++++++++++++
 +
 +.. ocv:function:: void Retina::getParvo( OutputArray retinaOutput_parvo )
 +.. ocv:function:: void Retina::getParvoRAW( OutputArray retinaOutput_parvo )
 +.. ocv:function:: const Mat Retina::getParvoRAW() const
 +
 +    Accessor of the details channel of the retina (models foveal vision). Warning, getParvoRAW methods return buffers that are not rescaled within range [0;255] while the non RAW method allows a normalized matrix to be retrieved.
 +
 +    :param retinaOutput_parvo: the output buffer (reallocated if necessary), format can be :
 +
 +        * a Mat, this output is rescaled for standard 8bits image processing use in OpenCV
 +
 +        * RAW methods actually return a 1D matrix (encoding is R1, R2, ... Rn, G1, G2, ..., Gn, B1, B2, ...Bn), this output is the original retina filter model output, without any quantification or rescaling.
 +
 +Retina::getMagno
 +++++++++++++++++
 +
 +.. ocv:function:: void Retina::getMagno( OutputArray retinaOutput_magno )
 +.. ocv:function:: void Retina::getMagnoRAW( OutputArray retinaOutput_magno )
 +.. ocv:function:: const Mat Retina::getMagnoRAW() const
 +
 +    Accessor of the motion channel of the retina (models peripheral vision). Warning, getMagnoRAW methods return buffers that are not rescaled within range [0;255] while the non RAW method allows a normalized matrix to be retrieved.
 +
 +    :param retinaOutput_magno: the output buffer (reallocated if necessary), format can be :
 +
 +        * a Mat, this output is rescaled for standard 8bits image processing use in OpenCV
 +
 +        * RAW methods actually return a 1D matrix (encoding is M1, M2,... Mn), this output is the original retina filter model output, without any quantification or rescaling.
 +
 +Retina::getInputSize
 +++++++++++++++++++++
 +
 +.. ocv:function:: Size Retina::getInputSize()
 +
 +    Retreive retina input buffer size
 +
 +    :return: the retina input buffer size
 +
 +Retina::getOutputSize
 ++++++++++++++++++++++
 +
 +.. ocv:function:: Size Retina::getOutputSize()
 +
 +    Retreive retina output buffer size that can be different from the input if a spatial log transformation is applied
 +
 +    :return: the retina output buffer size
 +
 +Retina::printSetup
 +++++++++++++++++++
 +
 +.. ocv:function:: const String Retina::printSetup()
 +
 +    Outputs a string showing the used parameters setup
 +
 +    :return: a string which contains formated parameters information
 +
 +Retina::run
 ++++++++++++
 +
 +.. ocv:function:: void Retina::run(InputArray inputImage)
 +
 +    Method which allows retina to be applied on an input image, after run, encapsulated retina module is ready to deliver its outputs using dedicated acccessors, see getParvo and getMagno methods
 +
 +    :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
 +++++++++++++++++++++++++++
 +
 +.. ocv:function:: void Retina::setColorSaturation(const bool saturateColors = true, const float colorSaturationValue = 4.0 )
 +
 +    Activate color saturation as the final step of the color demultiplexing process -> this saturation is a sigmoide function applied to each channel of the demultiplexed image.
 +
 +    :param saturateColors: boolean that activates color saturation (if true) or desactivate (if false)
 +    :param colorSaturationValue: the saturation factor : a simple factor applied on the chrominance buffers
 +
 +
 +Retina::setup
 ++++++++++++++
 +
 +.. ocv:function:: void Retina::setup(String retinaParameterFile = "", const bool applyDefaultSetupOnFailure = true )
 +.. ocv:function:: void Retina::setup(FileStorage & fs, const bool applyDefaultSetupOnFailure = true )
 +.. ocv:function:: void Retina::setup(RetinaParameters newParameters)
 +
 +    Try to open an XML retina parameters file to adjust current retina instance setup => if the xml file does not exist, then default setup is applied => warning, Exceptions are thrown if read XML file is not valid
 +
 +    :param retinaParameterFile: the parameters filename
 +    :param applyDefaultSetupOnFailure: set to true if an error must be thrown on error
 +    :param fs: the open Filestorage which contains retina parameters
 +    :param newParameters: a parameters structures updated with the new target configuration. You can retreive the current parameers structure using method *Retina::RetinaParameters Retina::getParameters()* and update it before running method *setup*.
 +
 +Retina::write
 ++++++++++++++
 +
 +.. ocv:function:: void Retina::write( String fs ) const
 +.. ocv:function:: void Retina::write( FileStorage& fs ) const
 +
 +    Write xml/yml formated parameters information
 +
 +    :param fs: the filename of the xml file that will be open and writen with formatted parameters information
 +
 +Retina::setupIPLMagnoChannel
 +++++++++++++++++++++++++++++
 +
 +.. ocv:function:: void Retina::setupIPLMagnoChannel(const bool normaliseOutput = true, const float parasolCells_beta = 0, const float parasolCells_tau = 0, const float parasolCells_k = 7, const float amacrinCellsTemporalCutFrequency = 1.2, const float V0CompressionParameter = 0.95, const float localAdaptintegration_tau = 0, const float localAdaptintegration_k = 7 )
 +
 +    Set parameters values for the Inner Plexiform Layer (IPL) magnocellular channel this channel processes signals output from OPL processing stage in peripheral vision, it allows motion information enhancement. It is decorrelated from the details channel. See reference papers for more details.
 +
 +    :param normaliseOutput: specifies if (true) output is rescaled between 0 and 255 of not (false)
 +    :param parasolCells_beta: the low pass filter gain used for local contrast adaptation at the IPL level of the retina (for ganglion cells local adaptation), typical value is 0
 +    :param parasolCells_tau: the low pass filter time constant used for local contrast adaptation at the IPL level of the retina (for ganglion cells local adaptation), unit is frame, typical value is 0 (immediate response)
 +    :param parasolCells_k: the low pass filter spatial constant used for local contrast adaptation at the IPL level of the retina (for ganglion cells local adaptation), unit is pixels, typical value is 5
 +    :param amacrinCellsTemporalCutFrequency: the time constant of the first order high pass fiter of the magnocellular way (motion information channel), unit is frames, typical value is 1.2
 +    :param V0CompressionParameter: the compression strengh of the ganglion cells local adaptation output, set a value between 0.6 and 1 for best results, a high value increases more the low value sensitivity... and the output saturates faster, recommended value: 0.95
 +    :param localAdaptintegration_tau: specifies the temporal constant of the low pas filter involved in the computation of the local "motion mean" for the local adaptation computation
 +    :param localAdaptintegration_k: specifies the spatial constant of the low pas filter involved in the computation of the local "motion mean" for the local adaptation computation
 +
 +Retina::setupOPLandIPLParvoChannel
 +++++++++++++++++++++++++++++++++++
 +
 +.. ocv:function:: void Retina::setupOPLandIPLParvoChannel(const bool colorMode = true, const bool normaliseOutput = true, const float photoreceptorsLocalAdaptationSensitivity = 0.7, const float photoreceptorsTemporalConstant = 0.5, const float photoreceptorsSpatialConstant = 0.53, const float horizontalCellsGain = 0, const float HcellsTemporalConstant = 1, const float HcellsSpatialConstant = 7, const float ganglionCellsSensitivity = 0.7 )
 +
 +    Setup the OPL and IPL parvo channels (see biologocal model) OPL is referred as Outer Plexiform Layer of the retina, it allows the spatio-temporal filtering which withens the spectrum and reduces spatio-temporal noise while attenuating global luminance (low frequency energy) IPL parvo is the OPL next processing stage, it refers to a part of the Inner Plexiform layer of the retina, it allows high contours sensitivity in foveal vision. See reference papers for more informations.
 +
 +    :param colorMode: specifies if (true) color is processed of not (false) to then processing gray level image
 +    :param normaliseOutput: specifies if (true) output is rescaled between 0 and 255 of not (false)
 +    :param photoreceptorsLocalAdaptationSensitivity: the photoreceptors sensitivity renage is 0-1 (more log compression effect when value increases)
 +    :param photoreceptorsTemporalConstant: the time constant of the first order low pass filter of the photoreceptors, use it to cut high temporal frequencies (noise or fast motion), unit is frames, typical value is 1 frame
 +    :param photoreceptorsSpatialConstant: the spatial constant of the first order low pass filter of the photoreceptors, use it to cut high spatial frequencies (noise or thick contours), unit is pixels, typical value is 1 pixel
 +    :param horizontalCellsGain: gain of the horizontal cells network, if 0, then the mean value of the output is zero, if the parameter is near 1, then, the luminance is not filtered and is still reachable at the output, typicall value is 0
 +    :param HcellsTemporalConstant: the time constant of the first order low pass filter of the horizontal cells, use it to cut low temporal frequencies (local luminance variations), unit is frames, typical value is 1 frame, as the photoreceptors
 +    :param HcellsSpatialConstant: the spatial constant of the first order low pass filter of the horizontal cells, use it to cut low spatial frequencies (local luminance), unit is pixels, typical value is 5 pixel, this value is also used for local contrast computing when computing the local contrast adaptation at the ganglion cells level (Inner Plexiform Layer parvocellular channel model)
 +    :param ganglionCellsSensitivity: the compression strengh of the ganglion cells local adaptation output, set a value between 0.6 and 1 for best results, a high value increases more the low value sensitivity... and the output saturates faster, recommended value: 0.7
 +
 +
 +Retina::RetinaParameters
 +========================
 +
 +.. ocv:struct:: Retina::RetinaParameters
 +
 +  This structure merges all the parameters that can be adjusted threw the **Retina::setup()**, **Retina::setupOPLandIPLParvoChannel** and **Retina::setupIPLMagnoChannel** setup methods
 +  Parameters structure for better clarity, check explenations on the comments of methods : setupOPLandIPLParvoChannel and setupIPLMagnoChannel. ::
 +
 +    class RetinaParameters{
 +        struct OPLandIplParvoParameters{ // Outer Plexiform Layer (OPL) and Inner Plexiform Layer Parvocellular (IplParvo) parameters
 +               OPLandIplParvoParameters():colorMode(true),
 +                  normaliseOutput(true), // specifies if (true) output is rescaled between 0 and 255 of not (false)
 +                  photoreceptorsLocalAdaptationSensitivity(0.7f), // the photoreceptors sensitivity renage is 0-1 (more log compression effect when value increases)
 +                  photoreceptorsTemporalConstant(0.5f),// the time constant of the first order low pass filter of the photoreceptors, use it to cut high temporal frequencies (noise or fast motion), unit is frames, typical value is 1 frame
 +                  photoreceptorsSpatialConstant(0.53f),// the spatial constant of the first order low pass filter of the photoreceptors, use it to cut high spatial frequencies (noise or thick contours), unit is pixels, typical value is 1 pixel
 +                  horizontalCellsGain(0.0f),//gain of the horizontal cells network, if 0, then the mean value of the output is zero, if the parameter is near 1, then, the luminance is not filtered and is still reachable at the output, typicall value is 0
 +                  hcellsTemporalConstant(1.f),// the time constant of the first order low pass filter of the horizontal cells, use it to cut low temporal frequencies (local luminance variations), unit is frames, typical value is 1 frame, as the photoreceptors. Reduce to 0.5 to limit retina after effects.
 +                  hcellsSpatialConstant(7.f),//the spatial constant of the first order low pass filter of the horizontal cells, use it to cut low spatial frequencies (local luminance), unit is pixels, typical value is 5 pixel, this value is also used for local contrast computing when computing the local contrast adaptation at the ganglion cells level (Inner Plexiform Layer parvocellular channel model)
 +                  ganglionCellsSensitivity(0.7f)//the compression strengh of the ganglion cells local adaptation output, set a value between 0.6 and 1 for best results, a high value increases more the low value sensitivity... and the output saturates faster, recommended value: 0.7
 +                  {};// default setup
 +               bool colorMode, normaliseOutput;
 +               float photoreceptorsLocalAdaptationSensitivity, photoreceptorsTemporalConstant, photoreceptorsSpatialConstant, horizontalCellsGain, hcellsTemporalConstant, hcellsSpatialConstant, ganglionCellsSensitivity;
 +           };
 +           struct IplMagnoParameters{ // Inner Plexiform Layer Magnocellular channel (IplMagno)
 +               IplMagnoParameters():
 +                  normaliseOutput(true), //specifies if (true) output is rescaled between 0 and 255 of not (false)
 +                  parasolCells_beta(0.f), // the low pass filter gain used for local contrast adaptation at the IPL level of the retina (for ganglion cells local adaptation), typical value is 0
 +                  parasolCells_tau(0.f), //the low pass filter time constant used for local contrast adaptation at the IPL level of the retina (for ganglion cells local adaptation), unit is frame, typical value is 0 (immediate response)
 +                  parasolCells_k(7.f), //the low pass filter spatial constant used for local contrast adaptation at the IPL level of the retina (for ganglion cells local adaptation), unit is pixels, typical value is 5
 +                  amacrinCellsTemporalCutFrequency(1.2f), //the time constant of the first order high pass fiter of the magnocellular way (motion information channel), unit is frames, typical value is 1.2
 +                  V0CompressionParameter(0.95f), the compression strengh of the ganglion cells local adaptation output, set a value between 0.6 and 1 for best results, a high value increases more the low value sensitivity... and the output saturates faster, recommended value: 0.95
 +                  localAdaptintegration_tau(0.f), // specifies the temporal constant of the low pas filter involved in the computation of the local "motion mean" for the local adaptation computation
 +                  localAdaptintegration_k(7.f) // specifies the spatial constant of the low pas filter involved in the computation of the local "motion mean" for the local adaptation computation
 +                  {};// default setup
 +               bool normaliseOutput;
 +               float parasolCells_beta, parasolCells_tau, parasolCells_k, amacrinCellsTemporalCutFrequency, V0CompressionParameter, localAdaptintegration_tau, localAdaptintegration_k;
 +           };
 +            struct OPLandIplParvoParameters OPLandIplParvo;
 +            struct IplMagnoParameters IplMagno;
 +    };
 +
 +Retina parameters files examples
 +++++++++++++++++++++++++++++++++
 +
 +Here is the default configuration file of the retina module. It gives results such as the first retina output shown on the top of this page.
 +
 +.. code-block:: cpp
 +
 +    <?xml version="1.0"?>
 +    <opencv_storage>
 +    <OPLandIPLparvo>
 +        <colorMode>1</colorMode>
 +        <normaliseOutput>1</normaliseOutput>
 +        <photoreceptorsLocalAdaptationSensitivity>7.5e-01</photoreceptorsLocalAdaptationSensitivity>
 +        <photoreceptorsTemporalConstant>9.0e-01</photoreceptorsTemporalConstant>
 +        <photoreceptorsSpatialConstant>5.3e-01</photoreceptorsSpatialConstant>
 +        <horizontalCellsGain>0.01</horizontalCellsGain>
 +        <hcellsTemporalConstant>0.5</hcellsTemporalConstant>
 +        <hcellsSpatialConstant>7.</hcellsSpatialConstant>
 +        <ganglionCellsSensitivity>7.5e-01</ganglionCellsSensitivity></OPLandIPLparvo>
 +    <IPLmagno>
 +        <normaliseOutput>1</normaliseOutput>
 +        <parasolCells_beta>0.</parasolCells_beta>
 +        <parasolCells_tau>0.</parasolCells_tau>
 +        <parasolCells_k>7.</parasolCells_k>
 +        <amacrinCellsTemporalCutFrequency>2.0e+00</amacrinCellsTemporalCutFrequency>
 +        <V0CompressionParameter>9.5e-01</V0CompressionParameter>
 +        <localAdaptintegration_tau>0.</localAdaptintegration_tau>
 +        <localAdaptintegration_k>7.</localAdaptintegration_k></IPLmagno>
 +    </opencv_storage>
 +
 +Here is the 'realistic" setup used to obtain the second retina output shown on the top of this page.
 +
 +.. code-block:: cpp
 +
 +    <?xml version="1.0"?>
 +    <opencv_storage>
 +    <OPLandIPLparvo>
 +      <colorMode>1</colorMode>
 +      <normaliseOutput>1</normaliseOutput>
 +      <photoreceptorsLocalAdaptationSensitivity>8.9e-01</photoreceptorsLocalAdaptationSensitivity>
 +      <photoreceptorsTemporalConstant>9.0e-01</photoreceptorsTemporalConstant>
 +      <photoreceptorsSpatialConstant>5.3e-01</photoreceptorsSpatialConstant>
 +      <horizontalCellsGain>0.3</horizontalCellsGain>
 +      <hcellsTemporalConstant>0.5</hcellsTemporalConstant>
 +      <hcellsSpatialConstant>7.</hcellsSpatialConstant>
 +      <ganglionCellsSensitivity>8.9e-01</ganglionCellsSensitivity></OPLandIPLparvo>
 +    <IPLmagno>
 +      <normaliseOutput>1</normaliseOutput>
 +      <parasolCells_beta>0.</parasolCells_beta>
 +      <parasolCells_tau>0.</parasolCells_tau>
 +      <parasolCells_k>7.</parasolCells_k>
 +      <amacrinCellsTemporalCutFrequency>2.0e+00</amacrinCellsTemporalCutFrequency>
 +      <V0CompressionParameter>9.5e-01</V0CompressionParameter>
 +      <localAdaptintegration_tau>0.</localAdaptintegration_tau>
 +      <localAdaptintegration_k>7.</localAdaptintegration_k></IPLmagno>
 +    </opencv_storage>
@@@ -1155,50 -1053,96 +1155,50 @@@ used in the global 3D geometry optimiza
  :ocv:func:`solvePnP` .
  
  
 +StereoMatcher
 +-------------
 +.. ocv:class:: StereoMatcher : public Algorithm
  
 -StereoBM
 ---------
 -.. ocv:class:: StereoBM
 -
 -Class for computing stereo correspondence using the block matching algorithm. ::
 -
 -    // Block matching stereo correspondence algorithm class StereoBM
 -    {
 -        enum { NORMALIZED_RESPONSE = CV_STEREO_BM_NORMALIZED_RESPONSE,
 -            BASIC_PRESET=CV_STEREO_BM_BASIC,
 -            FISH_EYE_PRESET=CV_STEREO_BM_FISH_EYE,
 -            NARROW_PRESET=CV_STEREO_BM_NARROW };
 -
 -        StereoBM();
 -        // the preset is one of ..._PRESET above.
 -        // ndisparities is the size of disparity range,
 -        // in which the optimal disparity at each pixel is searched for.
 -        // SADWindowSize is the size of averaging window used to match pixel blocks
 -        //    (larger values mean better robustness to noise, but yield blurry disparity maps)
 -        StereoBM(int preset, int ndisparities=0, int SADWindowSize=21);
 -        // separate initialization function
 -        void init(int preset, int ndisparities=0, int SADWindowSize=21);
 -        // computes the disparity for the two rectified 8-bit single-channel images.
 -        // the disparity will be 16-bit signed (fixed-point) or 32-bit floating-point image of the same size as left.
 -        void operator()( InputArray left, InputArray right, OutputArray disparity, int disptype=CV_16S );
 -
 -        Ptr<CvStereoBMState> state;
 -    };
 -
 -The class is a C++ wrapper for the associated functions. In particular, :ocv:funcx:`StereoBM::operator()` is the wrapper for
 -:ocv:cfunc:`cvFindStereoCorrespondenceBM`.
 -
 -.. Sample code:
 -
 -   (Ocl) An example for using the stereoBM matching algorithm can be found at opencv_source_code/samples/ocl/stereo_match.cpp
 -
 -StereoBM::StereoBM
 -------------------
 -The constructors.
 -
 -.. ocv:function:: StereoBM::StereoBM()
 -.. ocv:function:: StereoBM::StereoBM(int preset, int ndisparities=0, int SADWindowSize=21)
 -
 -.. ocv:pyfunction:: cv2.StereoBM([preset[, ndisparities[, SADWindowSize]]]) -> <StereoBM object>
 -
 -.. ocv:cfunction:: CvStereoBMState* cvCreateStereoBMState( int preset=CV_STEREO_BM_BASIC, int numberOfDisparities=0 )
 -
 -.. ocv:pyoldfunction:: cv.CreateStereoBMState(preset=CV_STEREO_BM_BASIC, numberOfDisparities=0)-> CvStereoBMState
 -
 -    :param preset: specifies the whole set of algorithm parameters, one of:
 -
 -            * BASIC_PRESET - parameters suitable for general cameras
 -            * FISH_EYE_PRESET - parameters suitable for wide-angle cameras
 -            * NARROW_PRESET - parameters suitable for narrow-angle cameras
 +The base class for stereo correspondence algorithms.
  
 -        After constructing the class, you can override any parameters set by the preset.
 +StereoMatcher::compute
 +-----------------------
 +Computes disparity map for the specified stereo pair
  
 -    :param ndisparities: the disparity search range. For each pixel algorithm will find the best disparity from 0 (default minimum disparity) to ``ndisparities``. The search range can then be shifted by changing the minimum disparity.
 +.. ocv:function:: void StereoMatcher::compute( InputArray left, InputArray right, OutputArray disparity )
  
 -    :param SADWindowSize: the linear size of the blocks compared by the algorithm. The size should be odd (as the block is centered at the current pixel). Larger block size implies smoother, though less accurate disparity map. Smaller block size gives more detailed disparity map, but there is higher chance for algorithm to find a wrong correspondence.
 +.. ocv:pyfunction:: cv2.StereoBM.compute(left, right[, disparity]) -> disparity
  
 -The constructors initialize ``StereoBM`` state. You can then call ``StereoBM::operator()`` to compute disparity for a specific stereo pair.
 +    :param left: Left 8-bit single-channel image.
  
 -.. note:: In the C API you need to deallocate ``CvStereoBM`` state when it is not needed anymore using ``cvReleaseStereoBMState(&stereobm)``.
 +    :param right: Right image of the same size and the same type as the left one.
  
 -StereoBM::operator()
 ------------------------
 -Computes disparity using the BM algorithm for a rectified stereo pair.
 +    :param disparity: Output disparity map. It has the same size as the input images. Some algorithms, like StereoBM or StereoSGBM compute 16-bit fixed-point disparity map (where each disparity value has 4 fractional bits), whereas other algorithms output 32-bit floating-point disparity map.
  
 -.. ocv:function:: void StereoBM::operator()( InputArray left, InputArray right, OutputArray disparity, int disptype=CV_16S )
  
 -.. ocv:pyfunction:: cv2.StereoBM.compute(left, right[, disparity[, disptype]]) -> disparity
 +StereoBM
 +--------
 +.. ocv:class:: StereoBM : public StereoMatcher
  
 -.. ocv:cfunction:: void cvFindStereoCorrespondenceBM( const CvArr* left, const CvArr* right, CvArr* disparity, CvStereoBMState* state )
 +Class for computing stereo correspondence using the block matching algorithm, introduced and contributed to OpenCV by K. Konolige.
  
 -.. ocv:pyoldfunction:: cv.FindStereoCorrespondenceBM(left, right, disparity, state)-> None
 +.. Sample code:
  
-    * : OCL : An example for using the stereoBM matching algorithm can be found at opencv_source_code/samples/ocl/stereo_match.cpp
 -    :param left: Left 8-bit single-channel image.
++   (Ocl) An example for using the stereoBM matching algorithm can be found at opencv_source_code/samples/ocl/stereo_match.cpp
  
 -    :param right: Right image of the same size and the same type as the left one.
 +createStereoBM
 +------------------
 +Creates StereoBM object
  
 -    :param disparity: Output disparity map. It has the same size as the input images. When ``disptype==CV_16S``, the map is a 16-bit signed single-channel image, containing disparity values scaled by 16. To get the true disparity values from such fixed-point representation, you will need to divide each  ``disp`` element by 16. If ``disptype==CV_32F``, the disparity map will already contain the real disparity values on output.
 +.. ocv:function:: Ptr<StereoBM> createStereoBM(int numDisparities=0, int blockSize=21)
  
 -    :param disptype: Type of the output disparity map, ``CV_16S`` (default) or ``CV_32F``.
 +.. ocv:pyfunction:: cv2.createStereoBM([numDisparities[, blockSize]]) -> retval
  
 -    :param state: The pre-initialized ``CvStereoBMState`` structure in the case of the old API.
 +    :param numDisparities: the disparity search range. For each pixel algorithm will find the best disparity from 0 (default minimum disparity) to ``numDisparities``. The search range can then be shifted by changing the minimum disparity.
  
 -The method executes the BM algorithm on a rectified stereo pair. See the ``stereo_match.cpp`` OpenCV sample on how to prepare images and call the method. Note that the method is not constant, thus you should not use the same ``StereoBM`` instance from within different threads simultaneously. The function is parallelized with the TBB library.
 +    :param blockSize: the linear size of the blocks compared by the algorithm. The size should be odd (as the block is centered at the current pixel). Larger block size implies smoother, though less accurate disparity map. Smaller block size gives more detailed disparity map, but there is higher chance for algorithm to find a wrong correspondence.
  
 +The function create ``StereoBM`` object. You can then call ``StereoBM::compute()`` to compute disparity for a specific stereo pair.
  
  
  StereoSGBM
@@@ -1214,19 -1186,21 +1214,19 @@@ The class implements the modified H. Hi
  
   * Mutual information cost function is not implemented. Instead, a simpler Birchfield-Tomasi sub-pixel metric from [BT98]_ is used. Though, the color images are supported as well.
  
 - * Some pre- and post- processing steps from K. Konolige algorithm :ocv:funcx:`StereoBM::operator()`  are included, for example: pre-filtering (``CV_STEREO_BM_XSOBEL`` type) and post-filtering (uniqueness check, quadratic interpolation and speckle filtering).
 + * Some pre- and post- processing steps from K. Konolige algorithm ``StereoBM``  are included, for example: pre-filtering (``StereoBM::PREFILTER_XSOBEL`` type) and post-filtering (uniqueness check, quadratic interpolation and speckle filtering).
  
- .. Sample code::
+ .. note::
  
-    * : PYTHON : An example illustrating the use of the StereoSGBM matching algorithm can be found at opencv_source_code/samples/python2/stereo_match.py
+    * (Python) An example illustrating the use of the StereoSGBM matching algorithm can be found at opencv_source_code/samples/python2/stereo_match.py
  
 -StereoSGBM::StereoSGBM
 +createStereoSGBM
  --------------------------
 -.. ocv:function:: StereoSGBM::StereoSGBM()
 -
 -.. ocv:function:: StereoSGBM::StereoSGBM( int minDisparity, int numDisparities, int SADWindowSize, int P1=0, int P2=0, int disp12MaxDiff=0, int preFilterCap=0, int uniquenessRatio=0, int speckleWindowSize=0, int speckleRange=0, bool fullDP=false)
 +Creates StereoSGBM object
  
 -.. ocv:pyfunction:: cv2.StereoSGBM([minDisparity, numDisparities, SADWindowSize[, P1[, P2[, disp12MaxDiff[, preFilterCap[, uniquenessRatio[, speckleWindowSize[, speckleRange[, fullDP]]]]]]]]]) -> <StereoSGBM object>
 +.. ocv:function:: Ptr<StereoSGBM> createStereoSGBM( int minDisparity, int numDisparities, int blockSize, int P1=0, int P2=0, int disp12MaxDiff=0, int preFilterCap=0, int uniquenessRatio=0, int speckleWindowSize=0, int speckleRange=0, int mode=StereoSGBM::MODE_SGBM)
  
 -    Initializes ``StereoSGBM`` and sets parameters to custom values.??
 +.. ocv:pyfunction:: cv2.createStereoSGBM(minDisparity, numDisparities, blockSize[, P1[, P2[, disp12MaxDiff[, preFilterCap[, uniquenessRatio[, speckleWindowSize[, speckleRange[, mode]]]]]]]]) -> retval
  
      :param minDisparity: Minimum possible disparity value. Normally, it is zero but sometimes rectification algorithms can shift images, so this parameter needs to be adjusted accordingly.
  
Simple merge
Simple merge
@@@ -479,93 -494,6 +479,93 @@@ Draws several polygonal curves
  The function ``polylines`` draws one or more polygonal curves.
  
  
- .. Sample code::
 +drawContours
 +----------------
 +Draws contours outlines or filled contours.
 +
 +.. ocv:function:: void drawContours( InputOutputArray image, InputArrayOfArrays contours, int contourIdx, const Scalar& color, int thickness=1, int lineType=LINE_8, InputArray hierarchy=noArray(), int maxLevel=INT_MAX, Point offset=Point() )
 +
 +.. ocv:pyfunction:: cv2.drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset]]]]]) -> image
 +
 +.. ocv:cfunction:: void cvDrawContours( CvArr * img, CvSeq* contour, CvScalar external_color, CvScalar hole_color, int max_level, int thickness=1, int line_type=8, CvPoint offset=cvPoint(0,0) )
 +
 +    :param image: Destination image.
 +
 +    :param contours: All the input contours. Each contour is stored as a point vector.
 +
 +    :param contourIdx: Parameter indicating a contour to draw. If it is negative, all the contours are drawn.
 +
 +    :param color: Color of the contours.
 +
 +    :param thickness: Thickness of lines the contours are drawn with. If it is negative (for example,  ``thickness=CV_FILLED`` ), the contour interiors are
 +        drawn.
 +
 +    :param lineType: Line connectivity. See  :ocv:func:`line`  for details.
 +
 +    :param hierarchy: Optional information about hierarchy. It is only needed if you want to draw only some of the  contours (see  ``maxLevel`` ).
 +
 +    :param maxLevel: Maximal level for drawn contours. If it is 0, only
 +        the specified contour is drawn. If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This parameter is only taken into account when there is  ``hierarchy``  available.
 +
 +    :param offset: Optional contour shift parameter. Shift all the drawn contours by the specified  :math:`\texttt{offset}=(dx,dy)` .
 +
 +    :param contour: Pointer to the first contour.
 +
 +    :param external_color: Color of external contours.
 +
 +    :param hole_color: Color of internal contours (holes).
 +
 +The function draws contour outlines in the image if
 +:math:`\texttt{thickness} \ge 0` or fills the area bounded by the contours if
 +:math:`\texttt{thickness}<0` . The example below shows how to retrieve connected components from the binary image and label them: ::
 +
 +    #include "opencv2/imgproc.hpp"
 +    #include "opencv2/highgui.hpp"
 +
 +    using namespace cv;
 +    using namespace std;
 +
 +    int main( int argc, char** argv )
 +    {
 +        Mat src;
 +        // the first command-line parameter must be a filename of the binary
 +        // (black-n-white) image
 +        if( argc != 2 || !(src=imread(argv[1], 0)).data)
 +            return -1;
 +
 +        Mat dst = Mat::zeros(src.rows, src.cols, CV_8UC3);
 +
 +        src = src > 1;
 +        namedWindow( "Source", 1 );
 +        imshow( "Source", src );
 +
 +        vector<vector<Point> > contours;
 +        vector<Vec4i> hierarchy;
 +
 +        findContours( src, contours, hierarchy,
 +            RETR_CCOMP, CHAIN_APPROX_SIMPLE );
 +
 +        // iterate through all the top-level contours,
 +        // draw each connected component with its own random color
 +        int idx = 0;
 +        for( ; idx >= 0; idx = hierarchy[idx][0] )
 +        {
 +            Scalar color( rand()&255, rand()&255, rand()&255 );
 +            drawContours( dst, contours, idx, color, FILLED, 8, hierarchy );
 +        }
 +
 +        namedWindow( "Components", 1 );
 +        imshow( "Components", dst );
 +        waitKey(0);
 +    }
 +
-    * : An example using the drawContour functionality can be found at opencv_source_code/samples/cpp/contours2.cpp
-    * : An example using drawContours to clean up a background segmentation result at opencv_source_code/samples/cpp/segment_objects.cpp
++.. note::
 +
-    * : PYTHON : An example using the drawContour functionality can be found at opencv_source/samples/python2/contours.py
++   * An example using the drawContour functionality can be found at opencv_source_code/samples/cpp/contours2.cpp
++   * An example using drawContours to clean up a background segmentation result at opencv_source_code/samples/cpp/segment_objects.cpp
 +
++   * (Python) An example using the drawContour functionality can be found at opencv_source/samples/python2/contours.py
 +
  
  putText
  -----------
Simple merge
Simple merge
@@@ -9,12 -9,41 +9,12 @@@ that are represented as vectors in a mu
  descriptor matchers inherit the
  :ocv:class:`DescriptorMatcher` interface.
  
- .. Sample code::
+ .. note::
  
-    * An example explaining keypoint matching can be found at opencv_source_code/samples/cpp/descriptor_extractor_matcher.cpp
-    * An example on descriptor matching evaluation can be found at opencv_source_code/samples/cpp/detector_descriptor_matcher_evaluation.cpp
-    * An example on one to many image matching can be found at opencv_source_code/samples/cpp/matching_to_many_images.cpp
+    * An example explaining keypoint matching can be found at opencv_source_code/samples/cpp/descriptor_extractor_matcher.cpp
+    * An example on descriptor matching evaluation can be found at opencv_source_code/samples/cpp/detector_descriptor_matcher_evaluation.cpp
+    * An example on one to many image matching can be found at opencv_source_code/samples/cpp/matching_to_many_images.cpp
  
 -DMatch
 -------
 -.. ocv:struct:: DMatch
 -
 -Class for matching keypoint descriptors: query descriptor index,
 -train descriptor index, train image index, and distance between descriptors. ::
 -
 -    struct DMatch
 -    {
 -        DMatch() : queryIdx(-1), trainIdx(-1), imgIdx(-1),
 -                   distance(std::numeric_limits<float>::max()) {}
 -        DMatch( int _queryIdx, int _trainIdx, float _distance ) :
 -                queryIdx(_queryIdx), trainIdx(_trainIdx), imgIdx(-1),
 -                distance(_distance) {}
 -        DMatch( int _queryIdx, int _trainIdx, int _imgIdx, float _distance ) :
 -                queryIdx(_queryIdx), trainIdx(_trainIdx), imgIdx(_imgIdx),
 -                distance(_distance) {}
 -
 -        int queryIdx; // query descriptor index
 -        int trainIdx; // train descriptor index
 -        int imgIdx;   // train image index
 -
 -        float distance;
 -
 -        // less is better
 -        bool operator<( const DMatch &m ) const;
 -    };
 -
 -
  DescriptorMatcher
  -----------------
  .. ocv:class:: DescriptorMatcher : public Algorithm
@@@ -8,10 -8,70 +8,10 @@@ between different algorithms solving th
  inherit the
  :ocv:class:`FeatureDetector` interface.
  
- .. Sample code::
+ .. note::
  
-    * An example explaining keypoint detection can be found at opencv_source_code/samples/cpp/descriptor_extractor_matcher.cpp
+    * An example explaining keypoint detection can be found at opencv_source_code/samples/cpp/descriptor_extractor_matcher.cpp
  
 -
 -KeyPoint
 ---------
 -.. ocv:class:: KeyPoint
 -
 -  Data structure for salient point detectors.
 -
 -  .. ocv:member:: Point2f pt
 -
 -     coordinates of the keypoint
 -
 -  .. ocv:member:: float size
 -
 -     diameter of the meaningful keypoint neighborhood
 -
 -  .. ocv:member:: float angle
 -
 -     computed orientation of the keypoint (-1 if not applicable). Its possible values are in a range [0,360) degrees. It is measured relative to image coordinate system (y-axis is directed downward), ie in clockwise.
 -
 -  .. ocv:member:: float response
 -
 -     the response by which the most strong keypoints have been selected. Can be used for further sorting or subsampling
 -
 -  .. ocv:member:: int octave
 -
 -     octave (pyramid layer) from which the keypoint has been extracted
 -
 -  .. ocv:member:: int class_id
 -
 -     object id that can be used to clustered keypoints by an object they belong to
 -
 -KeyPoint::KeyPoint
 -------------------
 -The keypoint constructors
 -
 -.. ocv:function:: KeyPoint::KeyPoint()
 -
 -.. ocv:function:: KeyPoint::KeyPoint(Point2f _pt, float _size, float _angle=-1, float _response=0, int _octave=0, int _class_id=-1)
 -
 -.. ocv:function:: KeyPoint::KeyPoint(float x, float y, float _size, float _angle=-1, float _response=0, int _octave=0, int _class_id=-1)
 -
 -.. ocv:pyfunction:: cv2.KeyPoint([x, y, _size[, _angle[, _response[, _octave[, _class_id]]]]]) -> <KeyPoint object>
 -
 -    :param x: x-coordinate of the keypoint
 -
 -    :param y: y-coordinate of the keypoint
 -
 -    :param _pt: x & y coordinates of the keypoint
 -
 -    :param _size: keypoint diameter
 -
 -    :param _angle: keypoint orientation
 -
 -    :param _response: keypoint detector response on the keypoint (that is, strength of the keypoint)
 -
 -    :param _octave: pyramid octave in which the keypoint has been detected
 -
 -    :param _class_id: object id
 -
 -
  FeatureDetector
  ---------------
  .. ocv:class:: FeatureDetector : public Algorithm
@@@ -204,4 -204,4 +204,3 @@@ BOWImgDescriptorExtractor::descriptorTy
  Returns an image descriptor type.
  
  .. ocv:function:: int BOWImgDescriptorExtractor::descriptorType() const
--
Simple merge
index 934afdc,0000000..53e67ea
mode 100644,000000..100644
--- /dev/null
@@@ -1,127 -1,0 +1,127 @@@
- .. Sample code::
 +Background Segmentation
 +=======================
 +
 +.. highlight:: cpp
 +
 +
 +
 +gpu::BackgroundSubtractorMOG
 +----------------------------
 +Gaussian Mixture-based Background/Foreground Segmentation Algorithm.
 +
 +.. ocv:class:: gpu::BackgroundSubtractorMOG : public cv::BackgroundSubtractorMOG
 +
 +The class discriminates between foreground and background pixels by building and maintaining a model of the background. Any pixel which does not fit this model is then deemed to be foreground. The class implements algorithm described in [MOG2001]_.
 +
 +.. seealso:: :ocv:class:`BackgroundSubtractorMOG`
 +
-    * : An example on gaussian mixture based background/foreground segmantation can be found at opencv_source_code/samples/gpu/bgfg_segm.cpp
++.. note::
 +
++   * An example on gaussian mixture based background/foreground segmantation can be found at opencv_source_code/samples/gpu/bgfg_segm.cpp
 +
 +
 +gpu::createBackgroundSubtractorMOG
 +----------------------------------
 +Creates mixture-of-gaussian background subtractor
 +
 +.. ocv:function:: Ptr<gpu::BackgroundSubtractorMOG> gpu::createBackgroundSubtractorMOG(int history=200, int nmixtures=5, double backgroundRatio=0.7, double noiseSigma=0)
 +
 +    :param history: Length of the history.
 +
 +    :param nmixtures: Number of Gaussian mixtures.
 +
 +    :param backgroundRatio: Background ratio.
 +
 +    :param noiseSigma: Noise strength (standard deviation of the brightness or each color channel). 0 means some automatic value.
 +
 +
 +
 +gpu::BackgroundSubtractorMOG2
 +-----------------------------
 +Gaussian Mixture-based Background/Foreground Segmentation Algorithm.
 +
 +.. ocv:class:: gpu::BackgroundSubtractorMOG2 : public cv::BackgroundSubtractorMOG2
 +
 +The class discriminates between foreground and background pixels by building and maintaining a model of the background. Any pixel which does not fit this model is then deemed to be foreground. The class implements algorithm described in [MOG2004]_.
 +
 +.. seealso:: :ocv:class:`BackgroundSubtractorMOG2`
 +
 +
 +
 +gpu::createBackgroundSubtractorMOG2
 +-----------------------------------
 +Creates MOG2 Background Subtractor
 +
 +.. ocv:function:: Ptr<gpu::BackgroundSubtractorMOG2> gpu::createBackgroundSubtractorMOG2( int history=500, double varThreshold=16, bool detectShadows=true )
 +
 +  :param history: Length of the history.
 +
 +  :param varThreshold: Threshold on the squared Mahalanobis distance between the pixel and the model to decide whether a pixel is well described by the background model. This parameter does not affect the background update.
 +
 +  :param detectShadows: If true, the algorithm will detect shadows and mark them. It decreases the speed a bit, so if you do not need this feature, set the parameter to false.
 +
 +
 +
 +gpu::BackgroundSubtractorGMG
 +----------------------------
 +Background/Foreground Segmentation Algorithm.
 +
 +.. ocv:class:: gpu::BackgroundSubtractorGMG : public cv::BackgroundSubtractorGMG
 +
 +The class discriminates between foreground and background pixels by building and maintaining a model of the background. Any pixel which does not fit this model is then deemed to be foreground. The class implements algorithm described in [GMG2012]_.
 +
 +
 +
 +gpu::createBackgroundSubtractorGMG
 +----------------------------------
 +Creates GMG Background Subtractor
 +
 +.. ocv:function:: Ptr<gpu::BackgroundSubtractorGMG> gpu::createBackgroundSubtractorGMG(int initializationFrames = 120, double decisionThreshold = 0.8)
 +
 +    :param initializationFrames: Number of frames of video to use to initialize histograms.
 +
 +    :param decisionThreshold: Value above which pixel is determined to be FG.
 +
 +
 +
 +gpu::BackgroundSubtractorFGD
 +----------------------------
 +
 +.. ocv:class:: gpu::BackgroundSubtractorFGD : public cv::BackgroundSubtractor
 +
 +The class discriminates between foreground and background pixels by building and maintaining a model of the background. Any pixel which does not fit this model is then deemed to be foreground. The class implements algorithm described in [FGD2003]_. ::
 +
 +    class CV_EXPORTS BackgroundSubtractorFGD : public cv::BackgroundSubtractor
 +    {
 +    public:
 +        virtual void getForegroundRegions(OutputArrayOfArrays foreground_regions) = 0;
 +    };
 +
 +.. seealso:: :ocv:class:`BackgroundSubtractor`
 +
 +
 +
 +gpu::BackgroundSubtractorFGD::getForegroundRegions
 +--------------------------------------------------
 +Returns the output foreground regions calculated by :ocv:func:`findContours`.
 +
 +.. ocv:function:: void gpu::BackgroundSubtractorFGD::getForegroundRegions(OutputArrayOfArrays foreground_regions)
 +
 +    :params foreground_regions: Output array (CPU memory).
 +
 +
 +
 +gpu::createBackgroundSubtractorFGD
 +----------------------------------
 +Creates FGD Background Subtractor
 +
 +.. ocv:function:: Ptr<gpu::BackgroundSubtractorGMG> gpu::createBackgroundSubtractorFGD(const FGDParams& params = FGDParams())
 +
 +    :param params: Algorithm's parameters. See [FGD2003]_ for explanation.
 +
 +
 +
 +.. [FGD2003] Liyuan Li, Weimin Huang, Irene Y.H. Gu, and Qi Tian. *Foreground Object Detection from Videos Containing Complex Background*. ACM MM2003 9p, 2003.
 +.. [MOG2001] P. KadewTraKuPong and R. Bowden. *An improved adaptive background mixture model for real-time tracking with shadow detection*. Proc. 2nd European Workshop on Advanced Video-Based Surveillance Systems, 2001
 +.. [MOG2004] Z. Zivkovic. *Improved adaptive Gausian mixture model for background subtraction*. International Conference Pattern Recognition, UK, August, 2004
 +.. [GMG2012] A. Godbehere, A. Matsukawa and K. Goldberg. *Visual Tracking of Human Visitors under Variable-Lighting Conditions for a Responsive Audio Art Installation*. American Control Conference, Montreal, June 2012
index 646f875,0000000..dbf8951
mode 100644,000000..100644
--- /dev/null
@@@ -1,156 -1,0 +1,156 @@@
- .. Sample code::
 +Video Decoding
 +==============
 +
 +.. highlight:: cpp
 +
 +
 +
 +gpucodec::VideoReader
 +---------------------
 +Video reader interface.
 +
 +.. ocv:class:: gpucodec::VideoReader
 +
-    * : An example on how to use the videoReader class can be found at opencv_source_code/samples/gpu/video_reader.cpp
++.. note::
 +
++   * An example on how to use the videoReader class can be found at opencv_source_code/samples/gpu/video_reader.cpp
 +
 +
 +gpucodec::VideoReader::nextFrame
 +--------------------------------
 +Grabs, decodes and returns the next video frame.
 +
 +.. ocv:function:: bool gpucodec::VideoReader::nextFrame(OutputArray frame)
 +
 +If no frames has been grabbed (there are no more frames in video file), the methods return ``false`` . The method throws :ocv:class:`Exception` if error occurs.
 +
 +
 +
 +gpucodec::VideoReader::format
 +-----------------------------
 +Returns information about video file format.
 +
 +.. ocv:function:: FormatInfo gpucodec::VideoReader::format() const
 +
 +
 +
 +gpucodec::Codec
 +---------------
 +Video codecs supported by :ocv:class:`gpucodec::VideoReader` .
 +
 +.. ocv:enum:: gpucodec::Codec
 +
 +  .. ocv:emember:: MPEG1 = 0
 +  .. ocv:emember:: MPEG2
 +  .. ocv:emember:: MPEG4
 +  .. ocv:emember:: VC1
 +  .. ocv:emember:: H264
 +  .. ocv:emember:: JPEG
 +  .. ocv:emember:: H264_SVC
 +  .. ocv:emember:: H264_MVC
 +
 +  .. ocv:emember:: Uncompressed_YUV420 = (('I'<<24)|('Y'<<16)|('U'<<8)|('V'))
 +
 +        Y,U,V (4:2:0)
 +
 +  .. ocv:emember:: Uncompressed_YV12   = (('Y'<<24)|('V'<<16)|('1'<<8)|('2'))
 +
 +        Y,V,U (4:2:0)
 +
 +  .. ocv:emember:: Uncompressed_NV12   = (('N'<<24)|('V'<<16)|('1'<<8)|('2'))
 +
 +        Y,UV  (4:2:0)
 +
 +  .. ocv:emember:: Uncompressed_YUYV   = (('Y'<<24)|('U'<<16)|('Y'<<8)|('V'))
 +
 +        YUYV/YUY2 (4:2:2)
 +
 +  .. ocv:emember:: Uncompressed_UYVY   = (('U'<<24)|('Y'<<16)|('V'<<8)|('Y'))
 +
 +        UYVY (4:2:2)
 +
 +
 +
 +gpucodec::ChromaFormat
 +----------------------
 +Chroma formats supported by :ocv:class:`gpucodec::VideoReader` .
 +
 +.. ocv:enum:: gpucodec::ChromaFormat
 +
 +  .. ocv:emember:: Monochrome = 0
 +  .. ocv:emember:: YUV420
 +  .. ocv:emember:: YUV422
 +  .. ocv:emember:: YUV444
 +
 +
 +
 +gpucodec::FormatInfo
 +--------------------
 +.. ocv:struct:: gpucodec::FormatInfo
 +
 +Struct providing information about video file format. ::
 +
 +    struct FormatInfo
 +    {
 +        Codec codec;
 +        ChromaFormat chromaFormat;
 +        int width;
 +        int height;
 +    };
 +
 +
 +
 +gpucodec::createVideoReader
 +---------------------------
 +Creates video reader.
 +
 +.. ocv:function:: Ptr<VideoReader> gpucodec::createVideoReader(const String& filename)
 +.. ocv:function:: Ptr<VideoReader> gpucodec::createVideoReader(const Ptr<RawVideoSource>& source)
 +
 +    :param filename: Name of the input video file.
 +
 +    :param source: RAW video source implemented by user.
 +
 +FFMPEG is used to read videos. User can implement own demultiplexing with :ocv:class:`gpucodec::RawVideoSource` .
 +
 +
 +
 +gpucodec::RawVideoSource
 +------------------------
 +.. ocv:class:: gpucodec::RawVideoSource
 +
 +Interface for video demultiplexing. ::
 +
 +    class RawVideoSource
 +    {
 +    public:
 +        virtual ~RawVideoSource() {}
 +
 +        virtual bool getNextPacket(unsigned char** data, int* size, bool* endOfFile) = 0;
 +
 +        virtual FormatInfo format() const = 0;
 +    };
 +
 +User can implement own demultiplexing by implementing this interface.
 +
 +
 +
 +gpucodec::RawVideoSource::getNextPacket
 +---------------------------------------
 +Returns next packet with RAW video frame.
 +
 +.. ocv:function:: bool gpucodec::VideoSource::getNextPacket(unsigned char** data, int* size, bool* endOfFile) = 0
 +
 +    :param data: Pointer to frame data.
 +
 +    :param size: Size in bytes of current frame.
 +
 +    :param endOfStream: Indicates that it is end of stream.
 +
 +
 +
 +gpucodec::RawVideoSource::format
 +--------------------------------
 +Returns information about video file format.
 +
 +.. ocv:function:: virtual FormatInfo gpucodec::RawVideoSource::format() const = 0
index f1e20dc,0000000..d4a6814
mode 100644,000000..100644
--- /dev/null
@@@ -1,192 -1,0 +1,192 @@@
- .. Sample code::
 +Video Encoding
 +==============
 +
 +.. highlight:: cpp
 +
 +
 +
 +gpucodec::VideoWriter
 +---------------------
 +Video writer interface.
 +
 +.. ocv:class:: gpucodec::VideoWriter
 +
 +The implementation uses H264 video codec.
 +
 +.. note:: Currently only Windows platform is supported.
 +
-    * : An example on how to use the videoWriter class can be found at opencv_source_code/samples/gpu/video_writer.cpp
++.. note::
 +
++   * An example on how to use the videoWriter class can be found at opencv_source_code/samples/gpu/video_writer.cpp
 +
 +
 +gpucodec::VideoWriter::write
 +----------------------------
 +Writes the next video frame.
 +
 +.. ocv:function:: void gpucodec::VideoWriter::write(InputArray frame, bool lastFrame = false) = 0
 +
 +    :param frame: The written frame.
 +
 +    :param lastFrame: Indicates that it is end of stream. The parameter can be ignored.
 +
 +The method write the specified image to video file. The image must have the same size and the same surface format as has been specified when opening the video writer.
 +
 +
 +
 +gpucodec::createVideoWriter
 +---------------------------
 +Creates video writer.
 +
 +.. ocv:function:: Ptr<gpucodec::VideoWriter> gpucodec::createVideoWriter(const String& fileName, Size frameSize, double fps, SurfaceFormat format = SF_BGR)
 +.. ocv:function:: Ptr<gpucodec::VideoWriter> gpucodec::createVideoWriter(const String& fileName, Size frameSize, double fps, const EncoderParams& params, SurfaceFormat format = SF_BGR)
 +.. ocv:function:: Ptr<gpucodec::VideoWriter> gpucodec::createVideoWriter(const Ptr<EncoderCallBack>& encoderCallback, Size frameSize, double fps, SurfaceFormat format = SF_BGR)
 +.. ocv:function:: Ptr<gpucodec::VideoWriter> gpucodec::createVideoWriter(const Ptr<EncoderCallBack>& encoderCallback, Size frameSize, double fps, const EncoderParams& params, SurfaceFormat format = SF_BGR)
 +
 +    :param fileName: Name of the output video file. Only AVI file format is supported.
 +
 +    :param frameSize: Size of the input video frames.
 +
 +    :param fps: Framerate of the created video stream.
 +
 +    :param params: Encoder parameters. See :ocv:struct:`gpucodec::EncoderParams` .
 +
 +    :param format: Surface format of input frames ( ``SF_UYVY`` , ``SF_YUY2`` , ``SF_YV12`` , ``SF_NV12`` , ``SF_IYUV`` , ``SF_BGR`` or ``SF_GRAY``). BGR or gray frames will be converted to YV12 format before encoding, frames with other formats will be used as is.
 +
 +    :param encoderCallback: Callbacks for video encoder. See :ocv:class:`gpucodec::EncoderCallBack` . Use it if you want to work with raw video stream.
 +
 +The constructors initialize video writer. FFMPEG is used to write videos. User can implement own multiplexing with :ocv:class:`gpucodec::EncoderCallBack` .
 +
 +
 +
 +gpucodec::EncoderParams
 +-----------------------
 +.. ocv:struct:: gpucodec::EncoderParams
 +
 +Different parameters for CUDA video encoder. ::
 +
 +    struct EncoderParams
 +    {
 +        int       P_Interval;      //    NVVE_P_INTERVAL,
 +        int       IDR_Period;      //    NVVE_IDR_PERIOD,
 +        int       DynamicGOP;      //    NVVE_DYNAMIC_GOP,
 +        int       RCType;          //    NVVE_RC_TYPE,
 +        int       AvgBitrate;      //    NVVE_AVG_BITRATE,
 +        int       PeakBitrate;     //    NVVE_PEAK_BITRATE,
 +        int       QP_Level_Intra;  //    NVVE_QP_LEVEL_INTRA,
 +        int       QP_Level_InterP; //    NVVE_QP_LEVEL_INTER_P,
 +        int       QP_Level_InterB; //    NVVE_QP_LEVEL_INTER_B,
 +        int       DeblockMode;     //    NVVE_DEBLOCK_MODE,
 +        int       ProfileLevel;    //    NVVE_PROFILE_LEVEL,
 +        int       ForceIntra;      //    NVVE_FORCE_INTRA,
 +        int       ForceIDR;        //    NVVE_FORCE_IDR,
 +        int       ClearStat;       //    NVVE_CLEAR_STAT,
 +        int       DIMode;          //    NVVE_SET_DEINTERLACE,
 +        int       Presets;         //    NVVE_PRESETS,
 +        int       DisableCabac;    //    NVVE_DISABLE_CABAC,
 +        int       NaluFramingType; //    NVVE_CONFIGURE_NALU_FRAMING_TYPE
 +        int       DisableSPSPPS;   //    NVVE_DISABLE_SPS_PPS
 +
 +        EncoderParams();
 +        explicit EncoderParams(const String& configFile);
 +
 +        void load(const String& configFile);
 +        void save(const String& configFile) const;
 +    };
 +
 +
 +
 +gpucodec::EncoderParams::EncoderParams
 +--------------------------------------
 +Constructors.
 +
 +.. ocv:function:: gpucodec::EncoderParams::EncoderParams()
 +.. ocv:function:: gpucodec::EncoderParams::EncoderParams(const String& configFile)
 +
 +    :param configFile: Config file name.
 +
 +Creates default parameters or reads parameters from config file.
 +
 +
 +
 +gpucodec::EncoderParams::load
 +-----------------------------
 +Reads parameters from config file.
 +
 +.. ocv:function:: void gpucodec::EncoderParams::load(const String& configFile)
 +
 +    :param configFile: Config file name.
 +
 +
 +
 +gpucodec::EncoderParams::save
 +-----------------------------
 +Saves parameters to config file.
 +
 +.. ocv:function:: void gpucodec::EncoderParams::save(const String& configFile) const
 +
 +    :param configFile: Config file name.
 +
 +
 +
 +gpucodec::EncoderCallBack
 +-------------------------
 +.. ocv:class:: gpucodec::EncoderCallBack
 +
 +Callbacks for CUDA video encoder. ::
 +
 +    class EncoderCallBack
 +    {
 +    public:
 +        enum PicType
 +        {
 +            IFRAME = 1,
 +            PFRAME = 2,
 +            BFRAME = 3
 +        };
 +
 +        virtual ~EncoderCallBack() {}
 +
 +        virtual unsigned char* acquireBitStream(int* bufferSize) = 0;
 +        virtual void releaseBitStream(unsigned char* data, int size) = 0;
 +        virtual void onBeginFrame(int frameNumber, PicType picType) = 0;
 +        virtual void onEndFrame(int frameNumber, PicType picType) = 0;
 +    };
 +
 +
 +
 +gpucodec::EncoderCallBack::acquireBitStream
 +-------------------------------------------
 +Callback function to signal the start of bitstream that is to be encoded.
 +
 +.. ocv:function:: virtual uchar* gpucodec::EncoderCallBack::acquireBitStream(int* bufferSize) = 0
 +
 +Callback must allocate buffer for CUDA encoder and return pointer to it and it's size.
 +
 +
 +
 +gpucodec::EncoderCallBack::releaseBitStream
 +-------------------------------------------
 +Callback function to signal that the encoded bitstream is ready to be written to file.
 +
 +.. ocv:function:: virtual void gpucodec::EncoderCallBack::releaseBitStream(unsigned char* data, int size) = 0
 +
 +
 +
 +gpucodec::EncoderCallBack::onBeginFrame
 +---------------------------------------
 +Callback function to signal that the encoding operation on the frame has started.
 +
 +.. ocv:function:: virtual void gpucodec::EncoderCallBack::onBeginFrame(int frameNumber, PicType picType) = 0
 +
 +    :param picType: Specify frame type (I-Frame, P-Frame or B-Frame).
 +
 +
 +
 +gpucodec::EncoderCallBack::onEndFrame
 +-------------------------------------
 +Callback function signals that the encoding operation on the frame has finished.
 +
 +.. ocv:function:: virtual void gpucodec::EncoderCallBack::onEndFrame(int frameNumber, PicType picType) = 0
 +
 +    :param picType: Specify frame type (I-Frame, P-Frame or B-Frame).
index 4e90961,0000000..cb824bf
mode 100644,000000..100644
--- /dev/null
@@@ -1,336 -1,0 +1,336 @@@
- .. Sample code::
 +Image Filtering
 +===============
 +
 +.. highlight:: cpp
 +
 +Functions and classes described in this section are used to perform various linear or non-linear filtering operations on 2D images.
 +
-    * : An example containing all basic morphology operators like erode and dilate can be found at opencv_source_code/samples/gpu/morphology.cpp
++.. note::
 +
++   * An example containing all basic morphology operators like erode and dilate can be found at opencv_source_code/samples/gpu/morphology.cpp
 +
 +gpu::Filter
 +-----------
 +.. ocv:class:: gpu::Filter
 +
 +Common interface for all GPU filters ::
 +
 +    class CV_EXPORTS Filter : public Algorithm
 +    {
 +    public:
 +        virtual void apply(InputArray src, OutputArray dst, Stream& stream = Stream::Null()) = 0;
 +    };
 +
 +
 +
 +gpu::Filter::apply
 +------------------
 +Applies the specified filter to the image.
 +
 +.. ocv:function:: void gpu::Filter::apply(InputArray src, OutputArray dst, Stream& stream = Stream::Null()) = 0
 +
 +    :param src: Input image.
 +
 +    :param dst: Output image.
 +
 +    :param stream: Stream for the asynchronous version.
 +
 +
 +
 +gpu::createBoxFilter
 +--------------------
 +Creates a normalized 2D box filter.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createBoxFilter(int srcType, int dstType, Size ksize, Point anchor = Point(-1,-1), int borderMode = BORDER_DEFAULT, Scalar borderVal = Scalar::all(0))
 +
 +    :param srcType: Input image type. Only ``CV_8UC1`` and ``CV_8UC4`` are supported for now.
 +
 +    :param dstType: Output image type. Only the same type as ``src`` is supported for now.
 +
 +    :param ksize: Kernel size.
 +
 +    :param anchor: Anchor point. The default value ``Point(-1, -1)`` means that the anchor is at the kernel center.
 +
 +    :param borderMode: Pixel extrapolation method. For details, see :ocv:func:`borderInterpolate` .
 +
 +    :param borderVal: Default border value.
 +
 +.. seealso:: :ocv:func:`boxFilter`
 +
 +
 +
 +gpu::createLinearFilter
 +-----------------------
 +Creates a non-separable linear 2D filter.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createLinearFilter(int srcType, int dstType, InputArray kernel, Point anchor = Point(-1,-1), int borderMode = BORDER_DEFAULT, Scalar borderVal = Scalar::all(0))
 +
 +    :param srcType: Input image type. Supports  ``CV_8U``  ,  ``CV_16U``  and  ``CV_32F``  one and four channel image.
 +
 +    :param dstType: Output image type. Only the same type as ``src`` is supported for now.
 +
 +    :param kernel: 2D array of filter coefficients.
 +
 +    :param anchor: Anchor point. The default value Point(-1, -1) means that the anchor is at the kernel center.
 +
 +    :param borderMode: Pixel extrapolation method. For details, see :ocv:func:`borderInterpolate` .
 +
 +    :param borderVal: Default border value.
 +
 +.. seealso:: :ocv:func:`filter2D`
 +
 +
 +
 +gpu::createLaplacianFilter
 +--------------------------
 +Creates a Laplacian operator.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createLaplacianFilter(int srcType, int dstType, int ksize = 1, double scale = 1, int borderMode = BORDER_DEFAULT, Scalar borderVal = Scalar::all(0))
 +
 +    :param srcType: Input image type. Supports  ``CV_8U``  ,  ``CV_16U``  and  ``CV_32F``  one and four channel image.
 +
 +    :param dstType: Output image type. Only the same type as ``src`` is supported for now.
 +
 +    :param ksize: Aperture size used to compute the second-derivative filters (see :ocv:func:`getDerivKernels`). It must be positive and odd. Only  ``ksize``  = 1 and  ``ksize``  = 3 are supported.
 +
 +    :param scale: Optional scale factor for the computed Laplacian values. By default, no scaling is applied (see  :ocv:func:`getDerivKernels` ).
 +
 +    :param borderMode: Pixel extrapolation method. For details, see :ocv:func:`borderInterpolate` .
 +
 +    :param borderVal: Default border value.
 +
 +.. seealso:: :ocv:func:`Laplacian`
 +
 +
 +
 +gpu::createSeparableLinearFilter
 +--------------------------------
 +Creates a separable linear filter.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createSeparableLinearFilter(int srcType, int dstType, InputArray rowKernel, InputArray columnKernel, Point anchor = Point(-1,-1), int rowBorderMode = BORDER_DEFAULT, int columnBorderMode = -1)
 +
 +    :param srcType: Source array type.
 +
 +    :param dstType: Destination array type.
 +
 +    :param rowKernel: Horizontal filter coefficients. Support kernels with ``size <= 32`` .
 +
 +    :param columnKernel: Vertical filter coefficients. Support kernels with ``size <= 32`` .
 +
 +    :param anchor: Anchor position within the kernel. Negative values mean that anchor is positioned at the aperture center.
 +
 +    :param rowBorderMode: Pixel extrapolation method in the vertical direction For details, see  :ocv:func:`borderInterpolate`.
 +
 +    :param columnBorderMode: Pixel extrapolation method in the horizontal direction.
 +
 +.. seealso:: :ocv:func:`sepFilter2D`
 +
 +
 +
 +gpu::createDerivFilter
 +----------------------
 +Creates a generalized Deriv operator.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createDerivFilter(int srcType, int dstType, int dx, int dy, int ksize, bool normalize = false, double scale = 1, int rowBorderMode = BORDER_DEFAULT, int columnBorderMode = -1)
 +
 +    :param srcType: Source image type.
 +
 +    :param dstType: Destination array type.
 +
 +    :param dx: Derivative order in respect of x.
 +
 +    :param dy: Derivative order in respect of y.
 +
 +    :param ksize: Aperture size. See  :ocv:func:`getDerivKernels` for details.
 +
 +    :param normalize: Flag indicating whether to normalize (scale down) the filter coefficients or not. See  :ocv:func:`getDerivKernels` for details.
 +
 +    :param scale: Optional scale factor for the computed derivative values. By default, no scaling is applied. For details, see  :ocv:func:`getDerivKernels` .
 +
 +    :param rowBorderMode: Pixel extrapolation method in the vertical direction. For details, see  :ocv:func:`borderInterpolate`.
 +
 +    :param columnBorderMode: Pixel extrapolation method in the horizontal direction.
 +
 +
 +
 +gpu::createSobelFilter
 +----------------------
 +Creates a Sobel operator.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createSobelFilter(int srcType, int dstType, int dx, int dy, int ksize = 3, double scale = 1, int rowBorderMode = BORDER_DEFAULT, int columnBorderMode = -1)
 +
 +    :param srcType: Source image type.
 +
 +    :param dstType: Destination array type.
 +
 +    :param dx: Derivative order in respect of x.
 +
 +    :param dy: Derivative order in respect of y.
 +
 +    :param ksize: Size of the extended Sobel kernel. Possible values are 1, 3, 5 or 7.
 +
 +    :param scale: Optional scale factor for the computed derivative values. By default, no scaling is applied. For details, see  :ocv:func:`getDerivKernels` .
 +
 +    :param rowBorderMode: Pixel extrapolation method in the vertical direction. For details, see  :ocv:func:`borderInterpolate`.
 +
 +    :param columnBorderMode: Pixel extrapolation method in the horizontal direction.
 +
 +.. seealso:: :ocv:func:`Sobel`
 +
 +
 +
 +gpu::createScharrFilter
 +-----------------------
 +Creates a vertical or horizontal Scharr operator.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createScharrFilter(int srcType, int dstType, int dx, int dy, double scale = 1, int rowBorderMode = BORDER_DEFAULT, int columnBorderMode = -1)
 +
 +    :param srcType: Source image type.
 +
 +    :param dstType: Destination array type.
 +
 +    :param dx: Order of the derivative x.
 +
 +    :param dy: Order of the derivative y.
 +
 +    :param scale: Optional scale factor for the computed derivative values. By default, no scaling is applied. See  :ocv:func:`getDerivKernels`  for details.
 +
 +    :param rowBorderMode: Pixel extrapolation method in the vertical direction. For details, see  :ocv:func:`borderInterpolate`.
 +
 +    :param columnBorderMode: Pixel extrapolation method in the horizontal direction.
 +
 +.. seealso:: :ocv:func:`Scharr`
 +
 +
 +
 +gpu::createGaussianFilter
 +-------------------------
 +Creates a Gaussian filter.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createGaussianFilter(int srcType, int dstType, Size ksize, double sigma1, double sigma2 = 0, int rowBorderMode = BORDER_DEFAULT, int columnBorderMode = -1)
 +
 +    :param srcType: Source image type.
 +
 +    :param dstType: Destination array type.
 +
 +    :param ksize: Aperture size. See  :ocv:func:`getGaussianKernel` for details.
 +
 +    :param sigma1: Gaussian sigma in the horizontal direction. See  :ocv:func:`getGaussianKernel` for details.
 +
 +    :param sigma2: Gaussian sigma in the vertical direction. If 0, then  :math:`\texttt{sigma2}\leftarrow\texttt{sigma1}` .
 +
 +    :param rowBorderMode: Pixel extrapolation method in the vertical direction. For details, see  :ocv:func:`borderInterpolate`.
 +
 +    :param columnBorderMode: Pixel extrapolation method in the horizontal direction.
 +
 +.. seealso:: :ocv:func:`GaussianBlur`
 +
 +
 +
 +gpu::createMorphologyFilter
 +---------------------------
 +Creates a 2D morphological filter.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createMorphologyFilter(int op, int srcType, InputArray kernel, Point anchor = Point(-1, -1), int iterations = 1)
 +
 +    :param op: Type of morphological operation. The following types are possible:
 +
 +        * **MORPH_ERODE** erode
 +
 +        * **MORPH_DILATE** dilate
 +
 +        * **MORPH_OPEN** opening
 +
 +        * **MORPH_CLOSE** closing
 +
 +        * **MORPH_GRADIENT** morphological gradient
 +
 +        * **MORPH_TOPHAT** "top hat"
 +
 +        * **MORPH_BLACKHAT** "black hat"
 +
 +    :param srcType: Input/output image type. Only  ``CV_8UC1``  and  ``CV_8UC4``  are supported.
 +
 +    :param kernel: 2D 8-bit structuring element for the morphological operation.
 +
 +    :param anchor: Anchor position within the structuring element. Negative values mean that the anchor is at the center.
 +
 +    :param iterations: Number of times erosion and dilation to be applied.
 +
 +.. seealso:: :ocv:func:`morphologyEx`
 +
 +
 +
 +gpu::createBoxMaxFilter
 +-----------------------
 +Creates the maximum filter.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createBoxMaxFilter(int srcType, Size ksize, Point anchor = Point(-1, -1), int borderMode = BORDER_DEFAULT, Scalar borderVal = Scalar::all(0))
 +
 +    :param srcType: Input/output image type. Only  ``CV_8UC1``  and  ``CV_8UC4`` are supported.
 +
 +    :param ksize: Kernel size.
 +
 +    :param anchor: Anchor point. The default value (-1) means that the anchor is at the kernel center.
 +
 +    :param borderMode: Pixel extrapolation method. For details, see :ocv:func:`borderInterpolate` .
 +
 +    :param borderVal: Default border value.
 +
 +
 +
 +gpu::createBoxMinFilter
 +-----------------------
 +Creates the minimum filter.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createBoxMinFilter(int srcType, Size ksize, Point anchor = Point(-1, -1), int borderMode = BORDER_DEFAULT, Scalar borderVal = Scalar::all(0))
 +
 +    :param srcType: Input/output image type. Only  ``CV_8UC1``  and  ``CV_8UC4`` are supported.
 +
 +    :param ksize: Kernel size.
 +
 +    :param anchor: Anchor point. The default value (-1) means that the anchor is at the kernel center.
 +
 +    :param borderMode: Pixel extrapolation method. For details, see :ocv:func:`borderInterpolate` .
 +
 +    :param borderVal: Default border value.
 +
 +
 +
 +gpu::createRowSumFilter
 +-----------------------
 +Creates a horizontal 1D box filter.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createRowSumFilter(int srcType, int dstType, int ksize, int anchor = -1, int borderMode = BORDER_DEFAULT, Scalar borderVal = Scalar::all(0))
 +
 +    :param srcType: Input image type. Only ``CV_8UC1`` type is supported for now.
 +
 +    :param sumType: Output image type. Only ``CV_32FC1`` type is supported for now.
 +
 +    :param ksize: Kernel size.
 +
 +    :param anchor: Anchor point. The default value (-1) means that the anchor is at the kernel center.
 +
 +    :param borderMode: Pixel extrapolation method. For details, see :ocv:func:`borderInterpolate` .
 +
 +    :param borderVal: Default border value.
 +
 +
 +
 +gpu::createColumnSumFilter
 +--------------------------
 +Creates a vertical 1D box filter.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createColumnSumFilter(int srcType, int dstType, int ksize, int anchor = -1, int borderMode = BORDER_DEFAULT, Scalar borderVal = Scalar::all(0))
 +
 +    :param srcType: Input image type. Only ``CV_8UC1`` type is supported for now.
 +
 +    :param sumType: Output image type. Only ``CV_32FC1`` type is supported for now.
 +
 +    :param ksize: Kernel size.
 +
 +    :param anchor: Anchor point. The default value (-1) means that the anchor is at the kernel center.
 +
 +    :param borderMode: Pixel extrapolation method. For details, see :ocv:func:`borderInterpolate` .
 +
 +    :param borderVal: Default border value.
index f3863cb,0000000..b1e8e03
mode 100644,000000..100644
--- /dev/null
@@@ -1,131 -1,0 +1,131 @@@
- .. Sample code::
 +Color space processing
 +======================
 +
 +.. highlight:: cpp
 +
 +
 +
 +gpu::cvtColor
 +-------------
 +Converts an image from one color space to another.
 +
 +.. ocv:function:: void gpu::cvtColor(InputArray src, OutputArray dst, int code, int dcn = 0, Stream& stream = Stream::Null())
 +
 +    :param src: Source image with  ``CV_8U`` , ``CV_16U`` , or  ``CV_32F`` depth and 1, 3, or 4 channels.
 +
 +    :param dst: Destination image.
 +
 +    :param code: Color space conversion code. For details, see  :ocv:func:`cvtColor` .
 +
 +    :param dcn: Number of channels in the destination image. If the parameter is 0, the number of the channels is derived automatically from  ``src`` and the  ``code`` .
 +
 +    :param stream: Stream for the asynchronous version.
 +
 +3-channel color spaces (like ``HSV``, ``XYZ``, and so on) can be stored in a 4-channel image for better performance.
 +
 +.. seealso:: :ocv:func:`cvtColor`
 +
 +
 +
 +gpu::demosaicing
 +----------------
 +Converts an image from Bayer pattern to RGB or grayscale.
 +
 +.. ocv:function:: void gpu::demosaicing(InputArray src, OutputArray dst, int code, int dcn = -1, Stream& stream = Stream::Null())
 +
 +    :param src: Source image (8-bit or 16-bit single channel).
 +
 +    :param dst: Destination image.
 +
 +    :param code: Color space conversion code (see the description below).
 +
 +    :param dcn: Number of channels in the destination image. If the parameter is 0, the number of the channels is derived automatically from  ``src`` and the  ``code`` .
 +
 +    :param stream: Stream for the asynchronous version.
 +
 +The function can do the following transformations:
 +
 +* Demosaicing using bilinear interpolation
 +
 +    * ``COLOR_BayerBG2GRAY`` , ``COLOR_BayerGB2GRAY`` , ``COLOR_BayerRG2GRAY`` , ``COLOR_BayerGR2GRAY``
 +
 +    * ``COLOR_BayerBG2BGR`` , ``COLOR_BayerGB2BGR`` , ``COLOR_BayerRG2BGR`` , ``COLOR_BayerGR2BGR``
 +
 +* Demosaicing using Malvar-He-Cutler algorithm ([MHT2011]_)
 +
 +    * ``COLOR_BayerBG2GRAY_MHT`` , ``COLOR_BayerGB2GRAY_MHT`` , ``COLOR_BayerRG2GRAY_MHT`` , ``COLOR_BayerGR2GRAY_MHT``
 +
 +    * ``COLOR_BayerBG2BGR_MHT`` , ``COLOR_BayerGB2BGR_MHT`` , ``COLOR_BayerRG2BGR_MHT`` , ``COLOR_BayerGR2BGR_MHT``
 +
 +.. seealso:: :ocv:func:`cvtColor`
 +
 +
 +
 +gpu::swapChannels
 +-----------------
 +Exchanges the color channels of an image in-place.
 +
 +.. ocv:function:: void gpu::swapChannels(InputOutputArray image, const int dstOrder[4], Stream& stream = Stream::Null())
 +
 +    :param image: Source image. Supports only ``CV_8UC4`` type.
 +
 +    :param dstOrder: Integer array describing how channel values are permutated. The n-th entry of the array contains the number of the channel that is stored in the n-th channel of the output image. E.g. Given an RGBA image, aDstOrder = [3,2,1,0] converts this to ABGR channel order.
 +
 +    :param stream: Stream for the asynchronous version.
 +
 +The methods support arbitrary permutations of the original channels, including replication.
 +
 +
 +
 +gpu::gammaCorrection
 +--------------------
 +Routines for correcting image color gamma.
 +
 +.. ocv:function:: void gpu::gammaCorrection(InputArray src, OutputArray dst, bool forward = true, Stream& stream = Stream::Null())
 +
 +    :param src: Source image (3- or 4-channel 8 bit).
 +
 +    :param dst: Destination image.
 +
 +    :param forward: ``true`` for forward gamma correction or ``false`` for inverse gamma correction.
 +
 +    :param stream: Stream for the asynchronous version.
 +
 +
 +
 +gpu::alphaComp
 +--------------
 +Composites two images using alpha opacity values contained in each image.
 +
 +.. ocv:function:: void gpu::alphaComp(InputArray img1, InputArray img2, OutputArray dst, int alpha_op, Stream& stream = Stream::Null())
 +
 +    :param img1: First image. Supports ``CV_8UC4`` , ``CV_16UC4`` , ``CV_32SC4`` and ``CV_32FC4`` types.
 +
 +    :param img2: Second image. Must have the same size and the same type as ``img1`` .
 +
 +    :param dst: Destination image.
 +
 +    :param alpha_op: Flag specifying the alpha-blending operation:
 +
 +            * **ALPHA_OVER**
 +            * **ALPHA_IN**
 +            * **ALPHA_OUT**
 +            * **ALPHA_ATOP**
 +            * **ALPHA_XOR**
 +            * **ALPHA_PLUS**
 +            * **ALPHA_OVER_PREMUL**
 +            * **ALPHA_IN_PREMUL**
 +            * **ALPHA_OUT_PREMUL**
 +            * **ALPHA_ATOP_PREMUL**
 +            * **ALPHA_XOR_PREMUL**
 +            * **ALPHA_PLUS_PREMUL**
 +            * **ALPHA_PREMUL**
 +
 +    :param stream: Stream for the asynchronous version.
 +
-    * : An example demonstrating the use of alphaComp can be found at opencv_source_code/samples/gpu/alpha_comp.cpp
++.. note::
 +
++   * An example demonstrating the use of alphaComp can be found at opencv_source_code/samples/gpu/alpha_comp.cpp
 +
 +
 +.. [MHT2011] Pascal Getreuer, Malvar-He-Cutler Linear Image Demosaicking, Image Processing On Line, 2011
index bf4185f,0000000..c640575
mode 100644,000000..100644
--- /dev/null
@@@ -1,315 -1,0 +1,315 @@@
- .. Sample code::
 +Hough Transform
 +===============
 +
 +.. highlight:: cpp
 +
 +
 +
 +gpu::HoughLinesDetector
 +-----------------------
 +.. ocv:class:: gpu::HoughLinesDetector : public Algorithm
 +
 +Base class for lines detector algorithm. ::
 +
 +    class CV_EXPORTS HoughLinesDetector : public Algorithm
 +    {
 +    public:
 +        virtual void detect(InputArray src, OutputArray lines) = 0;
 +        virtual void downloadResults(InputArray d_lines, OutputArray h_lines, OutputArray h_votes = noArray()) = 0;
 +
 +        virtual void setRho(float rho) = 0;
 +        virtual float getRho() const = 0;
 +
 +        virtual void setTheta(float theta) = 0;
 +        virtual float getTheta() const = 0;
 +
 +        virtual void setThreshold(int threshold) = 0;
 +        virtual int getThreshold() const = 0;
 +
 +        virtual void setDoSort(bool doSort) = 0;
 +        virtual bool getDoSort() const = 0;
 +
 +        virtual void setMaxLines(int maxLines) = 0;
 +        virtual int getMaxLines() const = 0;
 +    };
 +
 +
 +
 +gpu::HoughLinesDetector::detect
 +-------------------------------
 +Finds lines in a binary image using the classical Hough transform.
 +
 +.. ocv:function:: void gpu::HoughLinesDetector::detect(InputArray src, OutputArray lines)
 +
 +    :param src: 8-bit, single-channel binary source image.
 +
 +    :param lines: Output vector of lines. Each line is represented by a two-element vector  :math:`(\rho, \theta)` .  :math:`\rho`  is the distance from the coordinate origin  :math:`(0,0)`  (top-left corner of the image).  :math:`\theta`  is the line rotation angle in radians ( :math:`0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}` ).
 +
 +.. seealso:: :ocv:func:`HoughLines`
 +
 +
 +
 +gpu::HoughLinesDetector::downloadResults
 +----------------------------------------
 +Downloads results from :ocv:func:`gpu::HoughLinesDetector::detect` to host memory.
 +
 +.. ocv:function:: void gpu::HoughLinesDetector::downloadResults(InputArray d_lines, OutputArray h_lines, OutputArray h_votes = noArray())
 +
 +    :param d_lines: Result of :ocv:func:`gpu::HoughLinesDetector::detect` .
 +
 +    :param h_lines: Output host array.
 +
 +    :param h_votes: Optional output array for line's votes.
 +
 +
 +
 +gpu::createHoughLinesDetector
 +-----------------------------
 +Creates implementation for :ocv:class:`gpu::HoughLinesDetector` .
 +
 +.. ocv:function:: Ptr<HoughLinesDetector> gpu::createHoughLinesDetector(float rho, float theta, int threshold, bool doSort = false, int maxLines = 4096)
 +
 +    :param rho: Distance resolution of the accumulator in pixels.
 +
 +    :param theta: Angle resolution of the accumulator in radians.
 +
 +    :param threshold: Accumulator threshold parameter. Only those lines are returned that get enough votes ( :math:`>\texttt{threshold}` ).
 +
 +    :param doSort: Performs lines sort by votes.
 +
 +    :param maxLines: Maximum number of output lines.
 +
 +
 +
 +gpu::HoughSegmentDetector
 +-------------------------
 +.. ocv:class:: gpu::HoughSegmentDetector : public Algorithm
 +
 +Base class for line segments detector algorithm. ::
 +
 +    class CV_EXPORTS HoughSegmentDetector : public Algorithm
 +    {
 +    public:
 +        virtual void detect(InputArray src, OutputArray lines) = 0;
 +
 +        virtual void setRho(float rho) = 0;
 +        virtual float getRho() const = 0;
 +
 +        virtual void setTheta(float theta) = 0;
 +        virtual float getTheta() const = 0;
 +
 +        virtual void setMinLineLength(int minLineLength) = 0;
 +        virtual int getMinLineLength() const = 0;
 +
 +        virtual void setMaxLineGap(int maxLineGap) = 0;
 +        virtual int getMaxLineGap() const = 0;
 +
 +        virtual void setMaxLines(int maxLines) = 0;
 +        virtual int getMaxLines() const = 0;
 +    };
 +
-    * : An example using the Hough segment detector can be found at opencv_source_code/samples/gpu/houghlines.cpp
++.. note::
 +
++   * An example using the Hough segment detector can be found at opencv_source_code/samples/gpu/houghlines.cpp
 +
 +
 +gpu::HoughSegmentDetector::detect
 +---------------------------------
 +Finds line segments in a binary image using the probabilistic Hough transform.
 +
 +.. ocv:function:: void gpu::HoughSegmentDetector::detect(InputArray src, OutputArray lines)
 +
 +    :param src: 8-bit, single-channel binary source image.
 +
 +    :param lines: Output vector of lines. Each line is represented by a 4-element vector  :math:`(x_1, y_1, x_2, y_2)` , where  :math:`(x_1,y_1)`  and  :math:`(x_2, y_2)`  are the ending points of each detected line segment.
 +
 +.. seealso:: :ocv:func:`HoughLinesP`
 +
 +
 +
 +gpu::createHoughSegmentDetector
 +-------------------------------
 +Creates implementation for :ocv:class:`gpu::HoughSegmentDetector` .
 +
 +.. ocv:function:: Ptr<HoughSegmentDetector> gpu::createHoughSegmentDetector(float rho, float theta, int minLineLength, int maxLineGap, int maxLines = 4096)
 +
 +    :param rho: Distance resolution of the accumulator in pixels.
 +
 +    :param theta: Angle resolution of the accumulator in radians.
 +
 +    :param minLineLength: Minimum line length. Line segments shorter than that are rejected.
 +
 +    :param maxLineGap: Maximum allowed gap between points on the same line to link them.
 +
 +    :param maxLines: Maximum number of output lines.
 +
 +
 +
 +gpu::HoughCirclesDetector
 +-------------------------
 +.. ocv:class:: gpu::HoughCirclesDetector : public Algorithm
 +
 +Base class for circles detector algorithm. ::
 +
 +    class CV_EXPORTS HoughCirclesDetector : public Algorithm
 +    {
 +    public:
 +        virtual void detect(InputArray src, OutputArray circles) = 0;
 +
 +        virtual void setDp(float dp) = 0;
 +        virtual float getDp() const = 0;
 +
 +        virtual void setMinDist(float minDist) = 0;
 +        virtual float getMinDist() const = 0;
 +
 +        virtual void setCannyThreshold(int cannyThreshold) = 0;
 +        virtual int getCannyThreshold() const = 0;
 +
 +        virtual void setVotesThreshold(int votesThreshold) = 0;
 +        virtual int getVotesThreshold() const = 0;
 +
 +        virtual void setMinRadius(int minRadius) = 0;
 +        virtual int getMinRadius() const = 0;
 +
 +        virtual void setMaxRadius(int maxRadius) = 0;
 +        virtual int getMaxRadius() const = 0;
 +
 +        virtual void setMaxCircles(int maxCircles) = 0;
 +        virtual int getMaxCircles() const = 0;
 +    };
 +
 +
 +
 +gpu::HoughCirclesDetector::detect
 +---------------------------------
 +Finds circles in a grayscale image using the Hough transform.
 +
 +.. ocv:function:: void gpu::HoughCirclesDetector::detect(InputArray src, OutputArray circles)
 +
 +    :param src: 8-bit, single-channel grayscale input image.
 +
 +    :param circles: Output vector of found circles. Each vector is encoded as a 3-element floating-point vector  :math:`(x, y, radius)` .
 +
 +.. seealso:: :ocv:func:`HoughCircles`
 +
 +
 +
 +gpu::createHoughCirclesDetector
 +-------------------------------
 +Creates implementation for :ocv:class:`gpu::HoughCirclesDetector` .
 +
 +.. ocv:function:: Ptr<HoughCirclesDetector> gpu::createHoughCirclesDetector(float dp, float minDist, int cannyThreshold, int votesThreshold, int minRadius, int maxRadius, int maxCircles = 4096)
 +
 +    :param dp: Inverse ratio of the accumulator resolution to the image resolution. For example, if  ``dp=1`` , the accumulator has the same resolution as the input image. If  ``dp=2`` , the accumulator has half as big width and height.
 +
 +    :param minDist: Minimum distance between the centers of the detected circles. If the parameter is too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is too large, some circles may be missed.
 +
 +    :param cannyThreshold: The higher threshold of the two passed to Canny edge detector (the lower one is twice smaller).
 +
 +    :param votesThreshold: The accumulator threshold for the circle centers at the detection stage. The smaller it is, the more false circles may be detected.
 +
 +    :param minRadius: Minimum circle radius.
 +
 +    :param maxRadius: Maximum circle radius.
 +
 +    :param maxCircles: Maximum number of output circles.
 +
 +
 +
 +gpu::GeneralizedHough
 +---------------------
 +.. ocv:class:: gpu::GeneralizedHough : public Algorithm
 +
 +Base class for generalized hough transform. ::
 +
 +    class CV_EXPORTS GeneralizedHough : public Algorithm
 +    {
 +    public:
 +        static Ptr<GeneralizedHough> create(int method);
 +
 +        virtual void setTemplate(InputArray templ, int cannyThreshold = 100, Point templCenter = Point(-1, -1)) = 0;
 +        virtual void setTemplate(InputArray edges, InputArray dx, InputArray dy, Point templCenter = Point(-1, -1)) = 0;
 +
 +        virtual void detect(InputArray image, OutputArray positions, int cannyThreshold = 100) = 0;
 +        virtual void detect(InputArray edges, InputArray dx, InputArray dy, OutputArray positions) = 0;
 +
 +        virtual void downloadResults(InputArray d_positions, OutputArray h_positions, OutputArray h_votes = noArray()) = 0;
 +    };
 +
 +
 +Finds arbitrary template in the grayscale image using Generalized Hough Transform.
 +
 +
 +
 +gpu::GeneralizedHough::create
 +-----------------------------
 +Creates implementation for :ocv:class:`gpu::GeneralizedHough` .
 +
 +.. ocv:function:: Ptr<GeneralizedHough> gpu::GeneralizedHough::create(int method)
 +
 +    :param method: Combination of flags ( ``cv::GeneralizedHough::GHT_POSITION`` , ``cv::GeneralizedHough::GHT_SCALE`` , ``cv::GeneralizedHough::GHT_ROTATION`` ) specifying transformation to find.
 +
 +For full affine transformations (move + scale + rotation) [Guil1999]_ algorithm is used, otherwise [Ballard1981]_ algorithm is used.
 +
 +
 +
 +gpu::GeneralizedHough::setTemplate
 +----------------------------------
 +Set template to search.
 +
 +.. ocv:function:: void gpu::GeneralizedHough::setTemplate(InputArray templ, int cannyThreshold = 100, Point templCenter = Point(-1, -1))
 +
 +.. ocv:function:: void gpu::GeneralizedHough::setTemplate(InputArray edges, InputArray dx, InputArray dy, Point templCenter = Point(-1, -1))
 +
 +    :param templ: Template image. Canny edge detector will be applied to extract template edges.
 +
 +    :param cannyThreshold: Threshold value for Canny edge detector.
 +
 +    :param templCenter: Center for rotation. By default image center will be used.
 +
 +    :param edges: Edge map for template image.
 +
 +    :param dx: First derivative of template image in the vertical direction. Support only ``CV_32S`` type.
 +
 +    :param dy: First derivative of template image in the horizontal direction. Support only ``CV_32S`` type.
 +
 +
 +
 +gpu::GeneralizedHough::detect
 +-----------------------------
 +Finds template (set by :ocv:func:`gpu::GeneralizedHough::setTemplate` ) in the grayscale image.
 +
 +.. ocv:function:: void gpu::GeneralizedHough::detect(InputArray image, OutputArray positions, int cannyThreshold = 100)
 +
 +.. ocv:function:: void gpu::GeneralizedHough::detect(InputArray edges, InputArray dx, InputArray dy, OutputArray positions)
 +
 +    :param templ: Input image. Canny edge detector will be applied to extract template edges.
 +
 +    :param positions: Output vector of found objects. Each vector is encoded as a 4-element floating-point vector  :math:`(x, y, scale, angle)` .
 +
 +    :param cannyThreshold: Threshold value for Canny edge detector.
 +
 +    :param edges: Edge map for input image.
 +
 +    :param dx: First derivative of input image in the vertical direction. Support only ``CV_32S`` type.
 +
 +    :param dy: First derivative of input image in the horizontal direction. Support only ``CV_32S`` type.
 +
 +
 +
 +gpu::GeneralizedHough::downloadResults
 +--------------------------------------
 +Downloads results from :ocv:func:`gpu::GeneralizedHough::detect` to host memory.
 +
 +.. ocv:function:: void gpu::GeneralizedHough::downloadResult(InputArray d_positions, OutputArray h_positions, OutputArray h_votes = noArray())
 +
 +    :param d_lines: Result of :ocv:func:`gpu::GeneralizedHough::detect` .
 +
 +    :param h_lines: Output host array.
 +
 +    :param h_votes: Optional output array for votes. Each vector is encoded as a 3-element integer-point vector  :math:`(position_votes, scale_votes, angle_votes)` .
 +
 +
 +
 +.. [Ballard1981] Ballard, D.H. (1981). Generalizing the Hough transform to detect arbitrary shapes. Pattern Recognition 13 (2): 111-122.
 +.. [Guil1999] Guil, N., González-Linares, J.M. and Zapata, E.L. (1999). Bidimensional shape detection using an invariant approach. Pattern Recognition 32 (6): 1025-1038.
index 923fe9e,0000000..937b209
mode 100644,000000..100644
--- /dev/null
@@@ -1,229 -1,0 +1,229 @@@
- .. Sample code::
 +Optical Flow
 +============
 +
 +.. highlight:: cpp
 +
-    * : A general optical flow example can be found at opencv_source_code/samples/gpu/optical_flow.cpp
-    * : A feneral optical flow example using the nvidia API can be found at opencv_source_code/samples/gpu/opticalflow_nvidia_api.cpp
++.. note::
 +
- .. Sample code::
++   * A general optical flow example can be found at opencv_source_code/samples/gpu/optical_flow.cpp
++   * A general optical flow example using the Nvidia API can be found at opencv_source_code/samples/gpu/opticalflow_nvidia_api.cpp
 +
 +
 +gpu::BroxOpticalFlow
 +--------------------
 +.. ocv:class:: gpu::BroxOpticalFlow
 +
 +Class computing the optical flow for two images using Brox et al Optical Flow algorithm ([Brox2004]_). ::
 +
 +    class BroxOpticalFlow
 +    {
 +    public:
 +        BroxOpticalFlow(float alpha_, float gamma_, float scale_factor_, int inner_iterations_, int outer_iterations_, int solver_iterations_);
 +
 +        //! Compute optical flow
 +        //! frame0 - source frame (supports only CV_32FC1 type)
 +        //! frame1 - frame to track (with the same size and type as frame0)
 +        //! u      - flow horizontal component (along x axis)
 +        //! v      - flow vertical component (along y axis)
 +        void operator ()(const GpuMat& frame0, const GpuMat& frame1, GpuMat& u, GpuMat& v, Stream& stream = Stream::Null());
 +
 +        //! flow smoothness
 +        float alpha;
 +
 +        //! gradient constancy importance
 +        float gamma;
 +
 +        //! pyramid scale factor
 +        float scale_factor;
 +
 +        //! number of lagged non-linearity iterations (inner loop)
 +        int inner_iterations;
 +
 +        //! number of warping iterations (number of pyramid levels)
 +        int outer_iterations;
 +
 +        //! number of linear system solver iterations
 +        int solver_iterations;
 +
 +        GpuMat buf;
 +    };
 +
-    * : An example illustrating the Brox et al optical flow algorithm can be found at opencv_source_code/samples/gpu/brox_optical_flow.cpp
++.. note::
 +
- .. Sample code::
++   * An example illustrating the Brox et al optical flow algorithm can be found at opencv_source_code/samples/gpu/brox_optical_flow.cpp
 +
 +
 +gpu::FarnebackOpticalFlow
 +-------------------------
 +.. ocv:class:: gpu::FarnebackOpticalFlow
 +
 +Class computing a dense optical flow using the Gunnar Farneback’s algorithm. ::
 +
 +    class CV_EXPORTS FarnebackOpticalFlow
 +    {
 +    public:
 +        FarnebackOpticalFlow()
 +        {
 +            numLevels = 5;
 +            pyrScale = 0.5;
 +            fastPyramids = false;
 +            winSize = 13;
 +            numIters = 10;
 +            polyN = 5;
 +            polySigma = 1.1;
 +            flags = 0;
 +        }
 +
 +        int numLevels;
 +        double pyrScale;
 +        bool fastPyramids;
 +        int winSize;
 +        int numIters;
 +        int polyN;
 +        double polySigma;
 +        int flags;
 +
 +        void operator ()(const GpuMat &frame0, const GpuMat &frame1, GpuMat &flowx, GpuMat &flowy, Stream &s = Stream::Null());
 +
 +        void releaseMemory();
 +
 +    private:
 +        /* hidden */
 +    };
 +
 +
 +
 +gpu::FarnebackOpticalFlow::operator ()
 +--------------------------------------
 +Computes a dense optical flow using the Gunnar Farneback’s algorithm.
 +
 +.. ocv:function:: void gpu::FarnebackOpticalFlow::operator ()(const GpuMat &frame0, const GpuMat &frame1, GpuMat &flowx, GpuMat &flowy, Stream &s = Stream::Null())
 +
 +    :param frame0: First 8-bit gray-scale input image
 +    :param frame1: Second 8-bit gray-scale input image
 +    :param flowx: Flow horizontal component
 +    :param flowy: Flow vertical component
 +    :param s: Stream
 +
 +.. seealso:: :ocv:func:`calcOpticalFlowFarneback`
 +
 +
 +
 +gpu::FarnebackOpticalFlow::releaseMemory
 +----------------------------------------
 +Releases unused auxiliary memory buffers.
 +
 +.. ocv:function:: void gpu::FarnebackOpticalFlow::releaseMemory()
 +
 +
 +
 +gpu::PyrLKOpticalFlow
 +---------------------
 +.. ocv:class:: gpu::PyrLKOpticalFlow
 +
 +Class used for calculating an optical flow. ::
 +
 +    class PyrLKOpticalFlow
 +    {
 +    public:
 +        PyrLKOpticalFlow();
 +
 +        void sparse(const GpuMat& prevImg, const GpuMat& nextImg, const GpuMat& prevPts, GpuMat& nextPts,
 +            GpuMat& status, GpuMat* err = 0);
 +
 +        void dense(const GpuMat& prevImg, const GpuMat& nextImg, GpuMat& u, GpuMat& v, GpuMat* err = 0);
 +
 +        Size winSize;
 +        int maxLevel;
 +        int iters;
 +        bool useInitialFlow;
 +
 +        void releaseMemory();
 +    };
 +
 +The class can calculate an optical flow for a sparse feature set or dense optical flow using the iterative Lucas-Kanade method with pyramids.
 +
 +.. seealso:: :ocv:func:`calcOpticalFlowPyrLK`
 +
-    * : An example of the Lucas Kanade optical flow algorithm can be found at opencv_source_code/samples/gpu/pyrlk_optical_flow.cpp
++.. note::
 +
++   * An example of the Lucas Kanade optical flow algorithm can be found at opencv_source_code/samples/gpu/pyrlk_optical_flow.cpp
 +
 +
 +gpu::PyrLKOpticalFlow::sparse
 +-----------------------------
 +Calculate an optical flow for a sparse feature set.
 +
 +.. ocv:function:: void gpu::PyrLKOpticalFlow::sparse(const GpuMat& prevImg, const GpuMat& nextImg, const GpuMat& prevPts, GpuMat& nextPts, GpuMat& status, GpuMat* err = 0)
 +
 +    :param prevImg: First 8-bit input image (supports both grayscale and color images).
 +
 +    :param nextImg: Second input image of the same size and the same type as  ``prevImg`` .
 +
 +    :param prevPts: Vector of 2D points for which the flow needs to be found. It must be one row matrix with CV_32FC2 type.
 +
 +    :param nextPts: Output vector of 2D points (with single-precision floating-point coordinates) containing the calculated new positions of input features in the second image. When ``useInitialFlow`` is true, the vector must have the same size as in the input.
 +
 +    :param status: Output status vector (CV_8UC1 type). Each element of the vector is set to 1 if the flow for the corresponding features has been found. Otherwise, it is set to 0.
 +
 +    :param err: Output vector (CV_32FC1 type) that contains the difference between patches around the original and moved points or min eigen value if ``getMinEigenVals`` is checked. It can be NULL, if not needed.
 +
 +.. seealso:: :ocv:func:`calcOpticalFlowPyrLK`
 +
 +
 +
 +gpu::PyrLKOpticalFlow::dense
 +-----------------------------
 +Calculate dense optical flow.
 +
 +.. ocv:function:: void gpu::PyrLKOpticalFlow::dense(const GpuMat& prevImg, const GpuMat& nextImg, GpuMat& u, GpuMat& v, GpuMat* err = 0)
 +
 +    :param prevImg: First 8-bit grayscale input image.
 +
 +    :param nextImg: Second input image of the same size and the same type as  ``prevImg`` .
 +
 +    :param u: Horizontal component of the optical flow of the same size as input images, 32-bit floating-point, single-channel
 +
 +    :param v: Vertical component of the optical flow of the same size as input images, 32-bit floating-point, single-channel
 +
 +    :param err: Output vector (CV_32FC1 type) that contains the difference between patches around the original and moved points or min eigen value if ``getMinEigenVals`` is checked. It can be NULL, if not needed.
 +
 +
 +
 +gpu::PyrLKOpticalFlow::releaseMemory
 +------------------------------------
 +Releases inner buffers memory.
 +
 +.. ocv:function:: void gpu::PyrLKOpticalFlow::releaseMemory()
 +
 +
 +
 +gpu::interpolateFrames
 +----------------------
 +Interpolates frames (images) using provided optical flow (displacement field).
 +
 +.. ocv:function:: void gpu::interpolateFrames(const GpuMat& frame0, const GpuMat& frame1, const GpuMat& fu, const GpuMat& fv, const GpuMat& bu, const GpuMat& bv, float pos, GpuMat& newFrame, GpuMat& buf, Stream& stream = Stream::Null())
 +
 +    :param frame0: First frame (32-bit floating point images, single channel).
 +
 +    :param frame1: Second frame. Must have the same type and size as ``frame0`` .
 +
 +    :param fu: Forward horizontal displacement.
 +
 +    :param fv: Forward vertical displacement.
 +
 +    :param bu: Backward horizontal displacement.
 +
 +    :param bv: Backward vertical displacement.
 +
 +    :param pos: New frame position.
 +
 +    :param newFrame: Output image.
 +
 +    :param buf: Temporary buffer, will have width x 6*height size, CV_32FC1 type and contain 6 GpuMat: occlusion masks for first frame, occlusion masks for second, interpolated forward horizontal flow, interpolated forward vertical flow, interpolated backward horizontal flow, interpolated backward vertical flow.
 +
 +    :param stream: Stream for the asynchronous version.
 +
 +
 +
 +.. [Brox2004] T. Brox, A. Bruhn, N. Papenberg, J. Weickert. *High accuracy optical flow estimation based on a theory for warping*. ECCV 2004.
index 612777d,0000000..f87d43f
mode 100644,000000..100644
--- /dev/null
@@@ -1,336 -1,0 +1,336 @@@
- .. Sample code::
 +Stereo Correspondence
 +=====================
 +
 +.. highlight:: cpp
 +
-    * : A basic stereo matching example can be found at opencv_source_code/samples/gpu/stereo_match.cpp
-    * : A stereo matching example using several GPU's can be found at opencv_source_code/samples/gpu/stereo_multi.cpp
-    * : A stereo matching example using several GPU's and driver API can be found at opencv_source_code/samples/gpu/driver_api_stereo_multi.cpp
++.. note::
 +
++   * A basic stereo matching example can be found at opencv_source_code/samples/gpu/stereo_match.cpp
++   * A stereo matching example using several GPU's can be found at opencv_source_code/samples/gpu/stereo_multi.cpp
++   * A stereo matching example using several GPU's and driver API can be found at opencv_source_code/samples/gpu/driver_api_stereo_multi.cpp
 +
 +gpu::StereoBM
 +-------------
 +.. ocv:class:: gpu::StereoBM : public cv::StereoBM
 +
 +Class computing stereo correspondence (disparity map) using the block matching algorithm. ::
 +
 +.. seealso:: :ocv:class:`StereoBM`
 +
 +
 +
 +gpu::createStereoBM
 +-------------------
 +Creates StereoBM object.
 +
 +.. ocv:function:: Ptr<gpu::StereoBM> gpu::createStereoBM(int numDisparities = 64, int blockSize = 19)
 +
 +    :param numDisparities: the disparity search range. For each pixel algorithm will find the best disparity from 0 (default minimum disparity) to ``numDisparities``. The search range can then be shifted by changing the minimum disparity.
 +
 +    :param blockSize: the linear size of the blocks compared by the algorithm. The size should be odd (as the block is centered at the current pixel). Larger block size implies smoother, though less accurate disparity map. Smaller block size gives more detailed disparity map, but there is higher chance for algorithm to find a wrong correspondence.
 +
 +
 +
 +gpu::StereoBeliefPropagation
 +----------------------------
 +.. ocv:class:: gpu::StereoBeliefPropagation : public cv::StereoMatcher
 +
 +Class computing stereo correspondence using the belief propagation algorithm. ::
 +
 +    class CV_EXPORTS StereoBeliefPropagation : public cv::StereoMatcher
 +    {
 +    public:
 +        using cv::StereoMatcher::compute;
 +
 +        virtual void compute(InputArray left, InputArray right, OutputArray disparity, Stream& stream) = 0;
 +
 +        //! version for user specified data term
 +        virtual void compute(InputArray data, OutputArray disparity, Stream& stream = Stream::Null()) = 0;
 +
 +        //! number of BP iterations on each level
 +        virtual int getNumIters() const = 0;
 +        virtual void setNumIters(int iters) = 0;
 +
 +        //! number of levels
 +        virtual int getNumLevels() const = 0;
 +        virtual void setNumLevels(int levels) = 0;
 +
 +        //! truncation of data cost
 +        virtual double getMaxDataTerm() const = 0;
 +        virtual void setMaxDataTerm(double max_data_term) = 0;
 +
 +        //! data weight
 +        virtual double getDataWeight() const = 0;
 +        virtual void setDataWeight(double data_weight) = 0;
 +
 +        //! truncation of discontinuity cost
 +        virtual double getMaxDiscTerm() const = 0;
 +        virtual void setMaxDiscTerm(double max_disc_term) = 0;
 +
 +        //! discontinuity single jump
 +        virtual double getDiscSingleJump() const = 0;
 +        virtual void setDiscSingleJump(double disc_single_jump) = 0;
 +
 +        virtual int getMsgType() const = 0;
 +        virtual void setMsgType(int msg_type) = 0;
 +
 +        static void estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels);
 +    };
 +
 +
 +The class implements algorithm described in [Felzenszwalb2006]_ . It can compute own data cost (using a truncated linear model) or use a user-provided data cost.
 +
 +.. note::
 +
 +    ``StereoBeliefPropagation`` requires a lot of memory for message storage:
 +
 +    .. math::
 +
 +        width \_ step  \cdot height  \cdot ndisp  \cdot 4  \cdot (1 + 0.25)
 +
 +    and for data cost storage:
 +
 +    .. math::
 +
 +        width\_step \cdot height \cdot ndisp \cdot (1 + 0.25 + 0.0625 +  \dotsm + \frac{1}{4^{levels}})
 +
 +    ``width_step`` is the number of bytes in a line including padding.
 +
 +``StereoBeliefPropagation`` uses a truncated linear model for the data cost and discontinuity terms:
 +
 +.. math::
 +
 +    DataCost = data \_ weight  \cdot \min ( \lvert Img_Left(x,y)-Img_Right(x-d,y)  \rvert , max \_ data \_ term)
 +
 +.. math::
 +
 +    DiscTerm =  \min (disc \_ single \_ jump  \cdot \lvert f_1-f_2  \rvert , max \_ disc \_ term)
 +
 +For more details, see [Felzenszwalb2006]_.
 +
 +By default, ``StereoBeliefPropagation`` uses floating-point arithmetics and the ``CV_32FC1`` type for messages. But it can also use fixed-point arithmetics and the ``CV_16SC1`` message type for better performance. To avoid an overflow in this case, the parameters must satisfy the following requirement:
 +
 +.. math::
 +
 +    10  \cdot 2^{levels-1}  \cdot max \_ data \_ term < SHRT \_ MAX
 +
 +.. seealso:: :ocv:class:`StereoMatcher`
 +
 +
 +
 +gpu::createStereoBeliefPropagation
 +----------------------------------
 +Creates StereoBeliefPropagation object.
 +
 +.. ocv:function:: Ptr<gpu::StereoBeliefPropagation> gpu::createStereoBeliefPropagation(int ndisp = 64, int iters = 5, int levels = 5, int msg_type = CV_32F)
 +
 +    :param ndisp: Number of disparities.
 +
 +    :param iters: Number of BP iterations on each level.
 +
 +    :param levels: Number of levels.
 +
 +    :param msg_type: Type for messages.  ``CV_16SC1``  and  ``CV_32FC1`` types are supported.
 +
 +
 +
 +gpu::StereoBeliefPropagation::estimateRecommendedParams
 +-------------------------------------------------------
 +Uses a heuristic method to compute the recommended parameters ( ``ndisp``, ``iters`` and ``levels`` ) for the specified image size ( ``width`` and ``height`` ).
 +
 +.. ocv:function:: void gpu::StereoBeliefPropagation::estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels)
 +
 +
 +
 +gpu::StereoBeliefPropagation::compute
 +-------------------------------------
 +Enables the stereo correspondence operator that finds the disparity for the specified data cost.
 +
 +.. ocv:function:: void gpu::StereoBeliefPropagation::compute(InputArray data, OutputArray disparity, Stream& stream = Stream::Null())
 +
 +    :param data: User-specified data cost, a matrix of ``msg_type`` type and ``Size(<image columns>*ndisp, <image rows>)`` size.
 +
 +    :param disparity: Output disparity map. If  ``disparity``  is empty, the output type is  ``CV_16SC1`` . Otherwise, the type is retained.
 +
 +    :param stream: Stream for the asynchronous version.
 +
 +
 +
 +gpu::StereoConstantSpaceBP
 +--------------------------
 +.. ocv:class:: gpu::StereoConstantSpaceBP : public gpu::StereoBeliefPropagation
 +
 +Class computing stereo correspondence using the constant space belief propagation algorithm. ::
 +
 +    class CV_EXPORTS StereoConstantSpaceBP : public gpu::StereoBeliefPropagation
 +    {
 +    public:
 +        //! number of active disparity on the first level
 +        virtual int getNrPlane() const = 0;
 +        virtual void setNrPlane(int nr_plane) = 0;
 +
 +        virtual bool getUseLocalInitDataCost() const = 0;
 +        virtual void setUseLocalInitDataCost(bool use_local_init_data_cost) = 0;
 +
 +        static void estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels, int& nr_plane);
 +    };
 +
 +
 +The class implements algorithm described in [Yang2010]_. ``StereoConstantSpaceBP`` supports both local minimum and global minimum data cost initialization algorithms. For more details, see the paper mentioned above. By default, a local algorithm is used. To enable a global algorithm, set ``use_local_init_data_cost`` to ``false`` .
 +
 +``StereoConstantSpaceBP`` uses a truncated linear model for the data cost and discontinuity terms:
 +
 +.. math::
 +
 +    DataCost = data \_ weight  \cdot \min ( \lvert I_2-I_1  \rvert , max \_ data \_ term)
 +
 +.. math::
 +
 +    DiscTerm =  \min (disc \_ single \_ jump  \cdot \lvert f_1-f_2  \rvert , max \_ disc \_ term)
 +
 +For more details, see [Yang2010]_.
 +
 +By default, ``StereoConstantSpaceBP`` uses floating-point arithmetics and the ``CV_32FC1`` type for messages. But it can also use fixed-point arithmetics and the ``CV_16SC1`` message type for better performance. To avoid an overflow in this case, the parameters must satisfy the following requirement:
 +
 +.. math::
 +
 +    10  \cdot 2^{levels-1}  \cdot max \_ data \_ term < SHRT \_ MAX
 +
 +
 +
 +gpu::createStereoConstantSpaceBP
 +--------------------------------
 +Creates StereoConstantSpaceBP object.
 +
 +.. ocv:function:: Ptr<gpu::StereoConstantSpaceBP> gpu::createStereoConstantSpaceBP(int ndisp = 128, int iters = 8, int levels = 4, int nr_plane = 4, int msg_type = CV_32F)
 +
 +    :param ndisp: Number of disparities.
 +
 +    :param iters: Number of BP iterations on each level.
 +
 +    :param levels: Number of levels.
 +
 +    :param nr_plane: Number of disparity levels on the first level.
 +
 +    :param msg_type: Type for messages.  ``CV_16SC1``  and  ``CV_32FC1`` types are supported.
 +
 +
 +
 +gpu::StereoConstantSpaceBP::estimateRecommendedParams
 +-----------------------------------------------------
 +Uses a heuristic method to compute parameters (ndisp, iters, levelsand nrplane) for the specified image size (widthand height).
 +
 +.. ocv:function:: void gpu::StereoConstantSpaceBP::estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels, int& nr_plane)
 +
 +
 +
 +gpu::DisparityBilateralFilter
 +-----------------------------
 +.. ocv:class:: gpu::DisparityBilateralFilter : public cv::Algorithm
 +
 +Class refining a disparity map using joint bilateral filtering. ::
 +
 +    class CV_EXPORTS DisparityBilateralFilter : public cv::Algorithm
 +    {
 +    public:
 +        //! the disparity map refinement operator. Refine disparity map using joint bilateral filtering given a single color image.
 +        //! disparity must have CV_8U or CV_16S type, image must have CV_8UC1 or CV_8UC3 type.
 +        virtual void apply(InputArray disparity, InputArray image, OutputArray dst, Stream& stream = Stream::Null()) = 0;
 +
 +        virtual int getNumDisparities() const = 0;
 +        virtual void setNumDisparities(int numDisparities) = 0;
 +
 +        virtual int getRadius() const = 0;
 +        virtual void setRadius(int radius) = 0;
 +
 +        virtual int getNumIters() const = 0;
 +        virtual void setNumIters(int iters) = 0;
 +
 +        //! truncation of data continuity
 +        virtual double getEdgeThreshold() const = 0;
 +        virtual void setEdgeThreshold(double edge_threshold) = 0;
 +
 +        //! truncation of disparity continuity
 +        virtual double getMaxDiscThreshold() const = 0;
 +        virtual void setMaxDiscThreshold(double max_disc_threshold) = 0;
 +
 +        //! filter range sigma
 +        virtual double getSigmaRange() const = 0;
 +        virtual void setSigmaRange(double sigma_range) = 0;
 +    };
 +
 +
 +The class implements [Yang2010]_ algorithm.
 +
 +
 +
 +gpu::createDisparityBilateralFilter
 +-----------------------------------
 +Creates DisparityBilateralFilter object.
 +
 +.. ocv:function:: Ptr<gpu::DisparityBilateralFilter> gpu::createDisparityBilateralFilter(int ndisp = 64, int radius = 3, int iters = 1)
 +
 +    :param ndisp: Number of disparities.
 +
 +    :param radius: Filter radius.
 +
 +    :param iters: Number of iterations.
 +
 +
 +
 +gpu::DisparityBilateralFilter::apply
 +------------------------------------
 +Refines a disparity map using joint bilateral filtering.
 +
 +.. ocv:function:: void gpu::DisparityBilateralFilter::apply(InputArray disparity, InputArray image, OutputArray dst, Stream& stream = Stream::Null())
 +
 +    :param disparity: Input disparity map.  ``CV_8UC1``  and  ``CV_16SC1``  types are supported.
 +
 +    :param image: Input image. ``CV_8UC1``  and  ``CV_8UC3``  types are supported.
 +
 +    :param dst: Destination disparity map. It has the same size and type as  ``disparity`` .
 +
 +    :param stream: Stream for the asynchronous version.
 +
 +
 +
 +gpu::reprojectImageTo3D
 +-----------------------
 +Reprojects a disparity image to 3D space.
 +
 +.. ocv:function:: void gpu::reprojectImageTo3D(InputArray disp, OutputArray xyzw, InputArray Q, int dst_cn = 4, Stream& stream = Stream::Null())
 +
 +    :param disp: Input disparity image.  ``CV_8U``  and  ``CV_16S``  types are supported.
 +
 +    :param xyzw: Output 3- or 4-channel floating-point image of the same size as  ``disp`` . Each element of  ``xyzw(x,y)``  contains 3D coordinates ``(x,y,z)`` or ``(x,y,z,1)``  of the point  ``(x,y)`` , computed from the disparity map.
 +
 +    :param Q: :math:`4 \times 4`  perspective transformation matrix that can be obtained via  :ocv:func:`stereoRectify` .
 +
 +    :param dst_cn: The number of channels for output image. Can be 3 or 4.
 +
 +    :param stream: Stream for the asynchronous version.
 +
 +.. seealso:: :ocv:func:`reprojectImageTo3D`
 +
 +
 +
 +gpu::drawColorDisp
 +------------------
 +Colors a disparity image.
 +
 +.. ocv:function:: void gpu::drawColorDisp(InputArray src_disp, OutputArray dst_disp, int ndisp, Stream& stream = Stream::Null())
 +
 +    :param src_disp: Source disparity image.  ``CV_8UC1``  and  ``CV_16SC1``  types are supported.
 +
 +    :param dst_disp: Output disparity image. It has the same size as  ``src_disp`` . The  type is ``CV_8UC4``  in  ``BGRA``  format (alpha = 255).
 +
 +    :param ndisp: Number of disparities.
 +
 +    :param stream: Stream for the asynchronous version.
 +
 +This function draws a colored disparity map by converting disparity values from ``[0..ndisp)`` interval first to ``HSV`` color space (where different disparity values correspond to different hues) and then converting the pixels to ``RGB`` for visualization.
 +
 +
 +
 +.. [Felzenszwalb2006] Pedro F. Felzenszwalb algorithm [Pedro F. Felzenszwalb and Daniel P. Huttenlocher. *Efficient belief propagation for early vision*. International Journal of Computer Vision, 70(1), October 2006
 +.. [Yang2010] Q. Yang, L. Wang, and N. Ahuja. *A constant-space belief propagation algorithm for stereo matching*. In CVPR, 2010.
Simple merge
Simple merge
Simple merge
@@@ -801,8 -811,8 +801,8 @@@ See the sample ``grabcut.cpp`` to lear
  
  .. [Telea04] Alexandru Telea, *An Image Inpainting Technique Based on the Fast Marching Method*. Journal of Graphics, GPU, and Game Tools 9 1, pp 23-34 (2004)
  
- .. Sample code::
+ .. note::
  
-    * An example using the GrabCut algorithm can be found at opencv_source_code/samples/cpp/grabcut.cpp
+    * An example using the GrabCut algorithm can be found at opencv_source_code/samples/cpp/grabcut.cpp
  
-    * : PYTHON : An example using the GrabCut algorithm can be found at opencv_source_code/samples/python2/grabcut.py
 -   * (Python) An example using the GrabCut algorithm can be found at opencv_source_code/samples/python2/grabcut.py
++   * (Python) An example using the GrabCut algorithm can be found at opencv_source_code/samples/python2/grabcut.py
@@@ -73,6 -74,6 +73,6 @@@ image patch
  After the function finishes the comparison, the best matches can be found as global minimums (when ``CV_TM_SQDIFF`` was used) or maximums (when ``CV_TM_CCORR`` or ``CV_TM_CCOEFF`` was used) using the
  :ocv:func:`minMaxLoc` function. In case of a color image, template summation in the numerator and each sum in the denominator is done over all of the channels and separate mean values are used for each channel. That is, the function can take a color template and a color image. The result will still be a single-channel image, which is easier to analyze.
  
- .. Sample code::
+ .. note::
  
-    * : PYTHON : An example on how to match mouse selected regions in an image can be found at opencv_source_code/samples/python2/mouse_and_match.py
 -   * (Python) An example on how to match mouse selected regions in an image can be found at opencv_source_code/samples/python2/mouse_and_match.py
++   * (Python) An example on how to match mouse selected regions in an image can be found at opencv_source_code/samples/python2/mouse_and_match.py
@@@ -192,14 -166,100 +192,14 @@@ The function retrieves contours from th
  
  .. note:: If you use the new Python interface then the ``CV_`` prefix has to be omitted in contour retrieval mode and contour approximation method parameters (for example, use ``cv2.RETR_LIST`` and ``cv2.CHAIN_APPROX_NONE`` parameters). If you use the old Python interface then these parameters have the ``CV_`` prefix (for example, use ``cv.CV_RETR_LIST`` and ``cv.CV_CHAIN_APPROX_NONE``).
  
- .. Sample code::
+ .. note::
  
-    * An example using the findContour functionality can be found at opencv_source_code/samples/cpp/contours2.cpp
-    * An example using findContours to clean up a background segmentation result at opencv_source_code/samples/cpp/segment_objects.cpp
+    * An example using the findContour functionality can be found at opencv_source_code/samples/cpp/contours2.cpp
+    * An example using findContours to clean up a background segmentation result at opencv_source_code/samples/cpp/segment_objects.cpp
  
-    * : PYTHON : An example using the findContour functionality can be found at opencv_source/samples/python2/contours.py
-    * : PYTHON : An example of detecting squares in an image can be found at opencv_source/samples/python2/squares.py
+    * (Python) An example using the findContour functionality can be found at opencv_source/samples/python2/contours.py
+    * (Python) An example of detecting squares in an image can be found at opencv_source/samples/python2/squares.py
  
 -drawContours
 -----------------
 -Draws contours outlines or filled contours.
 -
 -.. ocv:function:: void drawContours( InputOutputArray image, InputArrayOfArrays contours,                   int contourIdx, const Scalar& color, int thickness=1, int lineType=8, InputArray hierarchy=noArray(), int maxLevel=INT_MAX, Point offset=Point() )
 -
 -.. ocv:pyfunction:: cv2.drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset]]]]]) -> None
 -
 -.. ocv:cfunction:: void cvDrawContours( CvArr *img, CvSeq* contour, CvScalar externalColor, CvScalar holeColor, int maxLevel, int thickness=1, int lineType=8 )
 -.. ocv:pyoldfunction:: cv.DrawContours(img, contour, external_color, hole_color, max_level, thickness=1, lineType=8, offset=(0, 0))-> None
 -
 -    :param image: Destination image.
 -
 -    :param contours: All the input contours. Each contour is stored as a point vector.
 -
 -    :param contourIdx: Parameter indicating a contour to draw. If it is negative, all the contours are drawn.
 -
 -    :param color: Color of the contours.
 -
 -    :param thickness: Thickness of lines the contours are drawn with. If it is negative (for example,  ``thickness=CV_FILLED`` ), the contour interiors are
 -        drawn.
 -
 -    :param lineType: Line connectivity. See  :ocv:func:`line`  for details.
 -
 -    :param hierarchy: Optional information about hierarchy. It is only needed if you want to draw only some of the  contours (see  ``maxLevel`` ).
 -
 -    :param maxLevel: Maximal level for drawn contours. If it is 0, only
 -        the specified contour is drawn. If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This parameter is only taken into account when there is  ``hierarchy``  available.
 -
 -    :param offset: Optional contour shift parameter. Shift all the drawn contours by the specified  :math:`\texttt{offset}=(dx,dy)` .
 -
 -    :param contour: Pointer to the first contour.
 -
 -    :param externalColor: Color of external contours.
 -
 -    :param holeColor: Color of internal contours (holes).
 -
 -The function draws contour outlines in the image if
 -:math:`\texttt{thickness} \ge 0` or fills the area bounded by the contours if
 -:math:`\texttt{thickness}<0` . The example below shows how to retrieve connected components from the binary image and label them: ::
 -
 -    #include "cv.h"
 -    #include "highgui.h"
 -
 -    using namespace cv;
 -
 -    int main( int argc, char** argv )
 -    {
 -        Mat src;
 -        // the first command-line parameter must be a filename of the binary
 -        // (black-n-white) image
 -        if( argc != 2 || !(src=imread(argv[1], 0)).data)
 -            return -1;
 -
 -        Mat dst = Mat::zeros(src.rows, src.cols, CV_8UC3);
 -
 -        src = src > 1;
 -        namedWindow( "Source", 1 );
 -        imshow( "Source", src );
 -
 -        vector<vector<Point> > contours;
 -        vector<Vec4i> hierarchy;
 -
 -        findContours( src, contours, hierarchy,
 -            CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
 -
 -        // iterate through all the top-level contours,
 -        // draw each connected component with its own random color
 -        int idx = 0;
 -        for( ; idx >= 0; idx = hierarchy[idx][0] )
 -        {
 -            Scalar color( rand()&255, rand()&255, rand()&255 );
 -            drawContours( dst, contours, idx, color, CV_FILLED, 8, hierarchy );
 -        }
 -
 -        namedWindow( "Components", 1 );
 -        imshow( "Components", dst );
 -        waitKey(0);
 -    }
 -
 -.. note::
 -
 -   * An example using the drawContour functionality can be found at opencv_source_code/samples/cpp/contours2.cpp
 -   * An example using drawContours to clean up a background segmentation result at opencv_source_code/samples/cpp/segment_objects.cpp
 -
 -   * (Python) An example using the drawContour functionality can be found at opencv_source/samples/python2/contours.py
  
  approxPolyDP
  ----------------
@@@ -418,11 -490,10 +418,11 @@@ Fits an ellipse around a set of 2D poin
  
  The function calculates the ellipse that fits (in a least-squares sense) a set of 2D points best of all. It returns the rotated rectangle in which the ellipse is inscribed. The algorithm [Fitzgibbon95]_ is used.
  
- .. Sample code::
+ .. note::
  
-    * An example using the fitEllipse technique can be found at opencv_source_code/samples/cpp/fitellipse.cpp
+    * An example using the fitEllipse technique can be found at opencv_source_code/samples/cpp/fitellipse.cpp
  
 +
  fitLine
  -----------
  Fits a line to a 2D or 3D point set.
@@@ -495,9 -568,8 +495,9 @@@ http://en.wikipedia.org/wiki/M-estimato
  
  .. Sample code:
  
-    * : PYTHON : An example of robust line fitting can be found at opencv_source_code/samples/python2/fitline.py
+    * (Python) An example of robust line fitting can be found at opencv_source_code/samples/python2/fitline.py
  
 +
  isContourConvex
  -------------------
  Tests a contour convexity.
Simple merge
@@@ -216,175 -480,118 +216,193 @@@ void getRectSubPix_Cn_(const _Tp* src, 
  }
  
  
 +static void getRectSubPix_8u32f
 +( const uchar* src, size_t src_step, Size src_size,
 + float* dst, size_t dst_step, Size win_size, Point2f center0, int cn )
 +{
 +    Point2f center = center0;
 +    Point ip;
  
 -#define ICV_SHIFT             16
 -#define ICV_SCALE(x)          cvRound((x)*(1 << ICV_SHIFT))
 -#define ICV_MUL_SCALE(x,y)    (((x)*(y) + (1 << (ICV_SHIFT-1))) >> ICV_SHIFT)
 -#define ICV_DESCALE(x)        (((x)+(1 << (ICV_SHIFT-1))) >> ICV_SHIFT)
 -
 -/*icvCopySubpix_8u_C1R_t icvCopySubpix_8u_C1R_p = 0;
 -icvCopySubpix_8u32f_C1R_t icvCopySubpix_8u32f_C1R_p = 0;
 -icvCopySubpix_32f_C1R_t icvCopySubpix_32f_C1R_p = 0;*/
 +    center.x -= (win_size.width-1)*0.5f;
 +    center.y -= (win_size.height-1)*0.5f;
  
 -ICV_DEF_GET_RECT_SUB_PIX_FUNC( 8u, uchar, uchar, int, CV_NOP, ICV_SCALE, ICV_DESCALE )
 -//ICV_DEF_GET_RECT_SUB_PIX_FUNC( 8u32f, uchar, float, float, CV_8TO32F, CV_NOP, CV_NOP )
 -ICV_DEF_GET_RECT_SUB_PIX_FUNC( 32f, float, float, float, CV_NOP, CV_NOP, CV_NOP )
 +    ip.x = cvFloor( center.x );
 +    ip.y = cvFloor( center.y );
  
 -ICV_DEF_GET_RECT_SUB_PIX_FUNC_C3( 8u, uchar, uchar, int, CV_NOP, ICV_SCALE, ICV_MUL_SCALE )
 -ICV_DEF_GET_RECT_SUB_PIX_FUNC_C3( 8u32f, uchar, float, float, CV_8TO32F, CV_NOP, CV_MUL )
 -ICV_DEF_GET_RECT_SUB_PIX_FUNC_C3( 32f, float, float, float, CV_NOP, CV_NOP, CV_MUL )
 +    if( cn == 1 &&
 +       0 <= ip.x && ip.x + win_size.width < src_size.width &&
 +       0 <= ip.y && ip.y + win_size.height < src_size.height &&
 +       win_size.width > 0 && win_size.height > 0 )
 +    {
 +        float a = center.x - ip.x;
 +        float b = center.y - ip.y;
 +        a = MAX(a,0.0001f);
 +        float a12 = a*(1.f-b);
 +        float a22 = a*b;
 +        float b1 = 1.f - b;
 +        float b2 = b;
 +        double s = (1. - a)/a;
 +
 +        src_step /= sizeof(src[0]);
 +        dst_step /= sizeof(dst[0]);
  
 +        // extracted rectangle is totally inside the image
 +        src += ip.y * src_step + ip.x;
  
 -#define  ICV_DEF_INIT_SUBPIX_TAB( FUNCNAME, FLAG )                  \
 -static void icvInit##FUNCNAME##FLAG##Table( CvFuncTable* tab )      \
 -{                                                                   \
 -    tab->fn_2d[CV_8U] = (void*)icv##FUNCNAME##_8u_##FLAG;           \
 -    tab->fn_2d[CV_32F] = (void*)icv##FUNCNAME##_32f_##FLAG;         \
 -                                                                    \
 -    tab->fn_2d[1] = (void*)icv##FUNCNAME##_8u32f_##FLAG;            \
 +        for( ; win_size.height--; src += src_step, dst += dst_step )
 +        {
 +            float prev = (1 - a)*(b1*src[0] + b2*src[src_step]);
 +            for( int j = 0; j < win_size.width; j++ )
 +            {
 +                float t = a12*src[j+1] + a22*src[j+1+src_step];
 +                dst[j] = prev + t;
 +                prev = (float)(t*s);
 +            }
 +        }
 +    }
 +    else
 +    {
 +        getRectSubPix_Cn_<uchar, float, float, nop<float>, nop<float> >
 +        (src, src_step, src_size, dst, dst_step, win_size, center0, cn );
 +    }
  }
  
 -
 -ICV_DEF_INIT_SUBPIX_TAB( GetRectSubPix, C1R )
 -ICV_DEF_INIT_SUBPIX_TAB( GetRectSubPix, C3R )
 -
 -typedef CvStatus (CV_STDCALL *CvGetRectSubPixFunc)( const void* src, int src_step,
 -                                                    CvSize src_size, void* dst,
 -                                                    int dst_step, CvSize win_size,
 -                                                    CvPoint2D32f center );
 -
+ typedef CvStatus (CV_STDCALL *CvIPPGetRectSubPixFunc)( const void* src, int src_step,
+                                                        CvSize src_size, void* dst,
+                                                        int dst_step, CvSize win_size,
+                                                        CvPoint2D32f center,
+                                                        CvPoint* minpt, CvPoint* maxpt );
  
 -CV_IMPL void
 -cvGetRectSubPix( const void* srcarr, void* dstarr, CvPoint2D32f center )
 +static void
 +getQuadrangleSubPix_8u32f_CnR( const uchar* src, size_t src_step, Size src_size,
 +                               float* dst, size_t dst_step, Size win_size,
 +                               const double *matrix, int cn )
  {
 -    static CvFuncTable gr_tab[2];
 -    static int inittab = 0;
 +    int x, y, k;
 +    double A11 = matrix[0], A12 = matrix[1], A13 = matrix[2];
 +    double A21 = matrix[3], A22 = matrix[4], A23 = matrix[5];
  
 -    CvMat srcstub, *src = (CvMat*)srcarr;
 -    CvMat dststub, *dst = (CvMat*)dstarr;
 -    CvSize src_size, dst_size;
 -    CvGetRectSubPixFunc func;
 -    int cn, src_step, dst_step;
 +    src_step /= sizeof(src[0]);
 +    dst_step /= sizeof(dst[0]);
  
 -    if( !inittab )
 +    for( y = 0; y < win_size.height; y++, dst += dst_step )
      {
 -        icvInitGetRectSubPixC1RTable( gr_tab + 0 );
 -        icvInitGetRectSubPixC3RTable( gr_tab + 1 );
 -        inittab = 1;
 +        double xs = A12*y + A13;
 +        double ys = A22*y + A23;
 +        double xe = A11*(win_size.width-1) + A12*y + A13;
 +        double ye = A21*(win_size.width-1) + A22*y + A23;
 +
 +        if( (unsigned)(cvFloor(xs)-1) < (unsigned)(src_size.width - 3) &&
 +            (unsigned)(cvFloor(ys)-1) < (unsigned)(src_size.height - 3) &&
 +            (unsigned)(cvFloor(xe)-1) < (unsigned)(src_size.width - 3) &&
 +            (unsigned)(cvFloor(ye)-1) < (unsigned)(src_size.height - 3))
 +        {
 +            for( x = 0; x < win_size.width; x++ )
 +            {
 +                int ixs = cvFloor( xs );
 +                int iys = cvFloor( ys );
 +                const uchar *ptr = src + src_step*iys;
 +                float a = (float)(xs - ixs), b = (float)(ys - iys), a1 = 1.f - a, b1 = 1.f - b;
 +                float w00 = a1*b1, w01 = a*b1, w10 = a1*b, w11 = a*b;
 +                xs += A11;
 +                ys += A21;
 +
 +                if( cn == 1 )
 +                {
 +                    ptr += ixs;
 +                    dst[x] = ptr[0]*w00 + ptr[1]*w01 + ptr[src_step]*w10 + ptr[src_step+1]*w11;
 +                }
 +                else if( cn == 3 )
 +                {
 +                    ptr += ixs*3;
 +                    float t0 = ptr[0]*w00 + ptr[3]*w01 + ptr[src_step]*w10 + ptr[src_step+3]*w11;
 +                    float t1 = ptr[1]*w00 + ptr[4]*w01 + ptr[src_step+1]*w10 + ptr[src_step+4]*w11;
 +                    float t2 = ptr[2]*w00 + ptr[5]*w01 + ptr[src_step+2]*w10 + ptr[src_step+5]*w11;
 +
 +                    dst[x*3] = t0;
 +                    dst[x*3+1] = t1;
 +                    dst[x*3+2] = t2;
 +                }
 +                else
 +                {
 +                    ptr += ixs*cn;
 +                    for( k = 0; k < cn; k++ )
 +                        dst[x*cn+k] = ptr[k]*w00 + ptr[k+cn]*w01 +
 +                                    ptr[src_step+k]*w10 + ptr[src_step+k+cn]*w11;
 +                }
 +            }
 +        }
 +        else
 +        {
 +            for( x = 0; x < win_size.width; x++ )
 +            {
 +                int ixs = cvFloor( xs ), iys = cvFloor( ys );
 +                float a = (float)(xs - ixs), b = (float)(ys - iys), a1 = 1.f - a, b1 = 1.f - b;
 +                float w00 = a1*b1, w01 = a*b1, w10 = a1*b, w11 = a*b;
 +                const uchar *ptr0, *ptr1;
 +                xs += A11; ys += A21;
-                 
++
 +                if( (unsigned)iys < (unsigned)(src_size.height-1) )
 +                    ptr0 = src + src_step*iys, ptr1 = ptr0 + src_step;
 +                else
 +                    ptr0 = ptr1 = src + (iys < 0 ? 0 : src_size.height-1)*src_step;
-                 
++
 +                if( (unsigned)ixs < (unsigned)(src_size.width-1) )
 +                {
 +                    ptr0 += ixs*cn; ptr1 += ixs*cn;
 +                    for( k = 0; k < cn; k++ )
 +                        dst[x*cn + k] = ptr0[k]*w00 + ptr0[k+cn]*w01 + ptr1[k]*w10 + ptr1[k+cn]*w11;
 +                }
 +                else
 +                {
 +                    ixs = ixs < 0 ? 0 : src_size.width - 1;
 +                    ptr0 += ixs*cn; ptr1 += ixs*cn;
 +                    for( k = 0; k < cn; k++ )
 +                        dst[x*cn + k] = ptr0[k]*b1 + ptr1[k]*b;
 +                }
 +            }
 +        }
      }
 +}
  
 -    if( !CV_IS_MAT(src))
 -        src = cvGetMat( src, &srcstub );
 -
 -    if( !CV_IS_MAT(dst))
 -        dst = cvGetMat( dst, &dststub );
 +}
  
 -    cn = CV_MAT_CN( src->type );
 +void cv::getRectSubPix( InputArray _image, Size patchSize, Point2f center,
 +                       OutputArray _patch, int patchType )
 +{
 +    Mat image = _image.getMat();
 +    int depth = image.depth(), cn = image.channels();
 +    int ddepth = patchType < 0 ? depth : CV_MAT_DEPTH(patchType);
  
 -    if( (cn != 1 && cn != 3) || !CV_ARE_CNS_EQ( src, dst ))
 -        CV_Error( CV_StsUnsupportedFormat, "" );
 +    CV_Assert( cn == 1 || cn == 3 );
  
 -    src_size = cvGetMatSize( src );
 -    dst_size = cvGetMatSize( dst );
 -    src_step = src->step ? src->step : CV_STUB_STEP;
 -    dst_step = dst->step ? dst->step : CV_STUB_STEP;
 +    _patch.create(patchSize, CV_MAKETYPE(ddepth, cn));
 +    Mat patch = _patch.getMat();
  
 -    //if( dst_size.width > src_size.width || dst_size.height > src_size.height )
 -    //    CV_ERROR( CV_StsBadSize, "destination ROI must be smaller than source ROI" );
+ #if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7)
+     CvPoint minpt, maxpt;
+     int srctype = CV_MAT_TYPE(src->type), dsttype = CV_MAT_TYPE(dst->type);
+     CvIPPGetRectSubPixFunc ippfunc =
+         srctype == CV_8UC1 && dsttype == CV_8UC1 ? (CvIPPGetRectSubPixFunc)ippiCopySubpixIntersect_8u_C1R :
+         srctype == CV_8UC1 && dsttype == CV_32FC1 ? (CvIPPGetRectSubPixFunc)ippiCopySubpixIntersect_8u32f_C1R :
+         srctype == CV_32FC1 && dsttype == CV_32FC1 ? (CvIPPGetRectSubPixFunc)ippiCopySubpixIntersect_32f_C1R : 0;
+     if( ippfunc && ippfunc(src->data.ptr, src->step, src_size, dst->data.ptr,
+                            dst->step, dst_size, center, &minpt, &maxpt) >= 0 )
+         return;
+ #endif
 -    if( CV_ARE_DEPTHS_EQ( src, dst ))
 -    {
 -        func = (CvGetRectSubPixFunc)(gr_tab[cn != 1].fn_2d[CV_MAT_DEPTH(src->type)]);
 -    }
 +    if( depth == CV_8U && ddepth == CV_8U )
 +        getRectSubPix_Cn_<uchar, uchar, int, scale_fixpt, cast_8u>
 +        (image.data, image.step, image.size(), patch.data, patch.step, patch.size(), center, cn);
 +    else if( depth == CV_8U && ddepth == CV_32F )
 +        getRectSubPix_8u32f
 +        (image.data, image.step, image.size(), (float*)patch.data, patch.step, patch.size(), center, cn);
 +    else if( depth == CV_32F && ddepth == CV_32F )
 +        getRectSubPix_Cn_<float, float, float, nop<float>, nop<float> >
 +        ((const float*)image.data, image.step, image.size(), (float*)patch.data, patch.step, patch.size(), center, cn);
      else
 -    {
 -        if( CV_MAT_DEPTH( src->type ) != CV_8U || CV_MAT_DEPTH( dst->type ) != CV_32F )
 -            CV_Error( CV_StsUnsupportedFormat, "" );
 -
 -        func = (CvGetRectSubPixFunc)(gr_tab[cn != 1].fn_2d[1]);
 -    }
 -
 -    if( !func )
 -        CV_Error( CV_StsUnsupportedFormat, "" );
 -
 -    IPPI_CALL( func( src->data.ptr, src_step, src_size,
 -                     dst->data.ptr, dst_step, dst_size, center ));
 +        CV_Error( CV_StsUnsupportedFormat, "Unsupported combination of input and output formats");
  }
  
  
@@@ -402,53 -776,113 +420,53 @@@ cvGetRectSubPix( const void* srcarr, vo
  CV_IMPL void
  cvGetQuadrangleSubPix( const void* srcarr, void* dstarr, const CvMat* mat )
  {
 -    static  CvFuncTable  gq_tab[2];
 -    static  int inittab = 0;
 -
 -    CvMat srcstub, *src = (CvMat*)srcarr;
 -    CvMat dststub, *dst = (CvMat*)dstarr;
 -    CvSize src_size, dst_size;
 -    CvGetQuadrangleSubPixFunc func;
 -    float m[6];
 -    int k, cn;
 -
 -    if( !inittab )
 +    cv::Mat src = cv::cvarrToMat(srcarr), m = cv::cvarrToMat(mat);
 +    const cv::Mat dst = cv::cvarrToMat(dstarr);
 +
 +    CV_Assert( src.channels() == dst.channels() );
 +
 +    cv::Size win_size = dst.size();
 +    double matrix[6];
 +    cv::Mat M(2, 3, CV_64F, matrix);
 +    m.convertTo(M, CV_64F);
 +    double dx = (win_size.width - 1)*0.5;
 +    double dy = (win_size.height - 1)*0.5;
 +    matrix[2] -= matrix[0]*dx + matrix[1]*dy;
 +    matrix[5] -= matrix[3]*dx + matrix[4]*dy;
 +
 +    if( src.depth() == CV_8U && dst.depth() == CV_32F )
 +        cv::getQuadrangleSubPix_8u32f_CnR( src.data, src.step, src.size(),
 +                                           (float*)dst.data, dst.step, dst.size(),
 +                                           matrix, src.channels());
 +    else
      {
 -        icvInitGetQuadrangleSubPixC1RTable( gq_tab + 0 );
 -        icvInitGetQuadrangleSubPixC3RTable( gq_tab + 1 );
 -        inittab = 1;
 +        CV_Assert( src.depth() == dst.depth() );
 +        cv::warpAffine(src, dst, M, dst.size(),
 +                       cv::INTER_LINEAR + cv::WARP_INVERSE_MAP,
 +                       cv::BORDER_REPLICATE);
      }
 +}
  
 -    if( !CV_IS_MAT(src))
 -        src = cvGetMat( src, &srcstub );
 -
 -    if( !CV_IS_MAT(dst))
 -        dst = cvGetMat( dst, &dststub );
 -
 -    if( !CV_IS_MAT(mat))
 -        CV_Error( CV_StsBadArg, "map matrix is not valid" );
 -
 -    cn = CV_MAT_CN( src->type );
 -
 -    if( (cn != 1 && cn != 3) || !CV_ARE_CNS_EQ( src, dst ))
 -        CV_Error( CV_StsUnsupportedFormat, "" );
 -
 -    src_size = cvGetMatSize( src );
 -    dst_size = cvGetMatSize( dst );
 -
 -    /*if( dst_size.width > src_size.width || dst_size.height > src_size.height )
 -        CV_ERROR( CV_StsBadSize, "destination ROI must not be larger than source ROI" );*/
  
 -    if( mat->rows != 2 || mat->cols != 3 )
 -        CV_Error( CV_StsBadArg,
 -        "Transformation matrix must be 2x3" );
 +CV_IMPL int
 +cvSampleLine( const void* _img, CvPoint pt1, CvPoint pt2,
 +              void* _buffer, int connectivity )
 +{
 +    cv::Mat img = cv::cvarrToMat(_img);
 +    cv::LineIterator li(img, pt1, pt2, connectivity, false);
 +    uchar* buffer = (uchar*)_buffer;
 +    size_t pixsize = img.elemSize();
-     
 -    if( CV_MAT_TYPE( mat->type ) == CV_32FC1 )
 -    {
 -        for( k = 0; k < 3; k++ )
 -        {
 -            m[k] = mat->data.fl[k];
 -            m[3 + k] = ((float*)(mat->data.ptr + mat->step))[k];
 -        }
 -    }
 -    else if( CV_MAT_TYPE( mat->type ) == CV_64FC1 )
 -    {
 -        for( k = 0; k < 3; k++ )
 -        {
 -            m[k] = (float)mat->data.db[k];
 -            m[3 + k] = (float)((double*)(mat->data.ptr + mat->step))[k];
 -        }
 -    }
 -    else
 -        CV_Error( CV_StsUnsupportedFormat,
 -            "The transformation matrix should have 32fC1 or 64fC1 type" );
 +    if( !buffer )
 +        CV_Error( CV_StsNullPtr, "" );
  
 -    if( CV_ARE_DEPTHS_EQ( src, dst ))
 -    {
 -        func = (CvGetQuadrangleSubPixFunc)(gq_tab[cn != 1].fn_2d[CV_MAT_DEPTH(src->type)]);
 -    }
 -    else
 +    for( int i = 0; i < li.count; i++, ++li )
      {
 -        if( CV_MAT_DEPTH( src->type ) != CV_8U || CV_MAT_DEPTH( dst->type ) != CV_32F )
 -            CV_Error( CV_StsUnsupportedFormat, "" );
 -
 -        func = (CvGetQuadrangleSubPixFunc)(gq_tab[cn != 1].fn_2d[1]);
 +        for( size_t k = 0; k < pixsize; k++ )
 +            *buffer++ = li.ptr[k];
      }
  
 -    if( !func )
 -        CV_Error( CV_StsUnsupportedFormat, "" );
 -
 -    IPPI_CALL( func( src->data.ptr, src->step, src_size,
 -                     dst->data.ptr, dst->step, dst_size, m ));
 +    return li.count;
  }
  
  
Simple merge
@@@ -345,6 -336,6 +345,6 @@@ The class ``SURF_OCL`` uses some buffer
  
  .. seealso:: :ocv:class:`SURF`
  
- .. Sample code::
+ .. note::
  
-    * : OCL : An example of the SURF detector can be found at opencv_source_code/samples/ocl/surf_matcher.cpp
 -   * OCL : An example of the SURF detector can be found at opencv_source_code/samples/ocl/surf_matcher.cpp
++   * OCL : An example of the SURF detector can be found at opencv_source_code/samples/ocl/surf_matcher.cpp
Simple merge
@@@ -12,14 -12,17 +12,14 @@@ Cascade classifier class used for objec
      class CV_EXPORTS OclCascadeClassifier : public CascadeClassifier
      {
      public:
 -          OclCascadeClassifier() {};
 -          ~OclCascadeClassifier() {};
 -           CvSeq *oclHaarDetectObjects(oclMat &gimg, CvMemStorage *storage,
 -                                      double scaleFactor,int minNeighbors,
 -                                      int flags, CvSize minSize = cvSize(0, 0),
 -                                      CvSize maxSize = cvSize(0, 0));
 +            void detectMultiScale(oclMat &image, CV_OUT std::vector<cv::Rect>& faces,
 +                                              double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0,
 +                                              Size minSize = Size(), Size maxSize = Size());
      };
  
- .. Sample code::
+ .. note::
  
-    * : OCL : A face detection example using cascade classifiers can be found at opencv_source_code/samples/ocl/facedetect.cpp
+    (Ocl) A face detection example using cascade classifiers can be found at opencv_source_code/samples/ocl/facedetect.cpp
  
  ocl::OclCascadeClassifier::oclHaarDetectObjects
  ------------------------------------------------------
index b1ed454,0000000..d4ce905
mode 100644,000000..100644
--- /dev/null
@@@ -1,1786 -1,0 +1,1811 @@@
 +/*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) 2010-2012, Institute Of Software Chinese Academy Of Science, all rights reserved.
 +// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
 +// Copyright (C) 2010-2012, Multicoreware, 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 oclMaterials 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_OCL_HPP__
 +#define __OPENCV_OCL_HPP__
 +
 +#include <memory>
 +#include <vector>
 +
 +#include "opencv2/core.hpp"
 +#include "opencv2/imgproc.hpp"
 +#include "opencv2/objdetect.hpp"
 +
 +namespace cv
 +{
 +    namespace ocl
 +    {
 +        enum
 +        {
 +            CVCL_DEVICE_TYPE_DEFAULT     = (1 << 0),
 +            CVCL_DEVICE_TYPE_CPU         = (1 << 1),
 +            CVCL_DEVICE_TYPE_GPU         = (1 << 2),
 +            CVCL_DEVICE_TYPE_ACCELERATOR = (1 << 3),
 +            //CVCL_DEVICE_TYPE_CUSTOM      = (1 << 4)
 +            CVCL_DEVICE_TYPE_ALL         = 0xFFFFFFFF
 +        };
 +
 +        enum DevMemRW
 +        {
 +            DEVICE_MEM_R_W = 0,
 +            DEVICE_MEM_R_ONLY,
 +            DEVICE_MEM_W_ONLY
 +        };
 +
 +        enum DevMemType
 +        {
 +            DEVICE_MEM_DEFAULT = 0,
 +            DEVICE_MEM_AHP,         //alloc host pointer
 +            DEVICE_MEM_UHP,         //use host pointer
 +            DEVICE_MEM_CHP,         //copy host pointer
 +            DEVICE_MEM_PM           //persistent memory
 +        };
 +
 +        //Get the global device memory and read/write type
 +        //return 1 if unified memory system supported, otherwise return 0
 +        CV_EXPORTS int getDevMemType(DevMemRW& rw_type, DevMemType& mem_type);
 +
 +        //Set the global device memory and read/write type,
 +        //the newly generated oclMat will all use this type
 +        //return -1 if the target type is unsupported, otherwise return 0
 +        CV_EXPORTS int setDevMemType(DevMemRW rw_type = DEVICE_MEM_R_W, DevMemType mem_type = DEVICE_MEM_DEFAULT);
 +
 +        //this class contains ocl runtime information
 +        class CV_EXPORTS Info
 +        {
 +        public:
 +            struct Impl;
 +            Impl *impl;
 +
 +            Info();
 +            Info(const Info &m);
 +            ~Info();
 +            void release();
 +            Info &operator = (const Info &m);
 +            std::vector<String> DeviceName;
 +            String PlatformName;
 +        };
 +        //////////////////////////////// Initialization & Info ////////////////////////
 +        //this function may be obsoleted
 +        //CV_EXPORTS cl_device_id getDevice();
 +        //the function must be called before any other cv::ocl::functions, it initialize ocl runtime
 +        //each Info relates to an OpenCL platform
 +        //there is one or more devices in each platform, each one has a separate name
 +        CV_EXPORTS int getDevice(std::vector<Info> &oclinfo, int devicetype = CVCL_DEVICE_TYPE_GPU);
 +
 +        //set device you want to use, optional function after getDevice be called
 +        //the devnum is the index of the selected device in DeviceName vector of INfo
 +        CV_EXPORTS void setDevice(Info &oclinfo, int devnum = 0);
 +
 +        //The two functions below enable other opencl program to use ocl module's cl_context and cl_command_queue
 +        //returns cl_context *
 +        CV_EXPORTS void* getoclContext();
 +        //returns cl_command_queue *
 +        CV_EXPORTS void* getoclCommandQueue();
 +
 +        //explicit call clFinish. The global command queue will be used.
 +        CV_EXPORTS void finish();
 +
 +        //this function enable ocl module to use customized cl_context and cl_command_queue
 +        //getDevice also need to be called before this function
 +        CV_EXPORTS void setDeviceEx(Info &oclinfo, void *ctx, void *qu, int devnum = 0);
 +
 +        //returns true when global OpenCL context is initialized
 +        CV_EXPORTS bool initialized();
 +
 +        //////////////////////////////// OpenCL context ////////////////////////
 +        //This is a global singleton class used to represent a OpenCL context.
 +        class CV_EXPORTS Context
 +        {
 +        protected:
 +            Context();
 +            friend class std::auto_ptr<Context>;
 +            friend bool initialized();
 +        private:
 +            static std::auto_ptr<Context> clCxt;
 +            static int val;
 +        public:
 +            ~Context();
 +            void release();
 +            Info::Impl* impl;
 +
 +            static Context *getContext();
 +            static void setContext(Info &oclinfo);
 +
 +            enum {CL_DOUBLE, CL_UNIFIED_MEM, CL_VER_1_2};
 +            bool supportsFeature(int ftype);
 +            size_t computeUnits();
 +            size_t maxWorkGroupSize();
 +            void* oclContext();
 +            void* oclCommandQueue();
 +        };
 +
 +        //! Calls a kernel, by string. Pass globalThreads = NULL, and cleanUp = true, to finally clean-up without executing.
 +        CV_EXPORTS double openCLExecuteKernelInterop(Context *clCxt ,
 +                                                        const char **source, String kernelName,
 +                                                        size_t globalThreads[3], size_t localThreads[3],
 +                                                        std::vector< std::pair<size_t, const void *> > &args,
 +                                                        int channels, int depth, const char *build_options,
 +                                                        bool finish = true, bool measureKernelTime = false,
 +                                                        bool cleanUp = true);
 +
 +        //! Calls a kernel, by file. Pass globalThreads = NULL, and cleanUp = true, to finally clean-up without executing.
 +        CV_EXPORTS double openCLExecuteKernelInterop(Context *clCxt ,
 +                                                        const char **fileName, const int numFiles, String kernelName,
 +                                                        size_t globalThreads[3], size_t localThreads[3],
 +                                                        std::vector< std::pair<size_t, const void *> > &args,
 +                                                        int channels, int depth, const char *build_options,
 +                                                        bool finish = true, bool measureKernelTime = false,
 +                                                        bool cleanUp = true);
 +
 +        //! Enable or disable OpenCL program binary caching onto local disk
 +        // After a program (*.cl files in opencl/ folder) is built at runtime, we allow the
 +        // compiled OpenCL program to be cached to the path automatically as "path/*.clb"
 +        // binary file, which will be reused when the OpenCV executable is started again.
 +        //
 +        // Caching mode is controlled by the following enums
 +        // Notes
 +        //   1. the feature is by default enabled when OpenCV is built in release mode.
 +        //   2. the CACHE_DEBUG / CACHE_RELEASE flags only effectively work with MSVC compiler;
 +        //      for GNU compilers, the function always treats the build as release mode (enabled by default).
 +        enum
 +        {
 +            CACHE_NONE    = 0,        // do not cache OpenCL binary
 +            CACHE_DEBUG   = 0x1 << 0, // cache OpenCL binary when built in debug mode (only work with MSVC)
 +            CACHE_RELEASE = 0x1 << 1, // default behavior, only cache when built in release mode (only work with MSVC)
 +            CACHE_ALL     = CACHE_DEBUG | CACHE_RELEASE, // always cache opencl binary
 +            CACHE_UPDATE  = 0x1 << 2  // if the binary cache file with the same name is already on the disk, it will be updated.
 +        };
 +        CV_EXPORTS void setBinaryDiskCache(int mode = CACHE_RELEASE, cv::String path = "./");
 +
 +        //! set where binary cache to be saved to
 +        CV_EXPORTS void setBinpath(const char *path);
 +
 +        class CV_EXPORTS oclMatExpr;
 +        //////////////////////////////// oclMat ////////////////////////////////
 +        class CV_EXPORTS oclMat
 +        {
 +        public:
 +            //! default constructor
 +            oclMat();
 +            //! constructs oclMatrix of the specified size and type (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
 +            oclMat(int rows, int cols, int type);
 +            oclMat(Size size, int type);
 +            //! constucts oclMatrix and fills it with the specified value _s.
 +            oclMat(int rows, int cols, int type, const Scalar &s);
 +            oclMat(Size size, int type, const Scalar &s);
 +            //! copy constructor
 +            oclMat(const oclMat &m);
 +
 +            //! constructor for oclMatrix headers pointing to user-allocated data
 +            oclMat(int rows, int cols, int type, void *data, size_t step = Mat::AUTO_STEP);
 +            oclMat(Size size, int type, void *data, size_t step = Mat::AUTO_STEP);
 +
 +            //! creates a matrix header for a part of the bigger matrix
 +            oclMat(const oclMat &m, const Range &rowRange, const Range &colRange);
 +            oclMat(const oclMat &m, const Rect &roi);
 +
 +            //! builds oclMat from Mat. Perfom blocking upload to device.
 +            explicit oclMat (const Mat &m);
 +
 +            //! destructor - calls release()
 +            ~oclMat();
 +
 +            //! assignment operators
 +            oclMat &operator = (const oclMat &m);
 +            //! assignment operator. Perfom blocking upload to device.
 +            oclMat &operator = (const Mat &m);
 +            oclMat &operator = (const oclMatExpr& expr);
 +
 +            //! pefroms blocking upload data to oclMat.
 +            void upload(const cv::Mat &m);
 +
 +
 +            //! downloads data from device to host memory. Blocking calls.
 +            operator Mat() const;
 +            void download(cv::Mat &m) const;
 +
 +            //! convert to _InputArray
 +            operator _InputArray();
 +
 +            //! convert to _OutputArray
 +            operator _OutputArray();
 +
 +            //! returns a new oclMatrix header for the specified row
 +            oclMat row(int y) const;
 +            //! returns a new oclMatrix header for the specified column
 +            oclMat col(int x) const;
 +            //! ... for the specified row span
 +            oclMat rowRange(int startrow, int endrow) const;
 +            oclMat rowRange(const Range &r) const;
 +            //! ... for the specified column span
 +            oclMat colRange(int startcol, int endcol) const;
 +            oclMat colRange(const Range &r) const;
 +
 +            //! returns deep copy of the oclMatrix, i.e. the data is copied
 +            oclMat clone() const;
 +            //! copies the oclMatrix content to "m".
 +            // It calls m.create(this->size(), this->type()).
 +            // It supports any data type
 +            void copyTo( oclMat &m ) const;
 +            //! copies those oclMatrix elements to "m" that are marked with non-zero mask elements.
 +            //It supports 8UC1 8UC4 32SC1 32SC4 32FC1 32FC4
 +            void copyTo( oclMat &m, const oclMat &mask ) const;
 +            //! converts oclMatrix to another datatype with optional scalng. See cvConvertScale.
 +            //It supports 8UC1 8UC4 32SC1 32SC4 32FC1 32FC4
 +            void convertTo( oclMat &m, int rtype, double alpha = 1, double beta = 0 ) const;
 +
 +            void assignTo( oclMat &m, int type = -1 ) const;
 +
 +            //! sets every oclMatrix element to s
 +            //It supports 8UC1 8UC4 32SC1 32SC4 32FC1 32FC4
 +            oclMat& operator = (const Scalar &s);
 +            //! sets some of the oclMatrix elements to s, according to the mask
 +            //It supports 8UC1 8UC4 32SC1 32SC4 32FC1 32FC4
 +            oclMat& setTo(const Scalar &s, const oclMat &mask = oclMat());
 +            //! creates alternative oclMatrix header for the same data, with different
 +            // number of channels and/or different number of rows. see cvReshape.
 +            oclMat reshape(int cn, int rows = 0) const;
 +
 +            //! allocates new oclMatrix data unless the oclMatrix already has specified size and type.
 +            // previous data is unreferenced if needed.
 +            void create(int rows, int cols, int type);
 +            void create(Size size, int type);
 +
 +            //! allocates new oclMatrix with specified device memory type.
 +            void createEx(int rows, int cols, int type,
 +                          DevMemRW rw_type, DevMemType mem_type, void* hptr = 0);
 +            void createEx(Size size, int type, DevMemRW rw_type,
 +                          DevMemType mem_type, void* hptr = 0);
 +
 +            //! decreases reference counter;
 +            // deallocate the data when reference counter reaches 0.
 +            void release();
 +
 +            //! swaps with other smart pointer
 +            void swap(oclMat &mat);
 +
 +            //! locates oclMatrix header within a parent oclMatrix. See below
 +            void locateROI( Size &wholeSize, Point &ofs ) const;
 +            //! moves/resizes the current oclMatrix ROI inside the parent oclMatrix.
 +            oclMat& adjustROI( int dtop, int dbottom, int dleft, int dright );
 +            //! extracts a rectangular sub-oclMatrix
 +            // (this is a generalized form of row, rowRange etc.)
 +            oclMat operator()( Range rowRange, Range colRange ) const;
 +            oclMat operator()( const Rect &roi ) const;
 +
 +            oclMat& operator+=( const oclMat& m );
 +            oclMat& operator-=( const oclMat& m );
 +            oclMat& operator*=( const oclMat& m );
 +            oclMat& operator/=( const oclMat& m );
 +
 +            //! returns true if the oclMatrix data is continuous
 +            // (i.e. when there are no gaps between successive rows).
 +            // similar to CV_IS_oclMat_CONT(cvoclMat->type)
 +            bool isContinuous() const;
 +            //! returns element size in bytes,
 +            // similar to CV_ELEM_SIZE(cvMat->type)
 +            size_t elemSize() const;
 +            //! returns the size of element channel in bytes.
 +            size_t elemSize1() const;
 +            //! returns element type, similar to CV_MAT_TYPE(cvMat->type)
 +            int type() const;
 +            //! returns element type, i.e. 8UC3 returns 8UC4 because in ocl
 +            //! 3 channels element actually use 4 channel space
 +            int ocltype() const;
 +            //! returns element type, similar to CV_MAT_DEPTH(cvMat->type)
 +            int depth() const;
 +            //! returns element type, similar to CV_MAT_CN(cvMat->type)
 +            int channels() const;
 +            //! returns element type, return 4 for 3 channels element,
 +            //!becuase 3 channels element actually use 4 channel space
 +            int oclchannels() const;
 +            //! returns step/elemSize1()
 +            size_t step1() const;
 +            //! returns oclMatrix size:
 +            // width == number of columns, height == number of rows
 +            Size size() const;
 +            //! returns true if oclMatrix data is NULL
 +            bool empty() const;
 +
 +            //! returns pointer to y-th row
 +            uchar* ptr(int y = 0);
 +            const uchar *ptr(int y = 0) const;
 +
 +            //! template version of the above method
 +            template<typename _Tp> _Tp *ptr(int y = 0);
 +            template<typename _Tp> const _Tp *ptr(int y = 0) const;
 +
 +            //! matrix transposition
 +            oclMat t() const;
 +
 +            /*! includes several bit-fields:
 +              - the magic signature
 +              - continuity flag
 +              - depth
 +              - number of channels
 +              */
 +            int flags;
 +            //! the number of rows and columns
 +            int rows, cols;
 +            //! a distance between successive rows in bytes; includes the gap if any
 +            size_t step;
 +            //! pointer to the data(OCL memory object)
 +            uchar *data;
 +
 +            //! pointer to the reference counter;
 +            // when oclMatrix points to user-allocated data, the pointer is NULL
 +            int *refcount;
 +
 +            //! helper fields used in locateROI and adjustROI
 +            //datastart and dataend are not used in current version
 +            uchar *datastart;
 +            uchar *dataend;
 +
 +            //! OpenCL context associated with the oclMat object.
 +            Context *clCxt;
 +            //add offset for handle ROI, calculated in byte
 +            int offset;
 +            //add wholerows and wholecols for the whole matrix, datastart and dataend are no longer used
 +            int wholerows;
 +            int wholecols;
 +        };
 +
 +        // convert InputArray/OutputArray to oclMat references
 +        CV_EXPORTS oclMat& getOclMatRef(InputArray src);
 +        CV_EXPORTS oclMat& getOclMatRef(OutputArray src);
 +
 +        ///////////////////// mat split and merge /////////////////////////////////
 +        //! Compose a multi-channel array from several single-channel arrays
 +        // Support all types
 +        CV_EXPORTS void merge(const oclMat *src, size_t n, oclMat &dst);
 +        CV_EXPORTS void merge(const std::vector<oclMat> &src, oclMat &dst);
 +
 +        //! Divides multi-channel array into several single-channel arrays
 +        // Support all types
 +        CV_EXPORTS void split(const oclMat &src, oclMat *dst);
 +        CV_EXPORTS void split(const oclMat &src, std::vector<oclMat> &dst);
 +
 +        ////////////////////////////// Arithmetics ///////////////////////////////////
 +        //#if defined DOUBLE_SUPPORT
 +        //typedef double F;
 +        //#else
 +        //typedef float F;
 +        //#endif
 +        //    CV_EXPORTS void addWeighted(const oclMat& a,F  alpha, const oclMat& b,F beta,F gama, oclMat& c);
 +        CV_EXPORTS void addWeighted(const oclMat &a, double  alpha, const oclMat &b, double beta, double gama, oclMat &c);
 +        //! adds one matrix to another (c = a + b)
 +        // supports all types except CV_8SC1,CV_8SC2,CV8SC3 and CV_8SC4
 +        CV_EXPORTS void add(const oclMat &a, const oclMat &b, oclMat &c);
 +        //! adds one matrix to another (c = a + b)
 +        // supports all types except CV_8SC1,CV_8SC2,CV8SC3 and CV_8SC4
 +        CV_EXPORTS void add(const oclMat &a, const oclMat &b, oclMat &c, const oclMat &mask);
 +        //! adds scalar to a matrix (c = a + s)
 +        // supports all types except CV_8SC1,CV_8SC2,CV8SC3 and CV_8SC4
 +        CV_EXPORTS void add(const oclMat &a, const Scalar &sc, oclMat &c, const oclMat &mask = oclMat());
 +        //! subtracts one matrix from another (c = a - b)
 +        // supports all types except CV_8SC1,CV_8SC2,CV8SC3 and CV_8SC4
 +        CV_EXPORTS void subtract(const oclMat &a, const oclMat &b, oclMat &c);
 +        //! subtracts one matrix from another (c = a - b)
 +        // supports all types except CV_8SC1,CV_8SC2,CV8SC3 and CV_8SC4
 +        CV_EXPORTS void subtract(const oclMat &a, const oclMat &b, oclMat &c, const oclMat &mask);
 +        //! subtracts scalar from a matrix (c = a - s)
 +        // supports all types except CV_8SC1,CV_8SC2,CV8SC3 and CV_8SC4
 +        CV_EXPORTS void subtract(const oclMat &a, const Scalar &sc, oclMat &c, const oclMat &mask = oclMat());
 +        //! subtracts scalar from a matrix (c = a - s)
 +        // supports all types except CV_8SC1,CV_8SC2,CV8SC3 and CV_8SC4
 +        CV_EXPORTS void subtract(const Scalar &sc, const oclMat &a, oclMat &c, const oclMat &mask = oclMat());
 +        //! computes element-wise product of the two arrays (c = a * b)
 +        // supports all types except CV_8SC1,CV_8SC2,CV8SC3 and CV_8SC4
 +        CV_EXPORTS void multiply(const oclMat &a, const oclMat &b, oclMat &c, double scale = 1);
 +        //! multiplies matrix to a number (dst = scalar * src)
 +        // supports CV_32FC1 only
 +        CV_EXPORTS void multiply(double scalar, const oclMat &src, oclMat &dst);
 +        //! computes element-wise quotient of the two arrays (c = a / b)
 +        // supports all types except CV_8SC1,CV_8SC2,CV8SC3 and CV_8SC4
 +        CV_EXPORTS void divide(const oclMat &a, const oclMat &b, oclMat &c, double scale = 1);
 +        //! computes element-wise quotient of the two arrays (c = a / b)
 +        // supports all types except CV_8SC1,CV_8SC2,CV8SC3 and CV_8SC4
 +        CV_EXPORTS void divide(double scale, const oclMat &b, oclMat &c);
 +
 +        //! compares elements of two arrays (c = a <cmpop> b)
 +        // supports except CV_8SC1,CV_8SC2,CV8SC3,CV_8SC4 types
 +        CV_EXPORTS void compare(const oclMat &a, const oclMat &b, oclMat &c, int cmpop);
 +
 +        //! transposes the matrix
 +        // supports  CV_8UC1, 8UC4, 8SC4, 16UC2, 16SC2, 32SC1 and 32FC1.(the same as cuda)
 +        CV_EXPORTS void transpose(const oclMat &src, oclMat &dst);
 +
 +        //! computes element-wise absolute difference of two arrays (c = abs(a - b))
 +        // supports all types except CV_8SC1,CV_8SC2,CV8SC3 and CV_8SC4
 +        CV_EXPORTS void absdiff(const oclMat &a, const oclMat &b, oclMat &c);
 +        //! computes element-wise absolute difference of array and scalar (c = abs(a - s))
 +        // supports all types except CV_8SC1,CV_8SC2,CV8SC3 and CV_8SC4
 +        CV_EXPORTS void absdiff(const oclMat &a, const Scalar &s, oclMat &c);
 +
 +        //! computes mean value and standard deviation of all or selected array elements
 +        // supports except CV_32F,CV_64F
 +        CV_EXPORTS void meanStdDev(const oclMat &mtx, Scalar &mean, Scalar &stddev);
 +
 +        //! computes norm of array
 +        // supports NORM_INF, NORM_L1, NORM_L2
 +        // supports only CV_8UC1 type
 +        CV_EXPORTS double norm(const oclMat &src1, int normType = NORM_L2);
 +
 +        //! computes norm of the difference between two arrays
 +        // supports NORM_INF, NORM_L1, NORM_L2
 +        // supports only CV_8UC1 type
 +        CV_EXPORTS double norm(const oclMat &src1, const oclMat &src2, int normType = NORM_L2);
 +
 +        //! reverses the order of the rows, columns or both in a matrix
 +        // supports all types
 +        CV_EXPORTS void flip(const oclMat &a, oclMat &b, int flipCode);
 +
 +        //! computes sum of array elements
 +        // disabled until fix crash
 +        // support all types
 +        CV_EXPORTS Scalar sum(const oclMat &m);
 +        CV_EXPORTS Scalar absSum(const oclMat &m);
 +        CV_EXPORTS Scalar sqrSum(const oclMat &m);
 +
 +        //! finds global minimum and maximum array elements and returns their values
 +        // support all C1 types
 +
 +        CV_EXPORTS void minMax(const oclMat &src, double *minVal, double *maxVal = 0, const oclMat &mask = oclMat());
 +        CV_EXPORTS void minMax_buf(const oclMat &src, double *minVal, double *maxVal, const oclMat &mask, oclMat& buf);
 +
 +        //! finds global minimum and maximum array elements and returns their values with locations
 +        // support all C1 types
 +
 +        CV_EXPORTS void minMaxLoc(const oclMat &src, double *minVal, double *maxVal = 0, Point *minLoc = 0, Point *maxLoc = 0,
 +                                  const oclMat &mask = oclMat());
 +
 +        //! counts non-zero array elements
 +        // support all types
 +        CV_EXPORTS int countNonZero(const oclMat &src);
 +
 +        //! transforms 8-bit unsigned integers using lookup table: dst(i)=lut(src(i))
 +        // destination array will have the depth type as lut and the same channels number as source
 +        //It supports 8UC1 8UC4 only
 +        CV_EXPORTS void LUT(const oclMat &src, const oclMat &lut, oclMat &dst);
 +
 +        //! only 8UC1 and 256 bins is supported now
 +        CV_EXPORTS void calcHist(const oclMat &mat_src, oclMat &mat_hist);
 +        //! only 8UC1 and 256 bins is supported now
 +        CV_EXPORTS void equalizeHist(const oclMat &mat_src, oclMat &mat_dst);
 +
 +        //! only 8UC1 is supported now
 +        CV_EXPORTS Ptr<cv::CLAHE> createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8));
 +
 +        //! bilateralFilter
 +        // supports 8UC1 8UC4
 +        CV_EXPORTS void bilateralFilter(const oclMat& src, oclMat& dst, int d, double sigmaColor, double sigmaSpave, int borderType=BORDER_DEFAULT);
 +        //! computes exponent of each matrix element (b = e**a)
 +        // supports only CV_32FC1 type
 +        CV_EXPORTS void exp(const oclMat &a, oclMat &b);
 +
 +        //! computes natural logarithm of absolute value of each matrix element: b = log(abs(a))
 +        // supports only CV_32FC1 type
 +        CV_EXPORTS void log(const oclMat &a, oclMat &b);
 +
 +        //! computes magnitude of each (x(i), y(i)) vector
 +        // supports only CV_32F CV_64F type
 +        CV_EXPORTS void magnitude(const oclMat &x, const oclMat &y, oclMat &magnitude);
 +        CV_EXPORTS void magnitudeSqr(const oclMat &x, const oclMat &y, oclMat &magnitude);
 +
 +        CV_EXPORTS void magnitudeSqr(const oclMat &x, oclMat &magnitude);
 +
 +        //! computes angle (angle(i)) of each (x(i), y(i)) vector
 +        // supports only CV_32F CV_64F type
 +        CV_EXPORTS void phase(const oclMat &x, const oclMat &y, oclMat &angle, bool angleInDegrees = false);
 +
 +        //! the function raises every element of tne input array to p
 +        //! support only CV_32F CV_64F type
 +        CV_EXPORTS void pow(const oclMat &x, double p, oclMat &y);
 +
 +        //! converts Cartesian coordinates to polar
 +        // supports only CV_32F CV_64F type
 +        CV_EXPORTS void cartToPolar(const oclMat &x, const oclMat &y, oclMat &magnitude, oclMat &angle, bool angleInDegrees = false);
 +
 +        //! converts polar coordinates to Cartesian
 +        // supports only CV_32F CV_64F type
 +        CV_EXPORTS void polarToCart(const oclMat &magnitude, const oclMat &angle, oclMat &x, oclMat &y, bool angleInDegrees = false);
 +
 +        //! perfroms per-elements bit-wise inversion
 +        // supports all types
 +        CV_EXPORTS void bitwise_not(const oclMat &src, oclMat &dst);
 +        //! calculates per-element bit-wise disjunction of two arrays
 +        // supports all types
 +        CV_EXPORTS void bitwise_or(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask = oclMat());
 +        CV_EXPORTS void bitwise_or(const oclMat &src1, const Scalar &s, oclMat &dst, const oclMat &mask = oclMat());
 +        //! calculates per-element bit-wise conjunction of two arrays
 +        // supports all types
 +        CV_EXPORTS void bitwise_and(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask = oclMat());
 +        CV_EXPORTS void bitwise_and(const oclMat &src1, const Scalar &s, oclMat &dst, const oclMat &mask = oclMat());
 +        //! calculates per-element bit-wise "exclusive or" operation
 +        // supports all types
 +        CV_EXPORTS void bitwise_xor(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask = oclMat());
 +        CV_EXPORTS void bitwise_xor(const oclMat &src1, const Scalar &s, oclMat &dst, const oclMat &mask = oclMat());
 +
 +        //! Logical operators
 +        CV_EXPORTS oclMat operator ~ (const oclMat &);
 +        CV_EXPORTS oclMat operator | (const oclMat &, const oclMat &);
 +        CV_EXPORTS oclMat operator & (const oclMat &, const oclMat &);
 +        CV_EXPORTS oclMat operator ^ (const oclMat &, const oclMat &);
 +
 +
 +        //! Mathematics operators
 +        CV_EXPORTS oclMatExpr operator + (const oclMat &src1, const oclMat &src2);
 +        CV_EXPORTS oclMatExpr operator - (const oclMat &src1, const oclMat &src2);
 +        CV_EXPORTS oclMatExpr operator * (const oclMat &src1, const oclMat &src2);
 +        CV_EXPORTS oclMatExpr operator / (const oclMat &src1, const oclMat &src2);
 +
 +        struct CV_EXPORTS ConvolveBuf
 +        {
 +            Size result_size;
 +            Size block_size;
 +            Size user_block_size;
 +            Size dft_size;
 +
 +            oclMat image_spect, templ_spect, result_spect;
 +            oclMat image_block, templ_block, result_data;
 +
 +            void create(Size image_size, Size templ_size);
 +            static Size estimateBlockSize(Size result_size, Size templ_size);
 +        };
 +
 +        //! computes convolution of two images, may use discrete Fourier transform
 +        //! support only CV_32FC1 type
 +        CV_EXPORTS void convolve(const oclMat &image, const oclMat &temp1, oclMat &result, bool ccorr = false);
 +        CV_EXPORTS void convolve(const oclMat &image, const oclMat &temp1, oclMat &result, bool ccorr, ConvolveBuf& buf);
 +
 +        //! Performs a per-element multiplication of two Fourier spectrums.
 +        //! Only full (not packed) CV_32FC2 complex spectrums in the interleaved format are supported for now.
 +        //! support only CV_32FC2 type
 +        CV_EXPORTS void mulSpectrums(const oclMat &a, const oclMat &b, oclMat &c, int flags, float scale, bool conjB = false);
 +
 +        CV_EXPORTS void cvtColor(const oclMat &src, oclMat &dst, int code , int dcn = 0);
 +
 +        //////////////////////////////// Filter Engine ////////////////////////////////
 +
 +        /*!
 +          The Base Class for 1D or Row-wise Filters
 +
 +          This is the base class for linear or non-linear filters that process 1D data.
 +          In particular, such filters are used for the "horizontal" filtering parts in separable filters.
 +          */
 +        class CV_EXPORTS BaseRowFilter_GPU
 +        {
 +        public:
 +            BaseRowFilter_GPU(int ksize_, int anchor_, int bordertype_) : ksize(ksize_), anchor(anchor_), bordertype(bordertype_) {}
 +            virtual ~BaseRowFilter_GPU() {}
 +            virtual void operator()(const oclMat &src, oclMat &dst) = 0;
 +            int ksize, anchor, bordertype;
 +        };
 +
 +        /*!
 +          The Base Class for Column-wise Filters
 +
 +          This is the base class for linear or non-linear filters that process columns of 2D arrays.
 +          Such filters are used for the "vertical" filtering parts in separable filters.
 +          */
 +        class CV_EXPORTS BaseColumnFilter_GPU
 +        {
 +        public:
 +            BaseColumnFilter_GPU(int ksize_, int anchor_, int bordertype_) : ksize(ksize_), anchor(anchor_), bordertype(bordertype_) {}
 +            virtual ~BaseColumnFilter_GPU() {}
 +            virtual void operator()(const oclMat &src, oclMat &dst) = 0;
 +            int ksize, anchor, bordertype;
 +        };
 +
 +        /*!
 +          The Base Class for Non-Separable 2D Filters.
 +
 +          This is the base class for linear or non-linear 2D filters.
 +          */
 +        class CV_EXPORTS BaseFilter_GPU
 +        {
 +        public:
 +            BaseFilter_GPU(const Size &ksize_, const Point &anchor_, const int &borderType_)
 +                : ksize(ksize_), anchor(anchor_), borderType(borderType_) {}
 +            virtual ~BaseFilter_GPU() {}
 +            virtual void operator()(const oclMat &src, oclMat &dst) = 0;
 +            Size ksize;
 +            Point anchor;
 +            int borderType;
 +        };
 +
 +        /*!
 +          The Base Class for Filter Engine.
 +
 +          The class can be used to apply an arbitrary filtering operation to an image.
 +          It contains all the necessary intermediate buffers.
 +          */
 +        class CV_EXPORTS FilterEngine_GPU
 +        {
 +        public:
 +            virtual ~FilterEngine_GPU() {}
 +
 +            virtual void apply(const oclMat &src, oclMat &dst, Rect roi = Rect(0, 0, -1, -1)) = 0;
 +        };
 +
 +        //! returns the non-separable filter engine with the specified filter
 +        CV_EXPORTS Ptr<FilterEngine_GPU> createFilter2D_GPU(const Ptr<BaseFilter_GPU> filter2D);
 +
 +        //! returns the primitive row filter with the specified kernel
 +        CV_EXPORTS Ptr<BaseRowFilter_GPU> getLinearRowFilter_GPU(int srcType, int bufType, const Mat &rowKernel,
 +                int anchor = -1, int bordertype = BORDER_DEFAULT);
 +
 +        //! returns the primitive column filter with the specified kernel
 +        CV_EXPORTS Ptr<BaseColumnFilter_GPU> getLinearColumnFilter_GPU(int bufType, int dstType, const Mat &columnKernel,
 +                int anchor = -1, int bordertype = BORDER_DEFAULT, double delta = 0.0);
 +
 +        //! returns the separable linear filter engine
 +        CV_EXPORTS Ptr<FilterEngine_GPU> createSeparableLinearFilter_GPU(int srcType, int dstType, const Mat &rowKernel,
 +                const Mat &columnKernel, const Point &anchor = Point(-1, -1), double delta = 0.0, int bordertype = BORDER_DEFAULT);
 +
 +        //! returns the separable filter engine with the specified filters
 +        CV_EXPORTS Ptr<FilterEngine_GPU> createSeparableFilter_GPU(const Ptr<BaseRowFilter_GPU> &rowFilter,
 +                const Ptr<BaseColumnFilter_GPU> &columnFilter);
 +
 +        //! returns the Gaussian filter engine
 +        CV_EXPORTS Ptr<FilterEngine_GPU> createGaussianFilter_GPU(int type, Size ksize, double sigma1, double sigma2 = 0, int bordertype = BORDER_DEFAULT);
 +
 +        //! returns filter engine for the generalized Sobel operator
 +        CV_EXPORTS Ptr<FilterEngine_GPU> createDerivFilter_GPU( int srcType, int dstType, int dx, int dy, int ksize, int borderType = BORDER_DEFAULT );
 +
 +        //! applies Laplacian operator to the image
 +        // supports only ksize = 1 and ksize = 3 8UC1 8UC4 32FC1 32FC4 data type
 +        CV_EXPORTS void Laplacian(const oclMat &src, oclMat &dst, int ddepth, int ksize = 1, double scale = 1);
 +
 +        //! returns 2D box filter
 +        // supports CV_8UC1 and CV_8UC4 source type, dst type must be the same as source type
 +        CV_EXPORTS Ptr<BaseFilter_GPU> getBoxFilter_GPU(int srcType, int dstType,
 +                const Size &ksize, Point anchor = Point(-1, -1), int borderType = BORDER_DEFAULT);
 +
 +        //! returns box filter engine
 +        CV_EXPORTS Ptr<FilterEngine_GPU> createBoxFilter_GPU(int srcType, int dstType, const Size &ksize,
 +                const Point &anchor = Point(-1, -1), int borderType = BORDER_DEFAULT);
 +
 +        //! returns 2D filter with the specified kernel
 +        // supports CV_8UC1 and CV_8UC4 types
 +        CV_EXPORTS Ptr<BaseFilter_GPU> getLinearFilter_GPU(int srcType, int dstType, const Mat &kernel, const Size &ksize,
 +                Point anchor = Point(-1, -1), int borderType = BORDER_DEFAULT);
 +
 +        //! returns the non-separable linear filter engine
 +        CV_EXPORTS Ptr<FilterEngine_GPU> createLinearFilter_GPU(int srcType, int dstType, const Mat &kernel,
 +                const Point &anchor = Point(-1, -1), int borderType = BORDER_DEFAULT);
 +
 +        //! smooths the image using the normalized box filter
 +        // supports data type: CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4
 +        // supports border type: BORDER_CONSTANT, BORDER_REPLICATE, BORDER_REFLECT,BORDER_REFLECT_101,BORDER_WRAP
 +        CV_EXPORTS void boxFilter(const oclMat &src, oclMat &dst, int ddepth, Size ksize,
 +                                  Point anchor = Point(-1, -1), int borderType = BORDER_DEFAULT);
 +
 +        //! returns 2D morphological filter
 +        //! only MORPH_ERODE and MORPH_DILATE are supported
 +        // supports CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4 types
 +        // kernel must have CV_8UC1 type, one rows and cols == ksize.width * ksize.height
 +        CV_EXPORTS Ptr<BaseFilter_GPU> getMorphologyFilter_GPU(int op, int type, const Mat &kernel, const Size &ksize,
 +                Point anchor = Point(-1, -1));
 +
 +        //! returns morphological filter engine. Only MORPH_ERODE and MORPH_DILATE are supported.
 +        CV_EXPORTS Ptr<FilterEngine_GPU> createMorphologyFilter_GPU(int op, int type, const Mat &kernel,
 +                const Point &anchor = Point(-1, -1), int iterations = 1);
 +
 +        //! a synonym for normalized box filter
 +        // supports data type: CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4
 +        // supports border type: BORDER_CONSTANT, BORDER_REPLICATE, BORDER_REFLECT,BORDER_REFLECT_101
 +        static inline void blur(const oclMat &src, oclMat &dst, Size ksize, Point anchor = Point(-1, -1),
 +                                int borderType = BORDER_CONSTANT)
 +        {
 +            boxFilter(src, dst, -1, ksize, anchor, borderType);
 +        }
 +
 +        //! applies non-separable 2D linear filter to the image
 +        //  Note, at the moment this function only works when anchor point is in the kernel center
 +        //  and kernel size supported is either 3x3 or 5x5; otherwise the function will fail to output valid result
 +        CV_EXPORTS void filter2D(const oclMat &src, oclMat &dst, int ddepth, const Mat &kernel,
 +                                 Point anchor = Point(-1, -1), int borderType = BORDER_DEFAULT);
 +
 +        //! applies separable 2D linear filter to the image
 +        CV_EXPORTS void sepFilter2D(const oclMat &src, oclMat &dst, int ddepth, const Mat &kernelX, const Mat &kernelY,
 +                                    Point anchor = Point(-1, -1), double delta = 0.0, int bordertype = BORDER_DEFAULT);
 +
 +        //! applies generalized Sobel operator to the image
 +        // dst.type must equalize src.type
 +        // supports data type: CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4
 +        // supports border type: BORDER_CONSTANT, BORDER_REPLICATE, BORDER_REFLECT,BORDER_REFLECT_101
 +        CV_EXPORTS void Sobel(const oclMat &src, oclMat &dst, int ddepth, int dx, int dy, int ksize = 3, double scale = 1, double delta = 0.0, int bordertype = BORDER_DEFAULT);
 +
 +        //! applies the vertical or horizontal Scharr operator to the image
 +        // dst.type must equalize src.type
 +        // supports data type: CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4
 +        // supports border type: BORDER_CONSTANT, BORDER_REPLICATE, BORDER_REFLECT,BORDER_REFLECT_101
 +        CV_EXPORTS void Scharr(const oclMat &src, oclMat &dst, int ddepth, int dx, int dy, double scale = 1, double delta = 0.0, int bordertype = BORDER_DEFAULT);
 +
 +        //! smooths the image using Gaussian filter.
 +        // dst.type must equalize src.type
 +        // supports data type: CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4
 +        // supports border type: BORDER_CONSTANT, BORDER_REPLICATE, BORDER_REFLECT,BORDER_REFLECT_101
 +        CV_EXPORTS void GaussianBlur(const oclMat &src, oclMat &dst, Size ksize, double sigma1, double sigma2 = 0, int bordertype = BORDER_DEFAULT);
 +
 +        //! erodes the image (applies the local minimum operator)
 +        // supports data type: CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4
 +        CV_EXPORTS void erode( const oclMat &src, oclMat &dst, const Mat &kernel, Point anchor = Point(-1, -1), int iterations = 1,
 +
 +                               int borderType = BORDER_CONSTANT, const Scalar &borderValue = morphologyDefaultBorderValue());
 +
 +
 +        //! dilates the image (applies the local maximum operator)
 +        // supports data type: CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4
 +        CV_EXPORTS void dilate( const oclMat &src, oclMat &dst, const Mat &kernel, Point anchor = Point(-1, -1), int iterations = 1,
 +
 +                                int borderType = BORDER_CONSTANT, const Scalar &borderValue = morphologyDefaultBorderValue());
 +
 +
 +        //! applies an advanced morphological operation to the image
 +        CV_EXPORTS void morphologyEx( const oclMat &src, oclMat &dst, int op, const Mat &kernel, Point anchor = Point(-1, -1), int iterations = 1,
 +
 +                                      int borderType = BORDER_CONSTANT, const Scalar &borderValue = morphologyDefaultBorderValue());
 +
 +
 +        ////////////////////////////// Image processing //////////////////////////////
 +        //! Does mean shift filtering on GPU.
 +        CV_EXPORTS void meanShiftFiltering(const oclMat &src, oclMat &dst, int sp, int sr,
 +                                           TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1));
 +
 +        //! Does mean shift procedure on GPU.
 +        CV_EXPORTS void meanShiftProc(const oclMat &src, oclMat &dstr, oclMat &dstsp, int sp, int sr,
 +                                      TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1));
 +
 +        //! Does mean shift segmentation with elimiation of small regions.
 +        CV_EXPORTS void meanShiftSegmentation(const oclMat &src, Mat &dst, int sp, int sr, int minsize,
 +                                              TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1));
 +
 +        //! applies fixed threshold to the image.
 +        // supports CV_8UC1 and CV_32FC1 data type
 +        // supports threshold type: THRESH_BINARY, THRESH_BINARY_INV, THRESH_TRUNC, THRESH_TOZERO, THRESH_TOZERO_INV
 +        CV_EXPORTS double threshold(const oclMat &src, oclMat &dst, double thresh, double maxVal, int type = THRESH_TRUNC);
 +
 +        //! resizes the image
 +        // Supports INTER_NEAREST, INTER_LINEAR
 +        // supports CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4 types
 +        CV_EXPORTS void resize(const oclMat &src, oclMat &dst, Size dsize, double fx = 0, double fy = 0, int interpolation = INTER_LINEAR);
 +
 +        //! Applies a generic geometrical transformation to an image.
 +
 +        // Supports INTER_NEAREST, INTER_LINEAR.
 +
 +        // Map1 supports CV_16SC2, CV_32FC2  types.
 +
 +        // Src supports CV_8UC1, CV_8UC2, CV_8UC4.
 +
 +        CV_EXPORTS void remap(const oclMat &src, oclMat &dst, oclMat &map1, oclMat &map2, int interpolation, int bordertype, const Scalar &value = Scalar());
 +
 +        //! copies 2D array to a larger destination array and pads borders with user-specifiable constant
 +        // supports CV_8UC1, CV_8UC4, CV_32SC1 types
 +        CV_EXPORTS void copyMakeBorder(const oclMat &src, oclMat &dst, int top, int bottom, int left, int right, int boardtype, const Scalar &value = Scalar());
 +
 +        //! Smoothes image using median filter
 +        // The source 1- or 4-channel image. When m is 3 or 5, the image depth should be CV 8U or CV 32F.
 +        CV_EXPORTS void medianFilter(const oclMat &src, oclMat &dst, int m);
 +
 +        //! warps the image using affine transformation
 +        // Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC
 +        // supports CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4 types
 +        CV_EXPORTS void warpAffine(const oclMat &src, oclMat &dst, const Mat &M, Size dsize, int flags = INTER_LINEAR);
 +
 +        //! warps the image using perspective transformation
 +        // Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC
 +        // supports CV_8UC1, CV_8UC4, CV_32FC1 and CV_32FC4 types
 +        CV_EXPORTS void warpPerspective(const oclMat &src, oclMat &dst, const Mat &M, Size dsize, int flags = INTER_LINEAR);
 +
 +        //! computes the integral image and integral for the squared image
 +        // sum will have CV_32S type, sqsum - CV32F type
 +        // supports only CV_8UC1 source type
 +        CV_EXPORTS void integral(const oclMat &src, oclMat &sum, oclMat &sqsum);
 +        CV_EXPORTS void integral(const oclMat &src, oclMat &sum);
 +        CV_EXPORTS void cornerHarris(const oclMat &src, oclMat &dst, int blockSize, int ksize, double k, int bordertype = cv::BORDER_DEFAULT);
 +        CV_EXPORTS void cornerHarris_dxdy(const oclMat &src, oclMat &dst, oclMat &Dx, oclMat &Dy,
 +            int blockSize, int ksize, double k, int bordertype = cv::BORDER_DEFAULT);
 +        CV_EXPORTS void cornerMinEigenVal(const oclMat &src, oclMat &dst, int blockSize, int ksize, int bordertype = cv::BORDER_DEFAULT);
 +        CV_EXPORTS void cornerMinEigenVal_dxdy(const oclMat &src, oclMat &dst, oclMat &Dx, oclMat &Dy,
 +            int blockSize, int ksize, int bordertype = cv::BORDER_DEFAULT);
 +
 +
 +        /////////////////////////////////// ML ///////////////////////////////////////////
 +
 +        //! Compute closest centers for each lines in source and lable it after center's index
 +        // supports CV_32FC1/CV_32FC2/CV_32FC4 data type
 +        CV_EXPORTS void distanceToCenters(oclMat &dists, oclMat &labels, const oclMat &src, const oclMat &centers);
 +
 +        //!Does k-means procedure on GPU
 +        // supports CV_32FC1/CV_32FC2/CV_32FC4 data type
 +        CV_EXPORTS double kmeans(const oclMat &src, int K, oclMat &bestLabels,
 +                                     TermCriteria criteria, int attemps, int flags, oclMat &centers);
 +
 +
 +        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 +        ///////////////////////////////////////////CascadeClassifier//////////////////////////////////////////////////////////////////
 +        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 +        class CV_EXPORTS OclCascadeClassifier : public  cv::CascadeClassifier
 +        {
 +        public:
 +            void detectMultiScale(oclMat &image, CV_OUT std::vector<cv::Rect>& faces,
 +                                  double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0,
 +                                  Size minSize = Size(), Size maxSize = Size());
 +        };
 +
 +        /////////////////////////////// Pyramid /////////////////////////////////////
 +        CV_EXPORTS void pyrDown(const oclMat &src, oclMat &dst);
 +
 +        //! upsamples the source image and then smoothes it
 +        CV_EXPORTS void pyrUp(const oclMat &src, oclMat &dst);
 +
 +        //! performs linear blending of two images
 +        //! to avoid accuracy errors sum of weigths shouldn't be very close to zero
 +        // supports only CV_8UC1 source type
 +        CV_EXPORTS void blendLinear(const oclMat &img1, const oclMat &img2, const oclMat &weights1, const oclMat &weights2, oclMat &result);
 +
 +        //! computes vertical sum, supports only CV_32FC1 images
 +        CV_EXPORTS void columnSum(const oclMat &src, oclMat &sum);
 +
 +        ///////////////////////////////////////// match_template /////////////////////////////////////////////////////////////
 +        struct CV_EXPORTS MatchTemplateBuf
 +        {
 +            Size user_block_size;
 +            oclMat imagef, templf;
 +            std::vector<oclMat> images;
 +            std::vector<oclMat> image_sums;
 +            std::vector<oclMat> image_sqsums;
 +        };
 +
 +        //! computes the proximity map for the raster template and the image where the template is searched for
 +        // Supports TM_SQDIFF, TM_SQDIFF_NORMED, TM_CCORR, TM_CCORR_NORMED, TM_CCOEFF, TM_CCOEFF_NORMED for type 8UC1 and 8UC4
 +        // Supports TM_SQDIFF, TM_CCORR for type 32FC1 and 32FC4
 +        CV_EXPORTS void matchTemplate(const oclMat &image, const oclMat &templ, oclMat &result, int method);
 +
 +        //! computes the proximity map for the raster template and the image where the template is searched for
 +        // Supports TM_SQDIFF, TM_SQDIFF_NORMED, TM_CCORR, TM_CCORR_NORMED, TM_CCOEFF, TM_CCOEFF_NORMED for type 8UC1 and 8UC4
 +        // Supports TM_SQDIFF, TM_CCORR for type 32FC1 and 32FC4
 +        CV_EXPORTS void matchTemplate(const oclMat &image, const oclMat &templ, oclMat &result, int method, MatchTemplateBuf &buf);
 +
 +
 +
 +        ///////////////////////////////////////////// Canny /////////////////////////////////////////////
 +        struct CV_EXPORTS CannyBuf;
 +
 +        //! compute edges of the input image using Canny operator
 +        // Support CV_8UC1 only
 +        CV_EXPORTS void Canny(const oclMat &image, oclMat &edges, double low_thresh, double high_thresh, int apperture_size = 3, bool L2gradient = false);
 +        CV_EXPORTS void Canny(const oclMat &image, CannyBuf &buf, oclMat &edges, double low_thresh, double high_thresh, int apperture_size = 3, bool L2gradient = false);
 +        CV_EXPORTS void Canny(const oclMat &dx, const oclMat &dy, oclMat &edges, double low_thresh, double high_thresh, bool L2gradient = false);
 +        CV_EXPORTS void Canny(const oclMat &dx, const oclMat &dy, CannyBuf &buf, oclMat &edges, double low_thresh, double high_thresh, bool L2gradient = false);
 +
 +        struct CV_EXPORTS CannyBuf
 +        {
 +            CannyBuf() : counter(NULL) {}
 +            ~CannyBuf()
 +            {
 +                release();
 +            }
 +            explicit CannyBuf(const Size &image_size, int apperture_size = 3) : counter(NULL)
 +            {
 +                create(image_size, apperture_size);
 +            }
 +            CannyBuf(const oclMat &dx_, const oclMat &dy_);
 +            void create(const Size &image_size, int apperture_size = 3);
 +            void release();
 +
 +            oclMat dx, dy;
 +            oclMat dx_buf, dy_buf;
 +            oclMat magBuf, mapBuf;
 +            oclMat trackBuf1, trackBuf2;
 +            void *counter;
 +            Ptr<FilterEngine_GPU> filterDX, filterDY;
 +        };
 +
 +        ///////////////////////////////////////// Hough Transform /////////////////////////////////////////
 +        //! HoughCircles
 +        struct HoughCirclesBuf
 +        {
 +            oclMat edges;
 +            oclMat accum;
 +            oclMat srcPoints;
 +            oclMat centers;
 +            CannyBuf cannyBuf;
 +        };
 +
 +        CV_EXPORTS void HoughCircles(const oclMat& src, oclMat& circles, int method, float dp, float minDist, int cannyThreshold, int votesThreshold, int minRadius, int maxRadius, int maxCircles = 4096);
 +        CV_EXPORTS void HoughCircles(const oclMat& src, oclMat& circles, HoughCirclesBuf& buf, int method, float dp, float minDist, int cannyThreshold, int votesThreshold, int minRadius, int maxRadius, int maxCircles = 4096);
 +        CV_EXPORTS void HoughCirclesDownload(const oclMat& d_circles, OutputArray h_circles);
 +
 +
 +        ///////////////////////////////////////// clAmdFft related /////////////////////////////////////////
 +        //! Performs a forward or inverse discrete Fourier transform (1D or 2D) of floating point matrix.
 +        //! Param dft_size is the size of DFT transform.
 +        //!
 +        //! For complex-to-real transform it is assumed that the source matrix is packed in CLFFT's format.
 +        // support src type of CV32FC1, CV32FC2
 +        // support flags: DFT_INVERSE, DFT_REAL_OUTPUT, DFT_COMPLEX_OUTPUT, DFT_ROWS
 +        // dft_size is the size of original input, which is used for transformation from complex to real.
 +        // dft_size must be powers of 2, 3 and 5
 +        // real to complex dft requires at least v1.8 clAmdFft
 +        // real to complex dft output is not the same with cpu version
 +        // real to complex and complex to real does not support DFT_ROWS
 +        CV_EXPORTS void dft(const oclMat &src, oclMat &dst, Size dft_size = Size(0, 0), int flags = 0);
 +
 +        //! implements generalized matrix product algorithm GEMM from BLAS
 +        // The functionality requires clAmdBlas library
 +        // only support type CV_32FC1
 +        // flag GEMM_3_T is not supported
 +        CV_EXPORTS void gemm(const oclMat &src1, const oclMat &src2, double alpha,
 +                             const oclMat &src3, double beta, oclMat &dst, int flags = 0);
 +
 +        //////////////// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector //////////////
 +
 +        struct CV_EXPORTS HOGDescriptor
 +
 +        {
 +
 +            enum { DEFAULT_WIN_SIGMA = -1 };
 +
 +            enum { DEFAULT_NLEVELS = 64 };
 +
 +            enum { DESCR_FORMAT_ROW_BY_ROW, DESCR_FORMAT_COL_BY_COL };
 +
 +
 +
 +            HOGDescriptor(Size win_size = Size(64, 128), Size block_size = Size(16, 16),
 +
 +                          Size block_stride = Size(8, 8), Size cell_size = Size(8, 8),
 +
 +                          int nbins = 9, double win_sigma = DEFAULT_WIN_SIGMA,
 +
 +                          double threshold_L2hys = 0.2, bool gamma_correction = true,
 +
 +                          int nlevels = DEFAULT_NLEVELS);
 +
 +
 +
 +            size_t getDescriptorSize() const;
 +
 +            size_t getBlockHistogramSize() const;
 +
 +
 +
 +            void setSVMDetector(const std::vector<float> &detector);
 +
 +
 +
 +            static std::vector<float> getDefaultPeopleDetector();
 +
 +            static std::vector<float> getPeopleDetector48x96();
 +
 +            static std::vector<float> getPeopleDetector64x128();
 +
 +
 +
 +            void detect(const oclMat &img, std::vector<Point> &found_locations,
 +
 +                        double hit_threshold = 0, Size win_stride = Size(),
 +
 +                        Size padding = Size());
 +
 +
 +
 +            void detectMultiScale(const oclMat &img, std::vector<Rect> &found_locations,
 +
 +                                  double hit_threshold = 0, Size win_stride = Size(),
 +
 +                                  Size padding = Size(), double scale0 = 1.05,
 +
 +                                  int group_threshold = 2);
 +
 +
 +
 +            void getDescriptors(const oclMat &img, Size win_stride,
 +
 +                                oclMat &descriptors,
 +
 +                                int descr_format = DESCR_FORMAT_COL_BY_COL);
 +
 +
 +
 +            Size win_size;
 +
 +            Size block_size;
 +
 +            Size block_stride;
 +
 +            Size cell_size;
 +
 +            int nbins;
 +
 +            double win_sigma;
 +
 +            double threshold_L2hys;
 +
 +            bool gamma_correction;
 +
 +            int nlevels;
 +
 +
 +
 +        protected:
 +
 +            // initialize buffers; only need to do once in case of multiscale detection
 +
 +            void init_buffer(const oclMat &img, Size win_stride);
 +
 +
 +
 +            void computeBlockHistograms(const oclMat &img);
 +
 +            void computeGradient(const oclMat &img, oclMat &grad, oclMat &qangle);
 +
 +
 +
 +            double getWinSigma() const;
 +
 +            bool checkDetectorSize() const;
 +
 +
 +
 +            static int numPartsWithin(int size, int part_size, int stride);
 +
 +            static Size numPartsWithin(Size size, Size part_size, Size stride);
 +
 +
 +
 +            // Coefficients of the separating plane
 +
 +            float free_coef;
 +
 +            oclMat detector;
 +
 +
 +
 +            // Results of the last classification step
 +
 +            oclMat labels;
 +
 +            Mat labels_host;
 +
 +
 +
 +            // Results of the last histogram evaluation step
 +
 +            oclMat block_hists;
 +
 +
 +
 +            // Gradients conputation results
 +
 +            oclMat grad, qangle;
 +
 +
 +
 +            // scaled image
 +
 +            oclMat image_scale;
 +
 +
 +
 +            // effect size of input image (might be different from original size after scaling)
 +
 +            Size effect_size;
 +
 +        };
 +
 +
 +        ////////////////////////feature2d_ocl/////////////////
 +        /****************************************************************************************\
 +        *                                      Distance                                          *
 +        \****************************************************************************************/
 +        template<typename T>
 +        struct CV_EXPORTS Accumulator
 +        {
 +            typedef T Type;
 +        };
 +        template<> struct Accumulator<unsigned char>
 +        {
 +            typedef float Type;
 +        };
 +        template<> struct Accumulator<unsigned short>
 +        {
 +            typedef float Type;
 +        };
 +        template<> struct Accumulator<char>
 +        {
 +            typedef float Type;
 +        };
 +        template<> struct Accumulator<short>
 +        {
 +            typedef float Type;
 +        };
 +
 +        /*
 +         * Manhattan distance (city block distance) functor
 +         */
 +        template<class T>
 +        struct CV_EXPORTS L1
 +        {
 +            enum { normType = NORM_L1 };
 +            typedef T ValueType;
 +            typedef typename Accumulator<T>::Type ResultType;
 +
 +            ResultType operator()( const T *a, const T *b, int size ) const
 +            {
 +                return normL1<ValueType, ResultType>(a, b, size);
 +            }
 +        };
 +
 +        /*
 +         * Euclidean distance functor
 +         */
 +        template<class T>
 +        struct CV_EXPORTS L2
 +        {
 +            enum { normType = NORM_L2 };
 +            typedef T ValueType;
 +            typedef typename Accumulator<T>::Type ResultType;
 +
 +            ResultType operator()( const T *a, const T *b, int size ) const
 +            {
 +                return (ResultType)std::sqrt((double)normL2Sqr<ValueType, ResultType>(a, b, size));
 +            }
 +        };
 +
 +        /*
 +         * Hamming distance functor - counts the bit differences between two strings - useful for the Brief descriptor
 +         * bit count of A exclusive XOR'ed with B
 +         */
 +        struct CV_EXPORTS Hamming
 +        {
 +            enum { normType = NORM_HAMMING };
 +            typedef unsigned char ValueType;
 +            typedef int ResultType;
 +
 +            /** this will count the bits in a ^ b
 +             */
 +            ResultType operator()( const unsigned char *a, const unsigned char *b, int size ) const
 +            {
 +                return normHamming(a, b, size);
 +            }
 +        };
 +
 +        ////////////////////////////////// BruteForceMatcher //////////////////////////////////
 +
 +        class CV_EXPORTS BruteForceMatcher_OCL_base
 +        {
 +        public:
 +            enum DistType {L1Dist = 0, L2Dist, HammingDist};
 +            explicit BruteForceMatcher_OCL_base(DistType distType = L2Dist);
 +
 +            // Add descriptors to train descriptor collection
 +            void add(const std::vector<oclMat> &descCollection);
 +
 +            // Get train descriptors collection
 +            const std::vector<oclMat> &getTrainDescriptors() const;
 +
 +            // Clear train descriptors collection
 +            void clear();
 +
 +            // Return true if there are not train descriptors in collection
 +            bool empty() const;
 +
 +            // Return true if the matcher supports mask in match methods
 +            bool isMaskSupported() const;
 +
 +            // Find one best match for each query descriptor
 +            void matchSingle(const oclMat &query, const oclMat &train,
 +                             oclMat &trainIdx, oclMat &distance,
 +                             const oclMat &mask = oclMat());
 +
 +            // Download trainIdx and distance and convert it to CPU vector with DMatch
 +            static void matchDownload(const oclMat &trainIdx, const oclMat &distance, std::vector<DMatch> &matches);
 +            // Convert trainIdx and distance to vector with DMatch
 +            static void matchConvert(const Mat &trainIdx, const Mat &distance, std::vector<DMatch> &matches);
 +
 +            // Find one best match for each query descriptor
 +            void match(const oclMat &query, const oclMat &train, std::vector<DMatch> &matches, const oclMat &mask = oclMat());
 +
 +            // Make gpu collection of trains and masks in suitable format for matchCollection function
 +            void makeGpuCollection(oclMat &trainCollection, oclMat &maskCollection, const std::vector<oclMat> &masks = std::vector<oclMat>());
 +
 +            // Find one best match from train collection for each query descriptor
 +            void matchCollection(const oclMat &query, const oclMat &trainCollection,
 +                                 oclMat &trainIdx, oclMat &imgIdx, oclMat &distance,
 +                                 const oclMat &masks = oclMat());
 +
 +            // Download trainIdx, imgIdx and distance and convert it to vector with DMatch
 +            static void matchDownload(const oclMat &trainIdx, const oclMat &imgIdx, const oclMat &distance, std::vector<DMatch> &matches);
 +            // Convert trainIdx, imgIdx and distance to vector with DMatch
 +            static void matchConvert(const Mat &trainIdx, const Mat &imgIdx, const Mat &distance, std::vector<DMatch> &matches);
 +
 +            // Find one best match from train collection for each query descriptor.
 +            void match(const oclMat &query, std::vector<DMatch> &matches, const std::vector<oclMat> &masks = std::vector<oclMat>());
 +
 +            // Find k best matches for each query descriptor (in increasing order of distances)
 +            void knnMatchSingle(const oclMat &query, const oclMat &train,
 +                                oclMat &trainIdx, oclMat &distance, oclMat &allDist, int k,
 +                                const oclMat &mask = oclMat());
 +
 +            // Download trainIdx and distance and convert it to vector with DMatch
 +            // compactResult is used when mask is not empty. If compactResult is false matches
 +            // vector will have the same size as queryDescriptors rows. If compactResult is true
 +            // matches vector will not contain matches for fully masked out query descriptors.
 +            static void knnMatchDownload(const oclMat &trainIdx, const oclMat &distance,
 +                                         std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
 +            // Convert trainIdx and distance to vector with DMatch
 +            static void knnMatchConvert(const Mat &trainIdx, const Mat &distance,
 +                                        std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
 +
 +            // Find k best matches for each query descriptor (in increasing order of distances).
 +            // compactResult is used when mask is not empty. If compactResult is false matches
 +            // vector will have the same size as queryDescriptors rows. If compactResult is true
 +            // matches vector will not contain matches for fully masked out query descriptors.
 +            void knnMatch(const oclMat &query, const oclMat &train,
 +                          std::vector< std::vector<DMatch> > &matches, int k, const oclMat &mask = oclMat(),
 +                          bool compactResult = false);
 +
 +            // Find k best matches from train collection for each query descriptor (in increasing order of distances)
 +            void knnMatch2Collection(const oclMat &query, const oclMat &trainCollection,
 +                                     oclMat &trainIdx, oclMat &imgIdx, oclMat &distance,
 +                                     const oclMat &maskCollection = oclMat());
 +
 +            // Download trainIdx and distance and convert it to vector with DMatch
 +            // compactResult is used when mask is not empty. If compactResult is false matches
 +            // vector will have the same size as queryDescriptors rows. If compactResult is true
 +            // matches vector will not contain matches for fully masked out query descriptors.
 +            static void knnMatch2Download(const oclMat &trainIdx, const oclMat &imgIdx, const oclMat &distance,
 +                                          std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
 +            // Convert trainIdx and distance to vector with DMatch
 +            static void knnMatch2Convert(const Mat &trainIdx, const Mat &imgIdx, const Mat &distance,
 +                                         std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
 +
 +            // Find k best matches  for each query descriptor (in increasing order of distances).
 +            // compactResult is used when mask is not empty. If compactResult is false matches
 +            // vector will have the same size as queryDescriptors rows. If compactResult is true
 +            // matches vector will not contain matches for fully masked out query descriptors.
 +            void knnMatch(const oclMat &query, std::vector< std::vector<DMatch> > &matches, int k,
 +                          const std::vector<oclMat> &masks = std::vector<oclMat>(), bool compactResult = false);
 +
 +            // Find best matches for each query descriptor which have distance less than maxDistance.
 +            // nMatches.at<int>(0, queryIdx) will contain matches count for queryIdx.
 +            // carefully nMatches can be greater than trainIdx.cols - it means that matcher didn't find all matches,
 +            // because it didn't have enough memory.
 +            // If trainIdx is empty, then trainIdx and distance will be created with size nQuery x max((nTrain / 100), 10),
 +            // otherwize user can pass own allocated trainIdx and distance with size nQuery x nMaxMatches
 +            // Matches doesn't sorted.
 +            void radiusMatchSingle(const oclMat &query, const oclMat &train,
 +                                   oclMat &trainIdx, oclMat &distance, oclMat &nMatches, float maxDistance,
 +                                   const oclMat &mask = oclMat());
 +
 +            // Download trainIdx, nMatches and distance and convert it to vector with DMatch.
 +            // matches will be sorted in increasing order of distances.
 +            // compactResult is used when mask is not empty. If compactResult is false matches
 +            // vector will have the same size as queryDescriptors rows. If compactResult is true
 +            // matches vector will not contain matches for fully masked out query descriptors.
 +            static void radiusMatchDownload(const oclMat &trainIdx, const oclMat &distance, const oclMat &nMatches,
 +                                            std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
 +            // Convert trainIdx, nMatches and distance to vector with DMatch.
 +            static void radiusMatchConvert(const Mat &trainIdx, const Mat &distance, const Mat &nMatches,
 +                                           std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
 +
 +            // Find best matches for each query descriptor which have distance less than maxDistance
 +            // in increasing order of distances).
 +            void radiusMatch(const oclMat &query, const oclMat &train,
 +                             std::vector< std::vector<DMatch> > &matches, float maxDistance,
 +                             const oclMat &mask = oclMat(), bool compactResult = false);
 +
 +            // Find best matches for each query descriptor which have distance less than maxDistance.
 +            // If trainIdx is empty, then trainIdx and distance will be created with size nQuery x max((nQuery / 100), 10),
 +            // otherwize user can pass own allocated trainIdx and distance with size nQuery x nMaxMatches
 +            // Matches doesn't sorted.
 +            void radiusMatchCollection(const oclMat &query, oclMat &trainIdx, oclMat &imgIdx, oclMat &distance, oclMat &nMatches, float maxDistance,
 +                                       const std::vector<oclMat> &masks = std::vector<oclMat>());
 +
 +            // Download trainIdx, imgIdx, nMatches and distance and convert it to vector with DMatch.
 +            // matches will be sorted in increasing order of distances.
 +            // compactResult is used when mask is not empty. If compactResult is false matches
 +            // vector will have the same size as queryDescriptors rows. If compactResult is true
 +            // matches vector will not contain matches for fully masked out query descriptors.
 +            static void radiusMatchDownload(const oclMat &trainIdx, const oclMat &imgIdx, const oclMat &distance, const oclMat &nMatches,
 +                                            std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
 +            // Convert trainIdx, nMatches and distance to vector with DMatch.
 +            static void radiusMatchConvert(const Mat &trainIdx, const Mat &imgIdx, const Mat &distance, const Mat &nMatches,
 +                                           std::vector< std::vector<DMatch> > &matches, bool compactResult = false);
 +
 +            // Find best matches from train collection for each query descriptor which have distance less than
 +            // maxDistance (in increasing order of distances).
 +            void radiusMatch(const oclMat &query, std::vector< std::vector<DMatch> > &matches, float maxDistance,
 +                             const std::vector<oclMat> &masks = std::vector<oclMat>(), bool compactResult = false);
 +
 +            DistType distType;
 +
 +        private:
 +            std::vector<oclMat> trainDescCollection;
 +        };
 +
 +        template <class Distance>
 +        class CV_EXPORTS BruteForceMatcher_OCL;
 +
 +        template <typename T>
 +        class CV_EXPORTS BruteForceMatcher_OCL< L1<T> > : public BruteForceMatcher_OCL_base
 +        {
 +        public:
 +            explicit BruteForceMatcher_OCL() : BruteForceMatcher_OCL_base(L1Dist) {}
 +            explicit BruteForceMatcher_OCL(L1<T> /*d*/) : BruteForceMatcher_OCL_base(L1Dist) {}
 +        };
 +        template <typename T>
 +        class CV_EXPORTS BruteForceMatcher_OCL< L2<T> > : public BruteForceMatcher_OCL_base
 +        {
 +        public:
 +            explicit BruteForceMatcher_OCL() : BruteForceMatcher_OCL_base(L2Dist) {}
 +            explicit BruteForceMatcher_OCL(L2<T> /*d*/) : BruteForceMatcher_OCL_base(L2Dist) {}
 +        };
 +        template <> class CV_EXPORTS BruteForceMatcher_OCL< Hamming > : public BruteForceMatcher_OCL_base
 +        {
 +        public:
 +            explicit BruteForceMatcher_OCL() : BruteForceMatcher_OCL_base(HammingDist) {}
 +            explicit BruteForceMatcher_OCL(Hamming /*d*/) : BruteForceMatcher_OCL_base(HammingDist) {}
 +        };
 +
 +        class CV_EXPORTS BFMatcher_OCL : public BruteForceMatcher_OCL_base
 +        {
 +        public:
 +            explicit BFMatcher_OCL(int norm = NORM_L2) : BruteForceMatcher_OCL_base(norm == NORM_L1 ? L1Dist : norm == NORM_L2 ? L2Dist : HammingDist) {}
 +        };
 +
 +        class CV_EXPORTS GoodFeaturesToTrackDetector_OCL
 +        {
 +        public:
 +            explicit GoodFeaturesToTrackDetector_OCL(int maxCorners = 1000, double qualityLevel = 0.01, double minDistance = 0.0,
 +                int blockSize = 3, bool useHarrisDetector = false, double harrisK = 0.04);
 +
 +            //! return 1 rows matrix with CV_32FC2 type
 +            void operator ()(const oclMat& image, oclMat& corners, const oclMat& mask = oclMat());
 +            //! download points of type Point2f to a vector. the vector's content will be erased
 +            void downloadPoints(const oclMat &points, std::vector<Point2f> &points_v);
 +
 +            int maxCorners;
 +            double qualityLevel;
 +            double minDistance;
 +
 +            int blockSize;
 +            bool useHarrisDetector;
 +            double harrisK;
 +            void releaseMemory()
 +            {
 +                Dx_.release();
 +                Dy_.release();
 +                eig_.release();
 +                minMaxbuf_.release();
 +                tmpCorners_.release();
 +            }
 +        private:
 +            oclMat Dx_;
 +            oclMat Dy_;
 +            oclMat eig_;
 +            oclMat minMaxbuf_;
 +            oclMat tmpCorners_;
 +        };
 +
 +        inline GoodFeaturesToTrackDetector_OCL::GoodFeaturesToTrackDetector_OCL(int maxCorners_, double qualityLevel_, double minDistance_,
 +            int blockSize_, bool useHarrisDetector_, double harrisK_)
 +        {
 +            maxCorners = maxCorners_;
 +            qualityLevel = qualityLevel_;
 +            minDistance = minDistance_;
 +            blockSize = blockSize_;
 +            useHarrisDetector = useHarrisDetector_;
 +            harrisK = harrisK_;
 +        }
 +
 +        /////////////////////////////// PyrLKOpticalFlow /////////////////////////////////////
 +
 +        class CV_EXPORTS PyrLKOpticalFlow
 +        {
 +        public:
 +            PyrLKOpticalFlow()
 +            {
 +                winSize = Size(21, 21);
 +                maxLevel = 3;
 +                iters = 30;
 +                derivLambda = 0.5;
 +                useInitialFlow = false;
 +                minEigThreshold = 1e-4f;
 +                getMinEigenVals = false;
 +                isDeviceArch11_ = false;
 +            }
 +
 +            void sparse(const oclMat &prevImg, const oclMat &nextImg, const oclMat &prevPts, oclMat &nextPts,
 +                        oclMat &status, oclMat *err = 0);
 +
 +            void dense(const oclMat &prevImg, const oclMat &nextImg, oclMat &u, oclMat &v, oclMat *err = 0);
 +
 +            Size winSize;
 +            int maxLevel;
 +            int iters;
 +            double derivLambda;
 +            bool useInitialFlow;
 +            float minEigThreshold;
 +            bool getMinEigenVals;
 +
 +            void releaseMemory()
 +            {
 +                dx_calcBuf_.release();
 +                dy_calcBuf_.release();
 +
 +                prevPyr_.clear();
 +                nextPyr_.clear();
 +
 +                dx_buf_.release();
 +                dy_buf_.release();
 +            }
 +
 +        private:
 +            void calcSharrDeriv(const oclMat &src, oclMat &dx, oclMat &dy);
 +
 +            void buildImagePyramid(const oclMat &img0, std::vector<oclMat> &pyr, bool withBorder);
 +
 +            oclMat dx_calcBuf_;
 +            oclMat dy_calcBuf_;
 +
 +            std::vector<oclMat> prevPyr_;
 +            std::vector<oclMat> nextPyr_;
 +
 +            oclMat dx_buf_;
 +            oclMat dy_buf_;
 +
 +            oclMat uPyr_[2];
 +            oclMat vPyr_[2];
 +
 +            bool isDeviceArch11_;
 +        };
 +
 +        class CV_EXPORTS FarnebackOpticalFlow
 +        {
 +        public:
 +            FarnebackOpticalFlow();
 +
 +            int numLevels;
 +            double pyrScale;
 +            bool fastPyramids;
 +            int winSize;
 +            int numIters;
 +            int polyN;
 +            double polySigma;
 +            int flags;
 +
 +            void operator ()(const oclMat &frame0, const oclMat &frame1, oclMat &flowx, oclMat &flowy);
 +
 +            void releaseMemory();
 +
 +        private:
 +            void prepareGaussian(
 +                int n, double sigma, float *g, float *xg, float *xxg,
 +                double &ig11, double &ig03, double &ig33, double &ig55);
 +
 +            void setPolynomialExpansionConsts(int n, double sigma);
 +
 +            void updateFlow_boxFilter(
 +                const oclMat& R0, const oclMat& R1, oclMat& flowx, oclMat &flowy,
 +                oclMat& M, oclMat &bufM, int blockSize, bool updateMatrices);
 +
 +            void updateFlow_gaussianBlur(
 +                const oclMat& R0, const oclMat& R1, oclMat& flowx, oclMat& flowy,
 +                oclMat& M, oclMat &bufM, int blockSize, bool updateMatrices);
 +
 +            oclMat frames_[2];
 +            oclMat pyrLevel_[2], M_, bufM_, R_[2], blurredFrame_[2];
 +            std::vector<oclMat> pyramid0_, pyramid1_;
 +        };
 +
 +        //////////////// build warping maps ////////////////////
 +        //! builds plane warping maps
 +        CV_EXPORTS void buildWarpPlaneMaps(Size src_size, Rect dst_roi, const Mat &K, const Mat &R, const Mat &T, float scale, oclMat &map_x, oclMat &map_y);
 +        //! builds cylindrical warping maps
 +        CV_EXPORTS void buildWarpCylindricalMaps(Size src_size, Rect dst_roi, const Mat &K, const Mat &R, float scale, oclMat &map_x, oclMat &map_y);
 +        //! builds spherical warping maps
 +        CV_EXPORTS void buildWarpSphericalMaps(Size src_size, Rect dst_roi, const Mat &K, const Mat &R, float scale, oclMat &map_x, oclMat &map_y);
 +        //! builds Affine warping maps
 +        CV_EXPORTS void buildWarpAffineMaps(const Mat &M, bool inverse, Size dsize, oclMat &xmap, oclMat &ymap);
 +
 +        //! builds Perspective warping maps
 +        CV_EXPORTS void buildWarpPerspectiveMaps(const Mat &M, bool inverse, Size dsize, oclMat &xmap, oclMat &ymap);
 +
 +        ///////////////////////////////////// interpolate frames //////////////////////////////////////////////
 +        //! Interpolate frames (images) using provided optical flow (displacement field).
 +        //! frame0   - frame 0 (32-bit floating point images, single channel)
 +        //! frame1   - frame 1 (the same type and size)
 +        //! fu       - forward horizontal displacement
 +        //! fv       - forward vertical displacement
 +        //! bu       - backward horizontal displacement
 +        //! bv       - backward vertical displacement
 +        //! pos      - new frame position
 +        //! newFrame - new frame
 +        //! buf      - temporary buffer, will have width x 6*height size, CV_32FC1 type and contain 6 oclMat;
 +        //!            occlusion masks            0, occlusion masks            1,
 +        //!            interpolated forward flow  0, interpolated forward flow  1,
 +        //!            interpolated backward flow 0, interpolated backward flow 1
 +        //!
 +        CV_EXPORTS void interpolateFrames(const oclMat &frame0, const oclMat &frame1,
 +                                          const oclMat &fu, const oclMat &fv,
 +                                          const oclMat &bu, const oclMat &bv,
 +                                          float pos, oclMat &newFrame, oclMat &buf);
 +
 +        //! computes moments of the rasterized shape or a vector of points
 +        CV_EXPORTS Moments ocl_moments(InputArray _array, bool binaryImage);
 +
 +        class CV_EXPORTS StereoBM_OCL
 +        {
 +        public:
 +            enum { BASIC_PRESET = 0, PREFILTER_XSOBEL = 1 };
 +
 +            enum { DEFAULT_NDISP = 64, DEFAULT_WINSZ = 19 };
 +
 +            //! the default constructor
 +            StereoBM_OCL();
 +            //! the full constructor taking the camera-specific preset, number of disparities and the SAD window size. ndisparities must be multiple of 8.
 +            StereoBM_OCL(int preset, int ndisparities = DEFAULT_NDISP, int winSize = DEFAULT_WINSZ);
 +
 +            //! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair
 +            //! Output disparity has CV_8U type.
 +            void operator() ( const oclMat &left, const oclMat &right, oclMat &disparity);
 +
 +            //! Some heuristics that tries to estmate
 +            // if current GPU will be faster then CPU in this algorithm.
 +            // It queries current active device.
 +            static bool checkIfGpuCallReasonable();
 +
 +            int preset;
 +            int ndisp;
 +            int winSize;
 +
 +            // If avergeTexThreshold  == 0 => post procesing is disabled
 +            // If avergeTexThreshold != 0 then disparity is set 0 in each point (x,y) where for left image
 +            // SumOfHorizontalGradiensInWindow(x, y, winSize) < (winSize * winSize) * avergeTexThreshold
 +            // i.e. input left image is low textured.
 +            float avergeTexThreshold;
 +        private:
 +            oclMat minSSD, leBuf, riBuf;
 +        };
 +
 +        class CV_EXPORTS StereoBeliefPropagation
 +        {
 +        public:
 +            enum { DEFAULT_NDISP  = 64 };
 +            enum { DEFAULT_ITERS  = 5  };
 +            enum { DEFAULT_LEVELS = 5  };
 +            static void estimateRecommendedParams(int width, int height, int &ndisp, int &iters, int &levels);
 +            explicit StereoBeliefPropagation(int ndisp  = DEFAULT_NDISP,
 +                                             int iters  = DEFAULT_ITERS,
 +                                             int levels = DEFAULT_LEVELS,
 +                                             int msg_type = CV_16S);
 +            StereoBeliefPropagation(int ndisp, int iters, int levels,
 +                                    float max_data_term, float data_weight,
 +                                    float max_disc_term, float disc_single_jump,
 +                                    int msg_type = CV_32F);
 +            void operator()(const oclMat &left, const oclMat &right, oclMat &disparity);
 +            void operator()(const oclMat &data, oclMat &disparity);
 +            int ndisp;
 +            int iters;
 +            int levels;
 +            float max_data_term;
 +            float data_weight;
 +            float max_disc_term;
 +            float disc_single_jump;
 +            int msg_type;
 +        private:
 +            oclMat u, d, l, r, u2, d2, l2, r2;
 +            std::vector<oclMat> datas;
 +            oclMat out;
 +        };
 +
 +        class CV_EXPORTS StereoConstantSpaceBP
 +        {
 +        public:
 +            enum { DEFAULT_NDISP    = 128 };
 +            enum { DEFAULT_ITERS    = 8   };
 +            enum { DEFAULT_LEVELS   = 4   };
 +            enum { DEFAULT_NR_PLANE = 4   };
 +            static void estimateRecommendedParams(int width, int height, int &ndisp, int &iters, int &levels, int &nr_plane);
 +            explicit StereoConstantSpaceBP(
 +                int ndisp    = DEFAULT_NDISP,
 +                int iters    = DEFAULT_ITERS,
 +                int levels   = DEFAULT_LEVELS,
 +                int nr_plane = DEFAULT_NR_PLANE,
 +                int msg_type = CV_32F);
 +            StereoConstantSpaceBP(int ndisp, int iters, int levels, int nr_plane,
 +                float max_data_term, float data_weight, float max_disc_term, float disc_single_jump,
 +                int min_disp_th = 0,
 +                int msg_type = CV_32F);
 +            void operator()(const oclMat &left, const oclMat &right, oclMat &disparity);
 +            int ndisp;
 +            int iters;
 +            int levels;
 +            int nr_plane;
 +            float max_data_term;
 +            float data_weight;
 +            float max_disc_term;
 +            float disc_single_jump;
 +            int min_disp_th;
 +            int msg_type;
 +            bool use_local_init_data_cost;
 +        private:
 +            oclMat u[2], d[2], l[2], r[2];
 +            oclMat disp_selected_pyr[2];
 +            oclMat data_cost;
 +            oclMat data_cost_selected;
 +            oclMat temp;
 +            oclMat out;
 +        };
 +
 +        // Implementation of the Zach, Pock and Bischof Dual TV-L1 Optical Flow method
 +        //
 +        // see reference:
 +        //   [1] C. Zach, T. Pock and H. Bischof, "A Duality Based Approach for Realtime TV-L1 Optical Flow".
 +        //   [2] Javier Sanchez, Enric Meinhardt-Llopis and Gabriele Facciolo. "TV-L1 Optical Flow Estimation".
 +        class CV_EXPORTS OpticalFlowDual_TVL1_OCL
 +        {
 +        public:
 +            OpticalFlowDual_TVL1_OCL();
 +
 +            void operator ()(const oclMat& I0, const oclMat& I1, oclMat& flowx, oclMat& flowy);
 +
 +            void collectGarbage();
 +
 +            /**
 +            * Time step of the numerical scheme.
 +            */
 +            double tau;
 +
 +            /**
 +            * Weight parameter for the data term, attachment parameter.
 +            * This is the most relevant parameter, which determines the smoothness of the output.
 +            * The smaller this parameter is, the smoother the solutions we obtain.
 +            * It depends on the range of motions of the images, so its value should be adapted to each image sequence.
 +            */
 +            double lambda;
 +
 +            /**
 +            * Weight parameter for (u - v)^2, tightness parameter.
 +            * It serves as a link between the attachment and the regularization terms.
 +            * In theory, it should have a small value in order to maintain both parts in correspondence.
 +            * The method is stable for a large range of values of this parameter.
 +            */
 +            double theta;
 +
 +            /**
 +            * Number of scales used to create the pyramid of images.
 +            */
 +            int nscales;
 +
 +            /**
 +            * Number of warpings per scale.
 +            * Represents the number of times that I1(x+u0) and grad( I1(x+u0) ) are computed per scale.
 +            * This is a parameter that assures the stability of the method.
 +            * It also affects the running time, so it is a compromise between speed and accuracy.
 +            */
 +            int warps;
 +
 +            /**
 +            * Stopping criterion threshold used in the numerical scheme, which is a trade-off between precision and running time.
 +            * A small value will yield more accurate solutions at the expense of a slower convergence.
 +            */
 +            double epsilon;
 +
 +            /**
 +            * Stopping criterion iterations number used in the numerical scheme.
 +            */
 +            int iterations;
 +
 +            bool useInitialFlow;
 +
 +        private:
 +            void procOneScale(const oclMat& I0, const oclMat& I1, oclMat& u1, oclMat& u2);
 +
 +            std::vector<oclMat> I0s;
 +            std::vector<oclMat> I1s;
 +            std::vector<oclMat> u1s;
 +            std::vector<oclMat> u2s;
 +
 +            oclMat I1x_buf;
 +            oclMat I1y_buf;
 +
 +            oclMat I1w_buf;
 +            oclMat I1wx_buf;
 +            oclMat I1wy_buf;
 +
 +            oclMat grad_buf;
 +            oclMat rho_c_buf;
 +
 +            oclMat p11_buf;
 +            oclMat p12_buf;
 +            oclMat p21_buf;
 +            oclMat p22_buf;
 +
 +            oclMat diff_buf;
 +            oclMat norm_buf;
 +        };
++        // current supported sorting methods
++        enum
++        {
++            SORT_BITONIC,   // only support power-of-2 buffer size
++            SORT_SELECTION, // cannot sort duplicate keys
++            SORT_MERGE,
++            SORT_RADIX      // only support signed int/float keys(CV_32S/CV_32F)
++        };
++        //! Returns the sorted result of all the elements in input based on equivalent keys.
++        //
++        //  The element unit in the values to be sorted is determined from the data type, 
++        //  i.e., a CV_32FC2 input {a1a2, b1b2} will be considered as two elements, regardless its
++        //  matrix dimension.
++        //  both keys and values will be sorted inplace
++        //  Key needs to be single channel oclMat.
++        //
++        //  Example:
++        //  input -
++        //    keys   = {2,    3,   1}   (CV_8UC1)
++        //    values = {10,5, 4,3, 6,2} (CV_8UC2)
++        //  sortByKey(keys, values, SORT_SELECTION, false);
++        //  output -
++        //    keys   = {1,    2,   3}   (CV_8UC1)
++        //    values = {6,2, 10,5, 4,3} (CV_8UC2)
++        void CV_EXPORTS sortByKey(oclMat& keys, oclMat& values, int method, bool isGreaterThan = false);
 +    }
 +}
 +#if defined _MSC_VER && _MSC_VER >= 1200
 +#  pragma warning( push)
 +#  pragma warning( disable: 4267)
 +#endif
 +#include "opencv2/ocl/matrix_operations.hpp"
 +#if defined _MSC_VER && _MSC_VER >= 1200
 +#  pragma warning( pop)
 +#endif
 +
 +#endif /* __OPENCV_OCL_HPP__ */
@@@ -31,8 -32,8 +31,8 @@@ The function reconstructs the selected 
  http://en.wikipedia.org/wiki/Inpainting
  for more details.
  
- .. Sample code::
+ .. note::
  
-    * An example using the inpainting technique can be found at opencv_source_code/samples/cpp/inpaint.cpp
+    * An example using the inpainting technique can be found at opencv_source_code/samples/cpp/inpaint.cpp
  
-    * : PYTHON : An example using the inpainting technique can be found at opencv_source_code/samples/python2/inpaint.py
 -   * (Python) An example using the inpainting technique can be found at opencv_source_code/samples/python2/inpaint.py
++   * (Python) An example using the inpainting technique can be found at opencv_source_code/samples/python2/inpaint.py
Simple merge
Simple merge
index b53f759,0000000..5d98810
mode 100644,000000..100644
--- /dev/null
@@@ -1,567 -1,0 +1,559 @@@
- #include "cvconfig.h"
- #ifndef GTEST_CREATE_SHARED_LIBRARY
- #ifdef BUILD_SHARED_LIBS
- #define GTEST_LINKED_AS_SHARED_LIBRARY 1
- #endif
- #endif
 +#ifndef __OPENCV_GTESTCV_HPP__
 +#define __OPENCV_GTESTCV_HPP__
 +
 +#include "opencv2/core/cvdef.h"
 +#include <stdarg.h> // for va_list
 +
 +#ifdef HAVE_WINRT
 +    #pragma warning(disable:4447) // Disable warning 'main' signature found without threading model
 +#endif
 +
 +#ifdef _MSC_VER
 +#pragma warning( disable: 4127 )
 +#endif
 +
 +#define GTEST_DONT_DEFINE_FAIL      0
 +#define GTEST_DONT_DEFINE_SUCCEED   0
 +#define GTEST_DONT_DEFINE_ASSERT_EQ 0
 +#define GTEST_DONT_DEFINE_ASSERT_NE 0
 +#define GTEST_DONT_DEFINE_ASSERT_LE 0
 +#define GTEST_DONT_DEFINE_ASSERT_LT 0
 +#define GTEST_DONT_DEFINE_ASSERT_GE 0
 +#define GTEST_DONT_DEFINE_ASSERT_GT 0
 +#define GTEST_DONT_DEFINE_TEST      0
 +
 +#include "opencv2/ts/ts_gtest.h"
 +
 +#ifndef GTEST_USES_SIMPLE_RE
 +#  define GTEST_USES_SIMPLE_RE 0
 +#endif
 +#ifndef GTEST_USES_POSIX_RE
 +#  define GTEST_USES_POSIX_RE 0
 +#endif
 +
 +#include "opencv2/core.hpp"
 +#include "opencv2/core/utility.hpp"
 +
 +namespace cvtest
 +{
 +
 +using std::vector;
 +using std::string;
 +using cv::RNG;
 +using cv::Mat;
 +using cv::Scalar;
 +using cv::Size;
 +using cv::Point;
 +using cv::Rect;
 +
 +class CV_EXPORTS TS;
 +
 +CV_EXPORTS int64 readSeed(const char* str);
 +
 +CV_EXPORTS void randUni( RNG& rng, Mat& a, const Scalar& param1, const Scalar& param2 );
 +
 +inline unsigned randInt( RNG& rng )
 +{
 +    return (unsigned)rng;
 +}
 +
 +inline  double randReal( RNG& rng )
 +{
 +    return (double)rng;
 +}
 +
 +
 +CV_EXPORTS const char* getTypeName( int type );
 +CV_EXPORTS int typeByName( const char* type_name );
 +
 +CV_EXPORTS string vec2str(const string& sep, const int* v, size_t nelems);
 +
 +inline int clipInt( int val, int min_val, int max_val )
 +{
 +    if( val < min_val )
 +        val = min_val;
 +    if( val > max_val )
 +        val = max_val;
 +    return val;
 +}
 +
 +CV_EXPORTS double getMinVal(int depth);
 +CV_EXPORTS double getMaxVal(int depth);
 +
 +CV_EXPORTS Size randomSize(RNG& rng, double maxSizeLog);
 +CV_EXPORTS void randomSize(RNG& rng, int minDims, int maxDims, double maxSizeLog, vector<int>& sz);
 +CV_EXPORTS int randomType(RNG& rng, int typeMask, int minChannels, int maxChannels);
 +CV_EXPORTS Mat randomMat(RNG& rng, Size size, int type, double minVal, double maxVal, bool useRoi);
 +CV_EXPORTS Mat randomMat(RNG& rng, const vector<int>& size, int type, double minVal, double maxVal, bool useRoi);
 +CV_EXPORTS void add(const Mat& a, double alpha, const Mat& b, double beta,
 +                      Scalar gamma, Mat& c, int ctype, bool calcAbs=false);
 +CV_EXPORTS void multiply(const Mat& a, const Mat& b, Mat& c, double alpha=1);
 +CV_EXPORTS void divide(const Mat& a, const Mat& b, Mat& c, double alpha=1);
 +
 +CV_EXPORTS void convert(const Mat& src, cv::OutputArray dst, int dtype, double alpha=1, double beta=0);
 +CV_EXPORTS void copy(const Mat& src, Mat& dst, const Mat& mask=Mat(), bool invertMask=false);
 +CV_EXPORTS void set(Mat& dst, const Scalar& gamma, const Mat& mask=Mat());
 +
 +// working with multi-channel arrays
 +CV_EXPORTS void extract( const Mat& a, Mat& plane, int coi );
 +CV_EXPORTS void insert( const Mat& plane, Mat& a, int coi );
 +
 +// checks that the array does not have NaNs and/or Infs and all the elements are
 +// within [min_val,max_val). idx is the index of the first "bad" element.
 +CV_EXPORTS int check( const Mat& data, double min_val, double max_val, vector<int>* idx );
 +
 +// modifies values that are close to zero
 +CV_EXPORTS void  patchZeros( Mat& mat, double level );
 +
 +CV_EXPORTS void transpose(const Mat& src, Mat& dst);
 +CV_EXPORTS void erode(const Mat& src, Mat& dst, const Mat& _kernel, Point anchor=Point(-1,-1),
 +                      int borderType=0, const Scalar& borderValue=Scalar());
 +CV_EXPORTS void dilate(const Mat& src, Mat& dst, const Mat& _kernel, Point anchor=Point(-1,-1),
 +                       int borderType=0, const Scalar& borderValue=Scalar());
 +CV_EXPORTS void filter2D(const Mat& src, Mat& dst, int ddepth, const Mat& kernel,
 +                         Point anchor, double delta, int borderType,
 +                         const Scalar& borderValue=Scalar());
 +CV_EXPORTS void copyMakeBorder(const Mat& src, Mat& dst, int top, int bottom, int left, int right,
 +                               int borderType, const Scalar& borderValue=Scalar());
 +CV_EXPORTS Mat calcSobelKernel2D( int dx, int dy, int apertureSize, int origin=0 );
 +CV_EXPORTS Mat calcLaplaceKernel2D( int aperture_size );
 +
 +CV_EXPORTS void initUndistortMap( const Mat& a, const Mat& k, Size sz, Mat& mapx, Mat& mapy );
 +
 +CV_EXPORTS void minMaxLoc(const Mat& src, double* minval, double* maxval,
 +                          vector<int>* minloc, vector<int>* maxloc, const Mat& mask=Mat());
 +CV_EXPORTS double norm(const Mat& src, int normType, const Mat& mask=Mat());
 +CV_EXPORTS double norm(const Mat& src1, const Mat& src2, int normType, const Mat& mask=Mat());
 +CV_EXPORTS Scalar mean(const Mat& src, const Mat& mask=Mat());
 +
 +CV_EXPORTS bool cmpUlps(const Mat& data, const Mat& refdata, int expMaxDiff, double* realMaxDiff, vector<int>* idx);
 +
 +// compares two arrays. max_diff is the maximum actual difference,
 +// success_err_level is maximum allowed difference, idx is the index of the first
 +// element for which difference is >success_err_level
 +// (or index of element with the maximum difference)
 +CV_EXPORTS int cmpEps( const Mat& data, const Mat& refdata, double* max_diff,
 +                       double success_err_level, vector<int>* idx,
 +                       bool element_wise_relative_error );
 +
 +// a wrapper for the previous function. in case of error prints the message to log file.
 +CV_EXPORTS int cmpEps2( TS* ts, const Mat& data, const Mat& refdata, double success_err_level,
 +                        bool element_wise_relative_error, const char* desc );
 +
 +CV_EXPORTS int cmpEps2_64f( TS* ts, const double* val, const double* refval, int len,
 +                        double eps, const char* param_name );
 +
 +CV_EXPORTS void logicOp(const Mat& src1, const Mat& src2, Mat& dst, char c);
 +CV_EXPORTS void logicOp(const Mat& src, const Scalar& s, Mat& dst, char c);
 +CV_EXPORTS void min(const Mat& src1, const Mat& src2, Mat& dst);
 +CV_EXPORTS void min(const Mat& src, double s, Mat& dst);
 +CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst);
 +CV_EXPORTS void max(const Mat& src, double s, Mat& dst);
 +
 +CV_EXPORTS void compare(const Mat& src1, const Mat& src2, Mat& dst, int cmpop);
 +CV_EXPORTS void compare(const Mat& src, double s, Mat& dst, int cmpop);
 +CV_EXPORTS void gemm(const Mat& src1, const Mat& src2, double alpha,
 +                     const Mat& src3, double beta, Mat& dst, int flags);
 +    CV_EXPORTS void transform( const Mat& src, Mat& dst, const Mat& transmat, const Mat& shift );
 +CV_EXPORTS double crossCorr(const Mat& src1, const Mat& src2);
 +
 +struct CV_EXPORTS MatInfo
 +{
 +    MatInfo(const Mat& _m) : m(&_m) {}
 +    const Mat* m;
 +};
 +
 +CV_EXPORTS std::ostream& operator << (std::ostream& out, const MatInfo& m);
 +
 +struct CV_EXPORTS MatComparator
 +{
 +public:
 +    MatComparator(double maxdiff, int context);
 +
 +    ::testing::AssertionResult operator()(const char* expr1, const char* expr2,
 +                                          const Mat& m1, const Mat& m2);
 +
 +    double maxdiff;
 +    double realmaxdiff;
 +    vector<int> loc0;
 +    int context;
 +};
 +
 +
 +
 +class BaseTest;
 +class TS;
 +
 +class CV_EXPORTS BaseTest
 +{
 +public:
 +    // constructor(s) and destructor
 +    BaseTest();
 +    virtual ~BaseTest();
 +
 +    // the main procedure of the test
 +    virtual void run( int start_from );
 +
 +    // the wrapper for run that cares of exceptions
 +    virtual void safe_run( int start_from=0 );
 +
 +    const string& get_name() const { return name; }
 +
 +    // returns true if and only if the different test cases do not depend on each other
 +    // (so that test system could get right to a problematic test case)
 +    virtual bool can_do_fast_forward();
 +
 +    // deallocates all the memory.
 +    // called by init() (before initialization) and by the destructor
 +    virtual void clear();
 +
 +protected:
 +    int test_case_count; // the total number of test cases
 +
 +    // read test params
 +    virtual int read_params( CvFileStorage* fs );
 +
 +    // returns the number of tests or -1 if it is unknown a-priori
 +    virtual int get_test_case_count();
 +
 +    // prepares data for the next test case. rng seed is updated by the function
 +    virtual int prepare_test_case( int test_case_idx );
 +
 +    // checks if the test output is valid and accurate
 +    virtual int validate_test_results( int test_case_idx );
 +
 +    // calls the tested function. the method is called from run_test_case()
 +    virtual void run_func(); // runs tested func(s)
 +
 +    // updates progress bar
 +    virtual int update_progress( int progress, int test_case_idx, int count, double dt );
 +
 +    // finds test parameter
 +    const CvFileNode* find_param( CvFileStorage* fs, const char* param_name );
 +
 +    // name of the test (it is possible to locate a test by its name)
 +    string name;
 +
 +    // pointer to the system that includes the test
 +    TS* ts;
 +};
 +
 +
 +/*****************************************************************************************\
 +*                               Information about a failed test                           *
 +\*****************************************************************************************/
 +
 +struct TestInfo
 +{
 +    TestInfo();
 +
 +    // pointer to the test
 +    BaseTest* test;
 +
 +    // failure code (CV_FAIL*)
 +    int code;
 +
 +    // seed value right before the data for the failed test case is prepared.
 +    uint64 rng_seed;
 +
 +    // seed value right before running the test
 +    uint64 rng_seed0;
 +
 +    // index of test case, can be then passed to BaseTest::proceed_to_test_case()
 +    int test_case_idx;
 +};
 +
 +/*****************************************************************************************\
 +*                                 Base Class for test system                              *
 +\*****************************************************************************************/
 +
 +// common parameters:
 +struct CV_EXPORTS TSParams
 +{
 +    TSParams();
 +
 +    // RNG seed, passed to and updated by every test executed.
 +    uint64 rng_seed;
 +
 +    // whether to use IPP, MKL etc. or not
 +    bool use_optimized;
 +
 +    // extensivity of the tests, scale factor for test_case_count
 +    double test_case_count_scale;
 +};
 +
 +
 +class CV_EXPORTS TS
 +{
 +public:
 +    // constructor(s) and destructor
 +    TS();
 +    virtual ~TS();
 +
 +    enum
 +    {
 +        NUL=0,
 +        SUMMARY_IDX=0,
 +        SUMMARY=1 << SUMMARY_IDX,
 +        LOG_IDX=1,
 +        LOG=1 << LOG_IDX,
 +        CSV_IDX=2,
 +        CSV=1 << CSV_IDX,
 +        CONSOLE_IDX=3,
 +        CONSOLE=1 << CONSOLE_IDX,
 +        MAX_IDX=4
 +    };
 +
 +    static TS* ptr();
 +
 +    // initialize test system before running the first test
 +    virtual void init( const string& modulename );
 +
 +    // low-level printing functions that are used by individual tests and by the system itself
 +    virtual void printf( int streams, const char* fmt, ... );
 +    virtual void vprintf( int streams, const char* fmt, va_list arglist );
 +
 +    // updates the context: current test, test case, rng state
 +    virtual void update_context( BaseTest* test, int test_case_idx, bool update_ts_context );
 +
 +    const TestInfo* get_current_test_info() { return &current_test_info; }
 +
 +    // sets information about a failed test
 +    virtual void set_failed_test_info( int fail_code );
 +
 +    virtual void set_gtest_status();
 +
 +    // test error codes
 +    enum
 +    {
 +        // everything is Ok
 +        OK=0,
 +
 +        // generic error: stub value to be used
 +        // temporarily if the error's cause is unknown
 +        FAIL_GENERIC=-1,
 +
 +        // the test is missing some essential data to proceed further
 +        FAIL_MISSING_TEST_DATA=-2,
 +
 +        // the tested function raised an error via cxcore error handler
 +        FAIL_ERROR_IN_CALLED_FUNC=-3,
 +
 +        // an exception has been raised;
 +        // for memory and arithmetic exception
 +        // there are two specialized codes (see below...)
 +        FAIL_EXCEPTION=-4,
 +
 +        // a memory exception
 +        // (access violation, access to missed page, stack overflow etc.)
 +        FAIL_MEMORY_EXCEPTION=-5,
 +
 +        // arithmetic exception (overflow, division by zero etc.)
 +        FAIL_ARITHM_EXCEPTION=-6,
 +
 +        // the tested function corrupted memory (no exception have been raised)
 +        FAIL_MEMORY_CORRUPTION_BEGIN=-7,
 +        FAIL_MEMORY_CORRUPTION_END=-8,
 +
 +        // the tested function (or test ifself) do not deallocate some memory
 +        FAIL_MEMORY_LEAK=-9,
 +
 +        // the tested function returned invalid object, e.g. matrix, containing NaNs,
 +        // structure with NULL or out-of-range fields (while it should not)
 +        FAIL_INVALID_OUTPUT=-10,
 +
 +        // the tested function returned valid object, but it does not match to
 +        // the original (or produced by the test) object
 +        FAIL_MISMATCH=-11,
 +
 +        // the tested function returned valid object (a single number or numerical array),
 +        // but it differs too much from the original (or produced by the test) object
 +        FAIL_BAD_ACCURACY=-12,
 +
 +        // the tested function hung. Sometimes, can be determined by unexpectedly long
 +        // processing time (in this case there should be possibility to interrupt such a function
 +        FAIL_HANG=-13,
 +
 +        // unexpected responce on passing bad arguments to the tested function
 +        // (the function crashed, proceed succesfully (while it should not), or returned
 +        // error code that is different from what is expected)
 +        FAIL_BAD_ARG_CHECK=-14,
 +
 +        // the test data (in whole or for the particular test case) is invalid
 +        FAIL_INVALID_TEST_DATA=-15,
 +
 +        // the test has been skipped because it is not in the selected subset of the tests to run,
 +        // because it has been run already within the same run with the same parameters, or because
 +        // of some other reason and this is not considered as an error.
 +        // Normally TS::run() (or overrided method in the derived class) takes care of what
 +        // needs to be run, so this code should not occur.
 +        SKIPPED=1
 +    };
 +
 +    // get file storage
 +    CvFileStorage* get_file_storage();
 +
 +    // get RNG to generate random input data for a test
 +    RNG& get_rng() { return rng; }
 +
 +    // returns the current error code
 +    int get_err_code() { return current_test_info.code; }
 +
 +    // returns the test extensivity scale
 +    double get_test_case_count_scale() { return params.test_case_count_scale; }
 +
 +    const string& get_data_path() const { return data_path; }
 +
 +    // returns textual description of failure code
 +    static string str_from_code( int code );
 +
 +protected:
 +
 +    // these are allocated within a test to try keep them valid in case of stack corruption
 +    RNG rng;
 +
 +    // information about the current test
 +    TestInfo current_test_info;
 +
 +    // the path to data files used by tests
 +    string data_path;
 +
 +    TSParams params;
 +    std::string output_buf[MAX_IDX];
 +};
 +
 +
 +/*****************************************************************************************\
 +*            Subclass of BaseTest for testing functions that process dense arrays           *
 +\*****************************************************************************************/
 +
 +class CV_EXPORTS ArrayTest : public BaseTest
 +{
 +public:
 +    // constructor(s) and destructor
 +    ArrayTest();
 +    virtual ~ArrayTest();
 +
 +    virtual void clear();
 +
 +protected:
 +
 +    virtual int read_params( CvFileStorage* fs );
 +    virtual int prepare_test_case( int test_case_idx );
 +    virtual int validate_test_results( int test_case_idx );
 +
 +    virtual void prepare_to_validation( int test_case_idx );
 +    virtual void get_test_array_types_and_sizes( int test_case_idx, vector<vector<Size> >& sizes, vector<vector<int> >& types );
 +    virtual void fill_array( int test_case_idx, int i, int j, Mat& arr );
 +    virtual void get_minmax_bounds( int i, int j, int type, Scalar& low, Scalar& high );
 +    virtual double get_success_error_level( int test_case_idx, int i, int j );
 +
 +    bool cvmat_allowed;
 +    bool iplimage_allowed;
 +    bool optional_mask;
 +    bool element_wise_relative_error;
 +
 +    int min_log_array_size;
 +    int max_log_array_size;
 +
 +    enum { INPUT, INPUT_OUTPUT, OUTPUT, REF_INPUT_OUTPUT, REF_OUTPUT, TEMP, MASK, MAX_ARR };
 +
 +    vector<vector<void*> > test_array;
 +    vector<vector<Mat> > test_mat;
 +    float buf[4];
 +};
 +
 +
 +class CV_EXPORTS BadArgTest : public BaseTest
 +{
 +public:
 +    // constructor(s) and destructor
 +    BadArgTest();
 +    virtual ~BadArgTest();
 +
 +protected:
 +    virtual int run_test_case( int expected_code, const string& descr );
 +    virtual void run_func(void) = 0;
 +    int test_case_idx;
 +
 +    template<class F>
 +    int run_test_case( int expected_code, const string& _descr, F f)
 +    {
 +        int errcount = 0;
 +        bool thrown = false;
 +        const char* descr = _descr.c_str() ? _descr.c_str() : "";
 +
 +        try
 +        {
 +            f();
 +        }
 +        catch(const cv::Exception& e)
 +        {
 +            thrown = true;
 +            if( e.code != expected_code )
 +            {
 +                ts->printf(TS::LOG, "%s (test case #%d): the error code %d is different from the expected %d\n",
 +                    descr, test_case_idx, e.code, expected_code);
 +                errcount = 1;
 +            }
 +        }
 +        catch(...)
 +        {
 +            thrown = true;
 +            ts->printf(TS::LOG, "%s  (test case #%d): unknown exception was thrown (the function has likely crashed)\n",
 +                       descr, test_case_idx);
 +            errcount = 1;
 +        }
 +        if(!thrown)
 +        {
 +            ts->printf(TS::LOG, "%s  (test case #%d): no expected exception was thrown\n",
 +                       descr, test_case_idx);
 +            errcount = 1;
 +        }
 +        test_case_idx++;
 +
 +        return errcount;
 +    }
 +};
 +
 +struct CV_EXPORTS DefaultRngAuto
 +{
 +    const uint64 old_state;
 +
 +    DefaultRngAuto() : old_state(cv::theRNG().state) { cv::theRNG().state = (uint64)-1; }
 +    ~DefaultRngAuto() { cv::theRNG().state = old_state; }
 +
 +    DefaultRngAuto& operator=(const DefaultRngAuto&);
 +};
 +
 +}
 +
 +namespace cvtest
 +{
 +
 +// test images generation functions
 +CV_EXPORTS void fillGradient(Mat& img, int delta = 5);
 +CV_EXPORTS void smoothBorder(Mat& img, const Scalar& color, int delta = 3);
 +
 +CV_EXPORTS void printVersionInfo(bool useStdOut = true);
 +} //namespace cvtest
 +
 +#define CV_TEST_MAIN(resourcesubdir) \
 +int main(int argc, char **argv) \
 +{ \
 +    cvtest::TS::ptr()->init(resourcesubdir); \
 +    ::testing::InitGoogleTest(&argc, argv); \
 +    cvtest::printVersionInfo();\
 +    return RUN_ALL_TESTS(); \
 +}
 +
 +// This usually only makes sense in perf tests with several implementations,
 +// some of which are not available.
 +#define CV_TEST_FAIL_NO_IMPL() do { \
 +    ::testing::Test::RecordProperty("custom_status", "noimpl"); \
 +    FAIL() << "No equivalent implementation."; \
 +} while (0)
 +
 +#endif
 +
 +#include "opencv2/ts/ts_perf.hpp"
@@@ -1,17 -1,15 +1,9 @@@
  #ifndef __OPENCV_TS_PERF_HPP__
  #define __OPENCV_TS_PERF_HPP__
  
- #include "cvconfig.h"
- #ifndef GTEST_CREATE_SHARED_LIBRARY
- #  ifdef BUILD_SHARED_LIBS
- #    define GTEST_LINKED_AS_SHARED_LIBRARY 1
- #  endif
- #endif
 -#include "opencv2/core/core.hpp"
 -#include "opencv2/imgproc/imgproc.hpp"
 -#include "opencv2/features2d/features2d.hpp"
 +#include "opencv2/core.hpp"
  #include "ts_gtest.h"
  
 -#ifdef HAVE_TBB
 -#include "tbb/task_scheduler_init.h"
 -#endif
 -
  #if !(defined(LOGD) || defined(LOGI) || defined(LOGW) || defined(LOGE))
  # if defined(ANDROID) && defined(USE_ANDROID_LOGGING)
  #  include <android/log.h>
@@@ -1,23 -1,27 +1,27 @@@
  # make target;        arch; API level; Android Source Code Root
 -native_camera_r2.2.0; armeabi;     8;  /home/alexander/Projects/AndroidSource/2.2.2
 -native_camera_r2.2.0; armeabi-v7a; 8;  /home/alexander/Projects/AndroidSource/2.2.2
 -native_camera_r2.3.3; armeabi;     9;  /home/alexander/Projects/AndroidSource/2.3.3
 -native_camera_r2.3.3; armeabi-v7a; 9;  /home/alexander/Projects/AndroidSource/2.3.3
 -native_camera_r2.3.3; x86;         9;  /home/alexander/Projects/AndroidSource/2.3.3
 -native_camera_r3.0.1; armeabi;     9;  /home/alexander/Projects/AndroidSource/3.0.1
 -native_camera_r3.0.1; armeabi-v7a; 9;  /home/alexander/Projects/AndroidSource/3.0.1
 -native_camera_r3.0.1; x86;         9;  /home/alexander/Projects/AndroidSource/3.0.1
 -native_camera_r4.0.3; armeabi;     14; /home/alexander/Projects/AndroidSource/4.0.3
 -native_camera_r4.0.3; armeabi-v7a; 14; /home/alexander/Projects/AndroidSource/4.0.3
 -native_camera_r4.0.3; x86;         14; /home/alexander/Projects/AndroidSource/4.0.3
 -native_camera_r4.0.3; mips;        14; /home/alexander/Projects/AndroidSource/4.0.3_mips
 -native_camera_r4.0.0; armeabi;     14; /home/alexander/Projects/AndroidSource/4.0.0
 -native_camera_r4.0.0; armeabi-v7a; 14; /home/alexander/Projects/AndroidSource/4.0.0
 -native_camera_r4.1.1; armeabi;     14; /home/alexander/Projects/AndroidSource/4.1.1
 -native_camera_r4.1.1; armeabi-v7a; 14; /home/alexander/Projects/AndroidSource/4.1.1
 -native_camera_r4.1.1; x86;         14; /home/alexander/Projects/AndroidSource/4.1.1
 -native_camera_r4.1.1; mips;        14; /home/alexander/Projects/AndroidSource/4.1.1_mips
 -native_camera_r4.2.0; armeabi-v7a; 14; /home/alexander/Projects/AndroidSource/4.2
 -native_camera_r4.2.0; armeabi;     14; /home/alexander/Projects/AndroidSource/4.2
 -native_camera_r4.2.0; x86;         14; /home/alexander/Projects/AndroidSource/4.2
 -native_camera_r4.2.0; mips;        14; /home/alexander/Projects/AndroidSource/4.2
 -native_camera_r4.3.0; armeabi;     14; /home/alexander/Projects/AndroidSource/4.3
 -native_camera_r4.3.0; armeabi-v7a; 14; /home/alexander/Projects/AndroidSource/4.3
 -native_camera_r4.3.0; x86;         14; /home/alexander/Projects/AndroidSource/4.3
 -native_camera_r4.3.0; mips;        14; /home/alexander/Projects/AndroidSource/4.3
 +native_camera_r2.2.0; armeabi;     8;  $ANDROID_STUB_ROOT/2.2.2
 +native_camera_r2.2.0; armeabi-v7a; 8;  $ANDROID_STUB_ROOT/2.2.2
 +native_camera_r2.3.3; armeabi;     9;  $ANDROID_STUB_ROOT/2.3.3
 +native_camera_r2.3.3; armeabi-v7a; 9;  $ANDROID_STUB_ROOT/2.3.3
 +native_camera_r2.3.3; x86;         9;  $ANDROID_STUB_ROOT/2.3.3
 +native_camera_r3.0.1; armeabi;     9;  $ANDROID_STUB_ROOT/3.0.1
 +native_camera_r3.0.1; armeabi-v7a; 9;  $ANDROID_STUB_ROOT/3.0.1
 +native_camera_r3.0.1; x86;         9;  $ANDROID_STUB_ROOT/3.0.1
 +native_camera_r4.0.3; armeabi;     14; $ANDROID_STUB_ROOT/4.0.3
 +native_camera_r4.0.3; armeabi-v7a; 14; $ANDROID_STUB_ROOT/4.0.3
 +native_camera_r4.0.3; x86;         14; $ANDROID_STUB_ROOT/4.0.3
 +native_camera_r4.0.3; mips;        14; $ANDROID_STUB_ROOT/4.0.3_mips
 +native_camera_r4.0.0; armeabi;     14; $ANDROID_STUB_ROOT/4.0.0
 +native_camera_r4.0.0; armeabi-v7a; 14; $ANDROID_STUB_ROOT/4.0.0
 +native_camera_r4.1.1; armeabi;     14; $ANDROID_STUB_ROOT/4.1.1
 +native_camera_r4.1.1; armeabi-v7a; 14; $ANDROID_STUB_ROOT/4.1.1
 +native_camera_r4.1.1; x86;         14; $ANDROID_STUB_ROOT/4.1.1
 +native_camera_r4.1.1; mips;        14; $ANDROID_STUB_ROOT/4.1.1
 +native_camera_r4.2.0; armeabi-v7a; 14; $ANDROID_STUB_ROOT/4.2.0
 +native_camera_r4.2.0; armeabi;     14; $ANDROID_STUB_ROOT/4.2.0
 +native_camera_r4.2.0; x86;         14; $ANDROID_STUB_ROOT/4.2.0
 +native_camera_r4.2.0; mips;        14; $ANDROID_STUB_ROOT/4.2.0
++native_camera_r4.3.0; armeabi;     14; $ANDROID_STUB_ROOT/4.3.0
++native_camera_r4.3.0; armeabi-v7a; 14; $ANDROID_STUB_ROOT/4.3.0
++native_camera_r4.3.0; x86;         14; $ANDROID_STUB_ROOT/4.3.0
++native_camera_r4.3.0; mips;        14; $ANDROID_STUB_ROOT/4.3.0