Merge remote-tracking branch 'origin/2.4'
authorRoman Donchenko <roman.donchenko@itseez.com>
Tue, 1 Oct 2013 11:57:33 +0000 (15:57 +0400)
committerRoman Donchenko <roman.donchenko@itseez.com>
Tue, 1 Oct 2013 11:57:33 +0000 (15:57 +0400)
Conflicts:
doc/tutorials/features2d/feature_detection/feature_detection.rst
modules/bioinspired/doc/retina/index.rst
modules/core/include/opencv2/core/core.hpp
modules/core/include/opencv2/core/mat.hpp
modules/core/include/opencv2/core/operations.hpp
modules/core/src/stat.cpp
modules/features2d/include/opencv2/features2d/features2d.hpp
modules/imgproc/src/filter.cpp
modules/legacy/src/dpstereo.cpp
modules/nonfree/src/surf.ocl.cpp
modules/ocl/doc/image_processing.rst
modules/ocl/doc/object_detection.rst
modules/ocl/include/opencv2/ocl/ocl.hpp
modules/ocl/include/opencv2/ocl/private/util.hpp
modules/ocl/src/arithm.cpp
modules/ocl/src/canny.cpp
modules/ocl/src/filtering.cpp
modules/ocl/src/imgproc.cpp
modules/ocl/src/initialization.cpp
modules/ocl/src/matrix_operations.cpp
modules/ocl/src/pyrdown.cpp
modules/ocl/src/pyrup.cpp
modules/ocl/src/split_merge.cpp
modules/ocl/test/test_objdetect.cpp
modules/ocl/test/utility.hpp

50 files changed:
1  2 
3rdparty/tbb/CMakeLists.txt
cmake/OpenCVModule.cmake
cmake/OpenCVPCHSupport.cmake
cmake/templates/cvconfig.h.cmake
doc/tutorials/bioinspired/retina_model/retina_model.rst~
doc/tutorials/features2d/feature_detection/feature_detection.rst
modules/bioinspired/doc/retina/index.rst
modules/core/include/opencv2/core/core_c.h
modules/core/include/opencv2/core/mat.inl.hpp
modules/core/include/opencv2/core/persistence.hpp
modules/core/include/opencv2/core/types_c.h
modules/core/include/opencv2/core/utility.hpp
modules/core/src/stat.cpp
modules/flann/include/opencv2/flann/lsh_table.h
modules/highgui/src/cap_qtkit.mm
modules/imgproc/src/filter.cpp
modules/imgproc/src/imgwarp.cpp
modules/java/CMakeLists.txt
modules/nonfree/src/surf.ocl.cpp
modules/ocl/doc/image_filtering.rst
modules/ocl/doc/image_processing.rst
modules/ocl/doc/object_detection.rst
modules/ocl/include/opencv2/ocl.hpp
modules/ocl/include/opencv2/ocl/private/util.hpp
modules/ocl/perf/perf_bgfg.cpp
modules/ocl/src/arithm.cpp
modules/ocl/src/canny.cpp
modules/ocl/src/filtering.cpp
modules/ocl/src/hog.cpp
modules/ocl/src/imgproc.cpp
modules/ocl/src/initialization.cpp
modules/ocl/src/knearest.cpp
modules/ocl/src/matrix_operations.cpp
modules/ocl/src/mcwutil.cpp
modules/ocl/src/optical_flow_farneback.cpp
modules/ocl/src/pyrdown.cpp
modules/ocl/src/pyrup.cpp
modules/ocl/src/split_merge.cpp
modules/ocl/src/stereo_csbp.cpp
modules/ocl/src/stereobm.cpp
modules/ocl/src/stereobp.cpp
modules/ocl/src/svm.cpp
modules/ocl/src/tvl1flow.cpp
modules/ocl/test/test_bgfg.cpp
modules/ocl/test/test_imgproc.cpp
modules/ocl/test/test_precomp.hpp
modules/ocl/test/utility.hpp
samples/cpp/OpenEXRimages_HDR_Retina_toneMapping.cpp
samples/cpp/OpenEXRimages_HDR_Retina_toneMapping_video.cpp
samples/cpp/latentsvm_multidetect.cpp

Simple merge
Simple merge
Simple merge
Simple merge
index 50bdcbb,0000000..855be9c
mode 100644,000000..100644
--- /dev/null
@@@ -1,418 -1,0 +1,418 @@@
- *Note :* image sample can be downloaded from the `OpenEXR website <http://www.openexr.com>`_. Regarding this demonstration, before retina processing, input image has been linearly rescaled within 0-255 keeping its channels float format. 5% of its histogram ends has been cut (mostly removes wrong HDR pixels). Check out the sample *opencv/samples/cpp/OpenEXRimages_HighDynamicRange_Retina_toneMapping.cpp* for similar processing. The following demonstration will only consider classical 8bit/channel images.
 +.. _Retina_Model:
 +
 +Discovering the human retina and its use for image processing
 +*************************************************************
 +
 +Goal
 +=====
 +
 +I present here a model of human retina that shows some interesting properties for image preprocessing and enhancement.
 +In this tutorial you will learn how to:
 +
 +.. container:: enumeratevisibleitemswithsquare
 +
 +   + discover the main two channels outing from your retina
 +
 +   + see the basics to use the retina model
 +
 +   + discover some parameters tweaks
 +
 +
 +General overview
 +================
 +
 +The proposed model originates from Jeanny Herault's research [herault2010]_ at `Gipsa <http://www.gipsa-lab.inpg.fr>`_. It is involved in image processing applications with `Listic <http://www.listic.univ-savoie.fr>`_ (code maintainer and user) lab. This is not a complete model but it already present interesting properties that can be involved for enhanced image processing experience. The model allows the following human retina properties to be used :
 +
 +* spectral whitening that has 3 important effects: high spatio-temporal frequency signals canceling (noise), mid-frequencies details enhancement and low frequencies luminance energy reduction. This *all in one* property directly allows visual signals cleaning of classical undesired distortions introduced by image sensors and input luminance range.
 +
 +* local logarithmic luminance compression allows details to be enhanced even in low light conditions.
 +
 +* decorrelation of the details information (Parvocellular output channel) and transient information (events, motion made available at the Magnocellular output channel).
 +
 +The first two points are illustrated below :
 +
 +In the figure below, the OpenEXR image sample *CrissyField.exr*, a High Dynamic Range image is shown. In order to make it visible on this web-page, the original input image is linearly rescaled to the classical image luminance range [0-255] and is converted to 8bit/channel format. Such strong conversion hides many details because of too strong local contrasts. Furthermore, noise energy is also strong and pollutes visual information.
 +
 +.. image:: images/retina_TreeHdr_small.jpg
 +   :alt: A High dynamic range image linearly rescaled within range [0-255].
 +   :align: center
 +
 +In the following image, applying the ideas proposed in [benoit2010]_, as your retina does, local luminance adaptation, spatial noise removal and spectral whitening work together and transmit accurate information on lower range 8bit data channels. On this picture, noise in significantly removed, local details hidden by strong luminance contrasts are enhanced. Output image keeps its naturalness and visual content is enhanced. Color processing is based on the color multiplexing/demultiplexing method proposed in [chaix2007]_.
 +
 +.. image:: images/retina_TreeHdr_retina.jpg
 +   :alt: A High dynamic range image compressed within range [0-255] using the retina.
 +   :align: center
 +
 +
++*Note :* image sample can be downloaded from the `OpenEXR website <http://www.openexr.com>`_. Regarding this demonstration, before retina processing, input image has been linearly rescaled within 0-255 keeping its channels float format. 5% of its histogram ends has been cut (mostly removes wrong HDR pixels). Check out the sample *opencv/samples/cpp/OpenEXRimages_HDR_Retina_toneMapping.cpp* for similar processing. The following demonstration will only consider classical 8bit/channel images.
 +
 +The retina model output channels
 +================================
 +
 +The retina model presents two outputs that benefit from the above cited behaviors.
 +
 +* The first one is called the Parvocellular channel. It is mainly active in the foveal retina area (high resolution central vision with color sensitive photo-receptors), its aim is to provide accurate color vision for visual details remaining static on the retina. On the other hand objects moving on the retina projection are blurred.
 +
 +* The second well known channel is the Magnocellular channel. It is mainly active in the retina peripheral vision and send signals related to change events (motion, transient events, etc.). These outing signals also help visual system to focus/center retina on 'transient'/moving areas for more detailed analysis thus improving visual scene context and object classification.
 +
 +**NOTE :** regarding the proposed model, contrary to the real retina, we apply these two channels on the entire input images using the same resolution. This allows enhanced visual details and motion information to be extracted on all the considered images... but remember, that these two channels are complementary. For example, if Magnocellular channel gives strong energy in an area, then, the Parvocellular channel is certainly blurred there since there is a transient event.
 +
 +As an illustration, we apply in the following the retina model on a webcam video stream of a dark visual scene. In this visual scene, captured in an amphitheater of the university, some students are moving while talking to the teacher.
 +
 +In this video sequence, because of the dark ambiance, signal to noise ratio is low and color artifacts are present on visual features edges because of the low quality image capture tool-chain.
 +
 +.. image:: images/studentsSample_input.jpg
 +   :alt: an input video stream extract sample
 +   :align: center
 +
 +Below is shown the retina foveal vision applied on the entire image. In the used retina configuration, global luminance is preserved and local contrasts are enhanced. Also, signal to noise ratio is improved : since high frequency spatio-temporal noise is reduced, enhanced details are not corrupted by any enhanced noise.
 +
 +.. image:: images/studentsSample_parvo.jpg
 +   :alt: the retina Parvocellular output. Enhanced details, luminance adaptation and noise removal. A processing tool for image analysis.
 +   :align: center
 +
 +Below is the output of the Magnocellular output of the retina model. Its signals are strong where transient events occur. Here, a student is moving at the bottom of the image thus generating high energy. The remaining of the image is static however, it is corrupted by a strong noise. Here, the retina filters out most of the noise thus generating low false motion area 'alarms'. This channel can be used as a transient/moving areas detector : it would provide relevant information for a low cost segmentation tool that would highlight areas in which an event is occurring.
 +
 +.. image:: images/studentsSample_magno.jpg
 +   :alt: the retina Magnocellular output. Enhanced transient signals (motion, etc.). A preprocessing tool for event detection.
 +   :align: center
 +
 +Retina use case
 +===============
 +
 +This model can be used basically for spatio-temporal video effects but also in the aim of :
 +
 +* performing texture analysis with enhanced signal to noise ratio and enhanced details robust against input images luminance ranges (check out the Parvocellular retina channel output)
 +
 +* performing motion analysis also taking benefit of the previously cited properties.
 +
 +Literature
 +==========
 +For more information, refer to the following papers :
 +
 +.. [benoit2010] Benoit A., Caplier A., Durette B., Herault, J., "Using Human Visual System Modeling For Bio-Inspired Low Level Image Processing", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773. DOI <http://dx.doi.org/10.1016/j.cviu.2010.01.011>
 +
 +* Please have a look at the reference work of Jeanny Herault that you can read in his book :
 +
 +.. [herault2010] Vision: Images, Signals and Neural Networks: Models of Neural Processing in Visual Perception (Progress in Neural Processing),By: Jeanny Herault, ISBN: 9814273686. WAPI (Tower ID): 113266891.
 +
 +This retina filter code includes the research contributions of phd/research collegues from which code has been redrawn by the author :
 +
 +* take a look at the *retinacolor.hpp* module to discover Brice Chaix de Lavarene phD color mosaicing/demosaicing and his reference paper:
 +
 +.. [chaix2007] B. Chaix de Lavarene, D. Alleysson, B. Durette, J. Herault (2007). "Efficient demosaicing through recursive filtering", IEEE International Conference on Image Processing ICIP 2007
 +
 +* take a look at *imagelogpolprojection.hpp* to discover retina spatial log sampling which originates from Barthelemy Durette phd with Jeanny Herault. A Retina / V1 cortex projection is also proposed and originates from Jeanny's discussions. More informations in the above cited Jeanny Heraults's book.
 +
 +Code tutorial
 +=============
 +
 +Please refer to the original tutorial source code in file *opencv_folder/samples/cpp/tutorial_code/bioinspired/retina_tutorial.cpp*.
 +
 +**Note :** do not forget that the retina model is included in the following namespace : *cv::bioinspired*.
 +
 +To compile it, assuming OpenCV is correctly installed, use the following command. It requires the opencv_core *(cv::Mat and friends objects management)*, opencv_highgui *(display and image/video read)* and opencv_bioinspired *(Retina description)* libraries to compile.
 +
 +.. code-block:: cpp
 +
 +   // compile
 +   gcc retina_tutorial.cpp -o Retina_tuto -lopencv_core -lopencv_highgui -lopencv_bioinspired
 +
 +   // Run commands : add 'log' as a last parameter to apply a spatial log sampling (simulates retina sampling)
 +   // run on webcam
 +   ./Retina_tuto -video
 +   // run on video file
 +   ./Retina_tuto -video myVideo.avi
 +   // run on an image
 +   ./Retina_tuto -image myPicture.jpg
 +   // run on an image with log sampling
 +   ./Retina_tuto -image myPicture.jpg log
 +
 +Here is a code explanation :
 +
 +Retina definition is present in the bioinspired package and a simple include allows to use it. You can rather use the specific header : *opencv2/bioinspired.hpp* if you prefer but then include the other required openv modules : *opencv2/core.hpp* and *opencv2/highgui.hpp* 
 +
 +.. code-block:: cpp
 +
 +   #include "opencv2/opencv.hpp"
 +
 +Provide user some hints to run the program with a help function
 +
 +.. code-block:: cpp
 +
 +   // the help procedure
 +   static void help(std::string errorMessage)
 +   {
 +    std::cout<<"Program init error : "<<errorMessage<<std::endl;
 +    std::cout<<"\nProgram call procedure : retinaDemo [processing mode] [Optional : media target] [Optional LAST parameter: \"log\" to activate retina log sampling]"<<std::endl;
 +    std::cout<<"\t[processing mode] :"<<std::endl;
 +    std::cout<<"\t -image : for still image processing"<<std::endl;
 +    std::cout<<"\t -video : for video stream processing"<<std::endl;
 +    std::cout<<"\t[Optional : media target] :"<<std::endl;
 +    std::cout<<"\t if processing an image or video file, then, specify the path and filename of the target to process"<<std::endl;
 +    std::cout<<"\t leave empty if processing video stream coming from a connected video device"<<std::endl;
 +    std::cout<<"\t[Optional : activate retina log sampling] : an optional last parameter can be specified for retina spatial log sampling"<<std::endl;
 +    std::cout<<"\t set \"log\" without quotes to activate this sampling, output frame size will be divided by 4"<<std::endl;
 +    std::cout<<"\nExamples:"<<std::endl;
 +    std::cout<<"\t-Image processing : ./retinaDemo -image lena.jpg"<<std::endl;
 +    std::cout<<"\t-Image processing with log sampling : ./retinaDemo -image lena.jpg log"<<std::endl;
 +    std::cout<<"\t-Video processing : ./retinaDemo -video myMovie.mp4"<<std::endl;
 +    std::cout<<"\t-Live video processing : ./retinaDemo -video"<<std::endl;
 +    std::cout<<"\nPlease start again with new parameters"<<std::endl;
 +    std::cout<<"****************************************************"<<std::endl;
 +    std::cout<<" NOTE : this program generates the default retina parameters file 'RetinaDefaultParameters.xml'"<<std::endl;
 +    std::cout<<" => you can use this to fine tune parameters and load them if you save to file 'RetinaSpecificParameters.xml'"<<std::endl;
 +   }
 +
 +Then, start the main program and first declare a *cv::Mat* matrix in which input images will be loaded. Also allocate a *cv::VideoCapture* object ready to load video streams (if necessary)
 +
 +.. code-block:: cpp
 +
 +  int main(int argc, char* argv[]) {
 +    // declare the retina input buffer... that will be fed differently in regard of the input media
 +    cv::Mat inputFrame;
 +    cv::VideoCapture videoCapture; // in case a video media is used, its manager is declared here
 +
 +
 +In the main program, before processing, first check input command parameters. Here it loads a first input image coming from a single loaded image (if user chose command *-image*) or from a video stream (if user chose command *-video*). Also, if the user added *log* command at the end of its program call, the spatial logarithmic image sampling performed by the retina is taken into account by the Boolean flag *useLogSampling*.
 +
 +.. code-block:: cpp
 +
 +  // welcome message
 +    std::cout<<"****************************************************"<<std::endl;
 +    std::cout<<"* Retina demonstration : demonstrates the use of is a wrapper class of the Gipsa/Listic Labs retina model."<<std::endl;
 +    std::cout<<"* This demo will try to load the file 'RetinaSpecificParameters.xml' (if exists).\nTo create it, copy the autogenerated template 'RetinaDefaultParameters.xml'.\nThen twaek it with your own retina parameters."<<std::endl;
 +    // basic input arguments checking
 +    if (argc<2)
 +    {
 +        help("bad number of parameter");
 +        return -1;
 +    }
 +
 +    bool useLogSampling = !strcmp(argv[argc-1], "log"); // check if user wants retina log sampling processing
 +
 +    std::string inputMediaType=argv[1];
 +
 +    //////////////////////////////////////////////////////////////////////////////
 +    // checking input media type (still image, video file, live video acquisition)
 +    if (!strcmp(inputMediaType.c_str(), "-image") && argc >= 3)
 +    {
 +        std::cout<<"RetinaDemo: processing image "<<argv[2]<<std::endl;
 +        // image processing case
 +        inputFrame = cv::imread(std::string(argv[2]), 1); // load image in RGB mode
 +    }else
 +        if (!strcmp(inputMediaType.c_str(), "-video"))
 +        {
 +            if (argc == 2 || (argc == 3 && useLogSampling)) // attempt to grab images from a video capture device
 +            {
 +                videoCapture.open(0);
 +            }else// attempt to grab images from a video filestream
 +            {
 +                std::cout<<"RetinaDemo: processing video stream "<<argv[2]<<std::endl;
 +                videoCapture.open(argv[2]);
 +            }
 +
 +            // grab a first frame to check if everything is ok
 +            videoCapture>>inputFrame;
 +        }else
 +        {
 +            // bad command parameter
 +            help("bad command parameter");
 +            return -1;
 +        }
 +
 +Once all input parameters are processed, a first image should have been loaded, if not, display error and stop program :
 +
 +.. code-block:: cpp
 +
 +    if (inputFrame.empty())
 +    {
 +        help("Input media could not be loaded, aborting");
 +        return -1;
 +    }
 +
 +Now, everything is ready to run the retina model. I propose here to allocate a retina instance and to manage the eventual log sampling option. The Retina constructor expects at least a cv::Size object that shows the input data size that will have to be managed. One can activate other options such as color and its related color multiplexing strategy (here Bayer multiplexing is chosen using *enum cv::bioinspired::RETINA_COLOR_BAYER*). If using log sampling, the image reduction factor (smaller output images) and log sampling strengh can be adjusted.
 +
 +.. code-block:: cpp
 +
 +    // pointer to a retina object
 +    cv::Ptr<Retina> myRetina;
 +
 +    // if the last parameter is 'log', then activate log sampling (favour foveal vision and subsamples peripheral vision)
 +    if (useLogSampling)
 +    {
 +        myRetina = cv::bioinspired::createRetina(inputFrame.size(), true, cv::bioinspired::RETINA_COLOR_BAYER, true, 2.0, 10.0);
 +    }
 +    else// -> else allocate "classical" retina :
 +        myRetina = cv::bioinspired::createRetina(inputFrame.size());
 +
 +Once done, the proposed code writes a default xml file that contains the default parameters of the retina. This is useful to make your own config using this template. Here generated template xml file is called *RetinaDefaultParameters.xml*.
 +
 +.. code-block:: cpp
 +
 +    // save default retina parameters file in order to let you see this and maybe modify it and reload using method "setup"
 +    myRetina->write("RetinaDefaultParameters.xml");
 +
 +In the following line, the retina attempts to load another xml file called *RetinaSpecificParameters.xml*. If you created it and introduced your own setup, it will be loaded, in the other case, default retina parameters are used.
 +
 +.. code-block:: cpp
 +
 +    // load parameters if file exists
 +    myRetina->setup("RetinaSpecificParameters.xml");
 +
 +It is not required here but just to show it is possible, you can reset the retina buffers to zero to force it to forget past events.
 +
 +.. code-block:: cpp
 +
 +    // reset all retina buffers (imagine you close your eyes for a long time)
 +    myRetina->clearBuffers();
 +
 +Now, it is time to run the retina ! First create some output buffers ready to receive the two retina channels outputs
 +
 +.. code-block:: cpp
 +
 +    // declare retina output buffers
 +    cv::Mat retinaOutput_parvo;
 +    cv::Mat retinaOutput_magno;
 +
 +Then, run retina in a loop, load new frames from video sequence if necessary and get retina outputs back to dedicated buffers.
 +
 +.. code-block:: cpp
 +
 +    // processing loop with no stop condition
 +    while(true)
 +    {
 +        // if using video stream, then, grabbing a new frame, else, input remains the same
 +        if (videoCapture.isOpened())
 +            videoCapture>>inputFrame;
 +
 +        // run retina filter on the loaded input frame
 +        myRetina->run(inputFrame);
 +        // Retrieve and display retina output
 +        myRetina->getParvo(retinaOutput_parvo);
 +        myRetina->getMagno(retinaOutput_magno);
 +        cv::imshow("retina input", inputFrame);
 +        cv::imshow("Retina Parvo", retinaOutput_parvo);
 +        cv::imshow("Retina Magno", retinaOutput_magno);
 +        cv::waitKey(10);
 +    }
 +
 +That's done ! But if you want to secure the system, take care and manage Exceptions. The retina can throw some when it sees irrelevant data (no input frame, wrong setup, etc.).
 +Then, i recommend to surround all the retina code by a try/catch system like this :
 +
 +.. code-block:: cpp
 +
 +    try{
 +         // pointer to a retina object
 +         cv::Ptr<cv::Retina> myRetina;
 +         [---]
 +         // processing loop with no stop condition
 +         while(true)
 +         {
 +             [---]
 +         }
 +
 +    }catch(cv::Exception e)
 +    {
 +        std::cerr<<"Error using Retina : "<<e.what()<<std::endl;
 +    }
 +
 +Retina parameters, what to do ?
 +===============================
 +
 +First, it is recommended to read the reference paper :
 +
 +* 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>
 +
 +Once done open the configuration file *RetinaDefaultParameters.xml* generated by the demo and let's have a look at it.
 +
 +.. 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.7e-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 are some hints but actually, the best parameter setup depends more on what you want to do with the retina rather than the images input that you give to retina. Apart from the more specific case of High Dynamic Range images (HDR) that require more specific setup for specific luminance compression objective, the retina behaviors should be rather stable from content to content. Note that OpenCV is able to manage such HDR format thanks to the OpenEXR images compatibility.
 +
 +Then, if the application target requires details enhancement prior to specific image processing, you need to know if mean luminance information is required or not. If not, the the retina can cancel or significantly reduce its energy thus giving more visibility to higher spatial frequency details.
 +
 +
 +Basic parameters
 +----------------
 +
 +The most simple parameters are the following :
 +
 +* **colorMode** : let the retina process color information (if 1) or gray scale images (if 0). In this last case, only the first channel of the input will be processed.
 +
 +* **normaliseOutput** : each channel has this parameter, if value is 1, then the considered channel output is rescaled between 0 and 255. Take care in this case at the Magnocellular output level (motion/transient channel detection). Residual noise will also be rescaled !
 +
 +**Note :** using color requires color channels multiplexing/demultipexing which requires more processing. You can expect much faster processing using gray levels : it would require around 30 product per pixel for all the retina processes and it has recently been parallelized for multicore architectures.
 +
 +Photo-receptors parameters
 +--------------------------
 +
 +The following parameters act on the entry point of the retina - photo-receptors - and impact all the following processes. These sensors are low pass spatio-temporal filters that smooth temporal and spatial data and also adjust there sensitivity to local luminance thus improving details extraction and high frequency noise canceling.
 +
 +* **photoreceptorsLocalAdaptationSensitivity** between 0 and 1. Values close to 1 allow high luminance log compression effect at the photo-receptors level. Values closer to 0 give a more linear sensitivity. Increased alone, it can burn the *Parvo (details channel)* output image. If adjusted in collaboration with **ganglionCellsSensitivity** images can be very contrasted whatever the local luminance there is... at the price of a naturalness decrease.
 +
 +* **photoreceptorsTemporalConstant** this setups the temporal constant of the low pass filter effect at the entry of the retina. High value lead to strong temporal smoothing effect : moving objects are blurred and can disappear while static object are favored. But when starting the retina processing, stable state is reached lately.
 +
 +* **photoreceptorsSpatialConstant** specifies the spatial constant related to photo-receptors low pass filter effect. This parameters specify the minimum allowed spatial signal period allowed in the following. Typically, this filter should cut high frequency noise. Then a 0 value doesn't cut anything noise while higher values start to cut high spatial frequencies and more and more lower frequencies... Then, do not go to high if you wanna see some details of the input images ! A good compromise for color images is 0.53 since this won't affect too much the color spectrum. Higher values would lead to gray and blurred output images.
 +
 +Horizontal cells parameters
 +---------------------------
 +
 +This parameter set tunes the neural network connected to the photo-receptors, the horizontal cells. It modulates photo-receptors sensitivity and completes the processing for final spectral whitening (part of the spatial band pass effect thus favoring visual details enhancement).
 +
 +* **horizontalCellsGain** here is a critical parameter ! If you are not interested by the mean luminance and focus on details enhancement, then, set to zero. But if you want to keep some environment luminance data, let some low spatial frequencies pass into the system and set a higher value (<1).
 +
 +* **hcellsTemporalConstant** similar to photo-receptors, this acts on the temporal constant of a low pass temporal filter that smooths input data. Here, a high value generates a high retina after effect while a lower value makes the retina more reactive. This value should be lower than **photoreceptorsTemporalConstant** to limit strong retina after effects.
 +
 +* **hcellsSpatialConstant** is the spatial constant of the low pass filter of these cells filter. It specifies the lowest spatial frequency allowed in the following. Visually, a high value leads to very low spatial frequencies processing and leads to salient halo effects. Lower values reduce this effect but the limit is : do not go lower than the value of **photoreceptorsSpatialConstant**. Those 2 parameters actually specify the spatial band-pass of the retina.
 +
 +**NOTE** after the processing managed by the previous parameters, input data is cleaned from noise and luminance in already partly enhanced. The following parameters act on the last processing stages of the two outing retina signals.
 +
 +Parvo (details channel) dedicated parameter
 +-------------------------------------------
 +
 +* **ganglionCellsSensitivity** specifies the strength of the final local adaptation occurring at the output of this details dedicated channel. Parameter values remain between 0 and 1. Low value tend to give a linear response while higher values enforces the remaining low contrasted areas.
 +
 +**Note :** this parameter can correct eventual burned images by favoring low energetic details of the visual scene, even in bright areas.
 +
 +IPL Magno (motion/transient channel) parameters
 +-----------------------------------------------
 +
 +Once image information is cleaned, this channel acts as a high pass temporal filter that only selects signals related to transient signals (events, motion, etc.). A low pass spatial filter smooths extracted transient data and a final logarithmic compression enhances low transient events thus enhancing event sensitivity.
 +
 +* **parasolCells_beta** generally set to zero, can be considered as an amplifier gain at the entry point of this processing stage. Generally set to 0.
 +
 +* **parasolCells_tau** the temporal smoothing effect that can be added
 +
 +* **parasolCells_k** the spatial constant of the spatial filtering effect, set it at a high value to favor low spatial frequency signals that are lower subject to residual noise.
 +
 +* **amacrinCellsTemporalCutFrequency** specifies the temporal constant of the high pass filter. High values let slow transient events to be selected.
 +
 +* **V0CompressionParameter** specifies the strength of the log compression. Similar behaviors to previous description but here it enforces sensitivity of transient events.
 +
 +* **localAdaptintegration_tau** generally set to 0, no real use here actually
 +
 +* **localAdaptintegration_k** specifies the size of the area on which local adaptation is performed. Low values lead to short range local adaptation (higher sensitivity to noise), high values secure log compression.
@@@ -28,10 -28,11 +28,11 @@@ This tutorial code's is shown lines bel
  
     #include <stdio.h>
     #include <iostream>
 -   #include "opencv2/core/core.hpp"
 -   #include "opencv2/features2d/features2d.hpp"
 +   #include "opencv2/core.hpp"
 +   #include "opencv2/features2d.hpp"
+    #include "opencv2/nonfree/features2d.hpp"
 -   #include "opencv2/highgui/highgui.hpp"
 -   #include "opencv2/nonfree/nonfree.hpp"
 +   #include "opencv2/highgui.hpp"
 +   #include "opencv2/nonfree.hpp"
  
     using namespace cv;
  
index 242416b,0000000..fd487b7
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
 +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::
 +
- * **samples/cpp/OpenEXRimages_HighDynamicRange_Retina_toneMapping.cpp** shows how to use the retina to perform High Dynamic Range (HDR) luminance compression
++   * An example on retina tone mapping can be found at opencv_source_code/samples/cpp/OpenEXRimages_HDR_Retina_toneMapping.cpp
++   * An example on retina tone mapping on video input can be found at opencv_source_code/samples/cpp/OpenEXRimages_HDR_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.
 +
 +
-    **OpenCVReleaseFolder/bin/OpenEXRimages_HighDynamicRange_Retina_toneMapping memorial.exr [optionnal: 'fast']**
++* **samples/cpp/OpenEXRimages_HDR_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_HDR_Retina_toneMapping memorial.exr [optional: '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>
index 026ab69,0000000..671ac60
mode 100644,000000..100644
--- /dev/null
@@@ -1,2961 -1,0 +1,2961 @@@
-     return (Node*)&hdr->pool[nidx];
 +/*M///////////////////////////////////////////////////////////////////////////////////////
 +//
 +//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
 +//
 +//  By downloading, copying, installing or using the software you agree to this license.
 +//  If you do not agree to this license, do not download, install,
 +//  copy or use the software.
 +//
 +//
 +//                           License Agreement
 +//                For Open Source Computer Vision Library
 +//
 +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
 +// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
 +// Third party copyrights are property of their respective owners.
 +//
 +// Redistribution and use in source and binary forms, with or without modification,
 +// are permitted provided that the following conditions are met:
 +//
 +//   * Redistribution's of source code must retain the above copyright notice,
 +//     this list of conditions and the following disclaimer.
 +//
 +//   * Redistribution's in binary form must reproduce the above copyright notice,
 +//     this list of conditions and the following disclaimer in the documentation
 +//     and/or other materials provided with the distribution.
 +//
 +//   * The name of the copyright holders may not be used to endorse or promote products
 +//     derived from this software without specific prior written permission.
 +//
 +// This software is provided by the copyright holders and contributors "as is" and
 +// any express or implied warranties, including, but not limited to, the implied
 +// warranties of merchantability and fitness for a particular purpose are disclaimed.
 +// In no event shall the Intel Corporation or contributors be liable for any direct,
 +// indirect, incidental, special, exemplary, or consequential damages
 +// (including, but not limited to, procurement of substitute goods or services;
 +// loss of use, data, or profits; or business interruption) however caused
 +// and on any theory of liability, whether in contract, strict liability,
 +// or tort (including negligence or otherwise) arising in any way out of
 +// the use of this software, even if advised of the possibility of such damage.
 +//
 +//M*/
 +
 +#ifndef __OPENCV_CORE_MATRIX_OPERATIONS_HPP__
 +#define __OPENCV_CORE_MATRIX_OPERATIONS_HPP__
 +
 +#ifndef __cplusplus
 +#  error mat.inl.hpp header must be compiled as C++
 +#endif
 +
 +namespace cv
 +{
 +
 +//////////////////////// Input/Output Arrays ////////////////////////
 +
 +template<typename _Tp> inline
 +_InputArray::_InputArray(const std::vector<_Tp>& vec)
 +    : flags(FIXED_TYPE + STD_VECTOR + DataType<_Tp>::type), obj((void*)&vec)
 +{}
 +
 +template<typename _Tp> inline
 +_InputArray::_InputArray(const std::vector<std::vector<_Tp> >& vec)
 +    : flags(FIXED_TYPE + STD_VECTOR_VECTOR + DataType<_Tp>::type), obj((void*)&vec)
 +{}
 +
 +template<typename _Tp> inline
 +_InputArray::_InputArray(const std::vector<Mat_<_Tp> >& vec)
 +    : flags(FIXED_TYPE + STD_VECTOR_MAT + DataType<_Tp>::type), obj((void*)&vec)
 +{}
 +
 +template<typename _Tp, int m, int n> inline
 +_InputArray::_InputArray(const Matx<_Tp, m, n>& mtx)
 +    : flags(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type), obj((void*)&mtx), sz(n, m)
 +{}
 +
 +template<typename _Tp> inline
 +_InputArray::_InputArray(const _Tp* vec, int n)
 +    : flags(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type), obj((void*)vec), sz(n, 1)
 +{}
 +
 +template<typename _Tp> inline
 +_InputArray::_InputArray(const Mat_<_Tp>& m)
 +    : flags(FIXED_TYPE + MAT + DataType<_Tp>::type), obj((void*)&m)
 +{}
 +
 +
 +template<typename _Tp> inline
 +_OutputArray::_OutputArray(std::vector<_Tp>& vec)
 +    : _InputArray(vec)
 +{}
 +
 +template<typename _Tp> inline
 +_OutputArray::_OutputArray(std::vector<std::vector<_Tp> >& vec)
 +    : _InputArray(vec)
 +{}
 +
 +template<typename _Tp> inline
 +_OutputArray::_OutputArray(std::vector<Mat_<_Tp> >& vec)
 +    : _InputArray(vec)
 +{}
 +
 +template<typename _Tp> inline
 +_OutputArray::_OutputArray(Mat_<_Tp>& m)
 +    : _InputArray(m)
 +{}
 +
 +template<typename _Tp, int m, int n> inline
 +_OutputArray::_OutputArray(Matx<_Tp, m, n>& mtx)
 +    : _InputArray(mtx)
 +{}
 +
 +template<typename _Tp> inline
 +_OutputArray::_OutputArray(_Tp* vec, int n)
 +    : _InputArray(vec, n)
 +{}
 +
 +template<typename _Tp> inline
 +_OutputArray::_OutputArray(const std::vector<_Tp>& vec)
 +    : _InputArray(vec)
 +{
 +    flags |= FIXED_SIZE;
 +}
 +
 +template<typename _Tp> inline
 +_OutputArray::_OutputArray(const std::vector<std::vector<_Tp> >& vec)
 +    : _InputArray(vec)
 +{
 +    flags |= FIXED_SIZE;
 +}
 +
 +template<typename _Tp> inline
 +_OutputArray::_OutputArray(const std::vector<Mat_<_Tp> >& vec)
 +    : _InputArray(vec)
 +{
 +    flags |= FIXED_SIZE;
 +}
 +
 +template<typename _Tp> inline
 +_OutputArray::_OutputArray(const Mat_<_Tp>& m)
 +    : _InputArray(m)
 +{
 +    flags |= FIXED_SIZE;
 +}
 +
 +template<typename _Tp, int m, int n> inline
 +_OutputArray::_OutputArray(const Matx<_Tp, m, n>& mtx)
 +    : _InputArray(mtx)
 +{}
 +
 +template<typename _Tp> inline
 +_OutputArray::_OutputArray(const _Tp* vec, int n)
 +    : _InputArray(vec, n)
 +{}
 +
 +
 +
 +//////////////////////////////// Mat ////////////////////////////////
 +
 +inline
 +Mat::Mat()
 +    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), refcount(0), datastart(0), dataend(0),
 +      datalimit(0), allocator(0), size(&rows)
 +{}
 +
 +inline
 +Mat::Mat(int _rows, int _cols, int _type)
 +    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), refcount(0), datastart(0), dataend(0),
 +      datalimit(0), allocator(0), size(&rows)
 +{
 +    create(_rows, _cols, _type);
 +}
 +
 +inline
 +Mat::Mat(int _rows, int _cols, int _type, const Scalar& _s)
 +    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), refcount(0), datastart(0), dataend(0),
 +      datalimit(0), allocator(0), size(&rows)
 +{
 +    create(_rows, _cols, _type);
 +    *this = _s;
 +}
 +
 +inline
 +Mat::Mat(Size _sz, int _type)
 +    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), refcount(0), datastart(0), dataend(0),
 +      datalimit(0), allocator(0), size(&rows)
 +{
 +    create( _sz.height, _sz.width, _type );
 +}
 +
 +inline
 +Mat::Mat(Size _sz, int _type, const Scalar& _s)
 +    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), refcount(0), datastart(0), dataend(0),
 +      datalimit(0), allocator(0), size(&rows)
 +{
 +    create(_sz.height, _sz.width, _type);
 +    *this = _s;
 +}
 +
 +inline
 +Mat::Mat(int _dims, const int* _sz, int _type)
 +    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), refcount(0), datastart(0), dataend(0),
 +      datalimit(0), allocator(0), size(&rows)
 +{
 +    create(_dims, _sz, _type);
 +}
 +
 +inline
 +Mat::Mat(int _dims, const int* _sz, int _type, const Scalar& _s)
 +    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), refcount(0), datastart(0), dataend(0),
 +      datalimit(0), allocator(0), size(&rows)
 +{
 +    create(_dims, _sz, _type);
 +    *this = _s;
 +}
 +
 +inline
 +Mat::Mat(const Mat& m)
 +    : flags(m.flags), dims(m.dims), rows(m.rows), cols(m.cols), data(m.data), refcount(m.refcount),
 +      datastart(m.datastart), dataend(m.dataend), datalimit(m.datalimit), allocator(m.allocator),
 +      size(&rows)
 +{
 +    if( refcount )
 +        CV_XADD(refcount, 1);
 +    if( m.dims <= 2 )
 +    {
 +        step[0] = m.step[0]; step[1] = m.step[1];
 +    }
 +    else
 +    {
 +        dims = 0;
 +        copySize(m);
 +    }
 +}
 +
 +inline
 +Mat::Mat(int _rows, int _cols, int _type, void* _data, size_t _step)
 +    : flags(MAGIC_VAL + (_type & TYPE_MASK)), dims(2), rows(_rows), cols(_cols),
 +      data((uchar*)_data), refcount(0), datastart((uchar*)_data), dataend(0), datalimit(0),
 +      allocator(0), size(&rows)
 +{
 +    size_t esz = CV_ELEM_SIZE(_type);
 +    size_t minstep = cols * esz;
 +    if( _step == AUTO_STEP )
 +    {
 +        _step = minstep;
 +        flags |= CONTINUOUS_FLAG;
 +    }
 +    else
 +    {
 +        if( rows == 1 ) _step = minstep;
 +        CV_DbgAssert( _step >= minstep );
 +        flags |= _step == minstep ? CONTINUOUS_FLAG : 0;
 +    }
 +    step[0] = _step;
 +    step[1] = esz;
 +    datalimit = datastart + _step * rows;
 +    dataend = datalimit - _step + minstep;
 +}
 +
 +inline
 +Mat::Mat(Size _sz, int _type, void* _data, size_t _step)
 +    : flags(MAGIC_VAL + (_type & TYPE_MASK)), dims(2), rows(_sz.height), cols(_sz.width),
 +      data((uchar*)_data), refcount(0), datastart((uchar*)_data), dataend(0), datalimit(0),
 +      allocator(0), size(&rows)
 +{
 +    size_t esz = CV_ELEM_SIZE(_type);
 +    size_t minstep = cols*esz;
 +    if( _step == AUTO_STEP )
 +    {
 +        _step = minstep;
 +        flags |= CONTINUOUS_FLAG;
 +    }
 +    else
 +    {
 +        if( rows == 1 ) _step = minstep;
 +        CV_DbgAssert( _step >= minstep );
 +        flags |= _step == minstep ? CONTINUOUS_FLAG : 0;
 +    }
 +    step[0] = _step;
 +    step[1] = esz;
 +    datalimit = datastart + _step*rows;
 +    dataend = datalimit - _step + minstep;
 +}
 +
 +template<typename _Tp> inline
 +Mat::Mat(const std::vector<_Tp>& vec, bool copyData)
 +    : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), dims(2), rows((int)vec.size()),
 +      cols(1), data(0), refcount(0), datastart(0), dataend(0), allocator(0), size(&rows)
 +{
 +    if(vec.empty())
 +        return;
 +    if( !copyData )
 +    {
 +        step[0] = step[1] = sizeof(_Tp);
 +        data = datastart = (uchar*)&vec[0];
 +        datalimit = dataend = datastart + rows * step[0];
 +    }
 +    else
 +        Mat((int)vec.size(), 1, DataType<_Tp>::type, (uchar*)&vec[0]).copyTo(*this);
 +}
 +
 +template<typename _Tp, int n> inline
 +Mat::Mat(const Vec<_Tp, n>& vec, bool copyData)
 +    : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), dims(2), rows(n), cols(1), data(0),
 +      refcount(0), datastart(0), dataend(0), allocator(0), size(&rows)
 +{
 +    if( !copyData )
 +    {
 +        step[0] = step[1] = sizeof(_Tp);
 +        data = datastart = (uchar*)vec.val;
 +        datalimit = dataend = datastart + rows * step[0];
 +    }
 +    else
 +        Mat(n, 1, DataType<_Tp>::type, (void*)vec.val).copyTo(*this);
 +}
 +
 +
 +template<typename _Tp, int m, int n> inline
 +Mat::Mat(const Matx<_Tp,m,n>& M, bool copyData)
 +    : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), dims(2), rows(m), cols(n), data(0),
 +      refcount(0), datastart(0), dataend(0), allocator(0), size(&rows)
 +{
 +    if( !copyData )
 +    {
 +        step[0] = cols * sizeof(_Tp);
 +        step[1] = sizeof(_Tp);
 +        data = datastart = (uchar*)M.val;
 +        datalimit = dataend = datastart + rows * step[0];
 +    }
 +    else
 +        Mat(m, n, DataType<_Tp>::type, (uchar*)M.val).copyTo(*this);
 +}
 +
 +template<typename _Tp> inline
 +Mat::Mat(const Point_<_Tp>& pt, bool copyData)
 +    : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), dims(2), rows(2), cols(1), data(0),
 +      refcount(0), datastart(0), dataend(0), allocator(0), size(&rows)
 +{
 +    if( !copyData )
 +    {
 +        step[0] = step[1] = sizeof(_Tp);
 +        data = datastart = (uchar*)&pt.x;
 +        datalimit = dataend = datastart + rows * step[0];
 +    }
 +    else
 +    {
 +        create(2, 1, DataType<_Tp>::type);
 +        ((_Tp*)data)[0] = pt.x;
 +        ((_Tp*)data)[1] = pt.y;
 +    }
 +}
 +
 +template<typename _Tp> inline
 +Mat::Mat(const Point3_<_Tp>& pt, bool copyData)
 +    : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), dims(2), rows(3), cols(1), data(0),
 +      refcount(0), datastart(0), dataend(0), allocator(0), size(&rows)
 +{
 +    if( !copyData )
 +    {
 +        step[0] = step[1] = sizeof(_Tp);
 +        data = datastart = (uchar*)&pt.x;
 +        datalimit = dataend = datastart + rows * step[0];
 +    }
 +    else
 +    {
 +        create(3, 1, DataType<_Tp>::type);
 +        ((_Tp*)data)[0] = pt.x;
 +        ((_Tp*)data)[1] = pt.y;
 +        ((_Tp*)data)[2] = pt.z;
 +    }
 +}
 +
 +template<typename _Tp> inline
 +Mat::Mat(const MatCommaInitializer_<_Tp>& commaInitializer)
 +    : flags(MAGIC_VAL | DataType<_Tp>::type | CV_MAT_CONT_FLAG), dims(0), rows(0), cols(0), data(0),
 +      refcount(0), datastart(0), dataend(0), allocator(0), size(&rows)
 +{
 +    *this = commaInitializer.operator Mat_<_Tp>();
 +}
 +
 +inline
 +Mat::~Mat()
 +{
 +    release();
 +    if( step.p != step.buf )
 +        fastFree(step.p);
 +}
 +
 +inline
 +Mat& Mat::operator = (const Mat& m)
 +{
 +    if( this != &m )
 +    {
 +        if( m.refcount )
 +            CV_XADD(m.refcount, 1);
 +        release();
 +        flags = m.flags;
 +        if( dims <= 2 && m.dims <= 2 )
 +        {
 +            dims = m.dims;
 +            rows = m.rows;
 +            cols = m.cols;
 +            step[0] = m.step[0];
 +            step[1] = m.step[1];
 +        }
 +        else
 +            copySize(m);
 +        data = m.data;
 +        datastart = m.datastart;
 +        dataend = m.dataend;
 +        datalimit = m.datalimit;
 +        refcount = m.refcount;
 +        allocator = m.allocator;
 +    }
 +    return *this;
 +}
 +
 +inline
 +Mat Mat::row(int y) const
 +{
 +    return Mat(*this, Range(y, y + 1), Range::all());
 +}
 +
 +inline
 +Mat Mat::col(int x) const
 +{
 +    return Mat(*this, Range::all(), Range(x, x + 1));
 +}
 +
 +inline
 +Mat Mat::rowRange(int startrow, int endrow) const
 +{
 +    return Mat(*this, Range(startrow, endrow), Range::all());
 +}
 +
 +inline
 +Mat Mat::rowRange(const Range& r) const
 +{
 +    return Mat(*this, r, Range::all());
 +}
 +
 +inline
 +Mat Mat::colRange(int startcol, int endcol) const
 +{
 +    return Mat(*this, Range::all(), Range(startcol, endcol));
 +}
 +
 +inline
 +Mat Mat::colRange(const Range& r) const
 +{
 +    return Mat(*this, Range::all(), r);
 +}
 +
 +inline
 +Mat Mat::clone() const
 +{
 +    Mat m;
 +    copyTo(m);
 +    return m;
 +}
 +
 +inline
 +void Mat::assignTo( Mat& m, int _type ) const
 +{
 +    if( _type < 0 )
 +        m = *this;
 +    else
 +        convertTo(m, _type);
 +}
 +
 +inline
 +void Mat::create(int _rows, int _cols, int _type)
 +{
 +    _type &= TYPE_MASK;
 +    if( dims <= 2 && rows == _rows && cols == _cols && type() == _type && data )
 +        return;
 +    int sz[] = {_rows, _cols};
 +    create(2, sz, _type);
 +}
 +
 +inline
 +void Mat::create(Size _sz, int _type)
 +{
 +    create(_sz.height, _sz.width, _type);
 +}
 +
 +inline
 +void Mat::addref()
 +{
 +    if( refcount )
 +        CV_XADD(refcount, 1);
 +}
 +
 +inline void Mat::release()
 +{
 +    if( refcount && CV_XADD(refcount, -1) == 1 )
 +        deallocate();
 +    data = datastart = dataend = datalimit = 0;
 +    size.p[0] = 0;
 +    refcount = 0;
 +}
 +
 +inline
 +Mat Mat::operator()( Range _rowRange, Range _colRange ) const
 +{
 +    return Mat(*this, _rowRange, _colRange);
 +}
 +
 +inline
 +Mat Mat::operator()( const Rect& roi ) const
 +{
 +    return Mat(*this, roi);
 +}
 +
 +inline
 +Mat Mat::operator()(const Range* ranges) const
 +{
 +    return Mat(*this, ranges);
 +}
 +
 +inline
 +bool Mat::isContinuous() const
 +{
 +    return (flags & CONTINUOUS_FLAG) != 0;
 +}
 +
 +inline
 +bool Mat::isSubmatrix() const
 +{
 +    return (flags & SUBMATRIX_FLAG) != 0;
 +}
 +
 +inline
 +size_t Mat::elemSize() const
 +{
 +    return dims > 0 ? step.p[dims - 1] : 0;
 +}
 +
 +inline
 +size_t Mat::elemSize1() const
 +{
 +    return CV_ELEM_SIZE1(flags);
 +}
 +
 +inline
 +int Mat::type() const
 +{
 +    return CV_MAT_TYPE(flags);
 +}
 +
 +inline
 +int Mat::depth() const
 +{
 +    return CV_MAT_DEPTH(flags);
 +}
 +
 +inline
 +int Mat::channels() const
 +{
 +    return CV_MAT_CN(flags);
 +}
 +
 +inline
 +size_t Mat::step1(int i) const
 +{
 +    return step.p[i] / elemSize1();
 +}
 +
 +inline
 +bool Mat::empty() const
 +{
 +    return data == 0 || total() == 0;
 +}
 +
 +inline
 +size_t Mat::total() const
 +{
 +    if( dims <= 2 )
 +        return (size_t)rows * cols;
 +    size_t p = 1;
 +    for( int i = 0; i < dims; i++ )
 +        p *= size[i];
 +    return p;
 +}
 +
 +inline
 +uchar* Mat::ptr(int y)
 +{
 +    CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) );
 +    return data + step.p[0] * y;
 +}
 +
 +inline
 +const uchar* Mat::ptr(int y) const
 +{
 +    CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) );
 +    return data + step.p[0] * y;
 +}
 +
 +template<typename _Tp> inline
 +_Tp* Mat::ptr(int y)
 +{
 +    CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) );
 +    return (_Tp*)(data + step.p[0] * y);
 +}
 +
 +template<typename _Tp> inline
 +const _Tp* Mat::ptr(int y) const
 +{
 +    CV_DbgAssert( y == 0 || (data && dims >= 1 && data && (unsigned)y < (unsigned)size.p[0]) );
 +    return (const _Tp*)(data + step.p[0] * y);
 +}
 +
 +inline
 +uchar* Mat::ptr(int i0, int i1)
 +{
 +    CV_DbgAssert( dims >= 2 && data &&
 +                  (unsigned)i0 < (unsigned)size.p[0] &&
 +                  (unsigned)i1 < (unsigned)size.p[1] );
 +    return data + i0 * step.p[0] + i1 * step.p[1];
 +}
 +
 +inline
 +const uchar* Mat::ptr(int i0, int i1) const
 +{
 +    CV_DbgAssert( dims >= 2 && data &&
 +                 (unsigned)i0 < (unsigned)size.p[0] &&
 +                 (unsigned)i1 < (unsigned)size.p[1] );
 +    return data + i0 * step.p[0] + i1 * step.p[1];
 +}
 +
 +template<typename _Tp> inline
 +_Tp* Mat::ptr(int i0, int i1)
 +{
 +    CV_DbgAssert( dims >= 2 && data &&
 +                  (unsigned)i0 < (unsigned)size.p[0] &&
 +                  (unsigned)i1 < (unsigned)size.p[1] );
 +    return (_Tp*)(data + i0 * step.p[0] + i1 * step.p[1]);
 +}
 +
 +template<typename _Tp> inline
 +const _Tp* Mat::ptr(int i0, int i1) const
 +{
 +    CV_DbgAssert( dims >= 2 && data &&
 +                  (unsigned)i0 < (unsigned)size.p[0] &&
 +                  (unsigned)i1 < (unsigned)size.p[1] );
 +    return (const _Tp*)(data + i0 * step.p[0] + i1 * step.p[1]);
 +}
 +
 +inline
 +uchar* Mat::ptr(int i0, int i1, int i2)
 +{
 +    CV_DbgAssert( dims >= 3 && data &&
 +                  (unsigned)i0 < (unsigned)size.p[0] &&
 +                  (unsigned)i1 < (unsigned)size.p[1] &&
 +                  (unsigned)i2 < (unsigned)size.p[2] );
 +    return data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2];
 +}
 +
 +inline
 +const uchar* Mat::ptr(int i0, int i1, int i2) const
 +{
 +    CV_DbgAssert( dims >= 3 && data &&
 +                  (unsigned)i0 < (unsigned)size.p[0] &&
 +                  (unsigned)i1 < (unsigned)size.p[1] &&
 +                  (unsigned)i2 < (unsigned)size.p[2] );
 +    return data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2];
 +}
 +
 +template<typename _Tp> inline
 +_Tp* Mat::ptr(int i0, int i1, int i2)
 +{
 +    CV_DbgAssert( dims >= 3 && data &&
 +                  (unsigned)i0 < (unsigned)size.p[0] &&
 +                  (unsigned)i1 < (unsigned)size.p[1] &&
 +                  (unsigned)i2 < (unsigned)size.p[2] );
 +    return (_Tp*)(data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2]);
 +}
 +
 +template<typename _Tp> inline
 +const _Tp* Mat::ptr(int i0, int i1, int i2) const
 +{
 +    CV_DbgAssert( dims >= 3 && data &&
 +                  (unsigned)i0 < (unsigned)size.p[0] &&
 +                  (unsigned)i1 < (unsigned)size.p[1] &&
 +                  (unsigned)i2 < (unsigned)size.p[2] );
 +    return (const _Tp*)(data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2]);
 +}
 +
 +inline
 +uchar* Mat::ptr(const int* idx)
 +{
 +    int i, d = dims;
 +    uchar* p = data;
 +    CV_DbgAssert( d >= 1 && p );
 +    for( i = 0; i < d; i++ )
 +    {
 +        CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] );
 +        p += idx[i] * step.p[i];
 +    }
 +    return p;
 +}
 +
 +inline
 +const uchar* Mat::ptr(const int* idx) const
 +{
 +    int i, d = dims;
 +    uchar* p = data;
 +    CV_DbgAssert( d >= 1 && p );
 +    for( i = 0; i < d; i++ )
 +    {
 +        CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] );
 +        p += idx[i] * step.p[i];
 +    }
 +    return p;
 +}
 +
 +template<typename _Tp> inline
 +_Tp& Mat::at(int i0, int i1)
 +{
 +    CV_DbgAssert( dims <= 2 && data && (unsigned)i0 < (unsigned)size.p[0] &&
 +        (unsigned)(i1 * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels()) &&
 +        CV_ELEM_SIZE1(DataType<_Tp>::depth) == elemSize1());
 +    return ((_Tp*)(data + step.p[0] * i0))[i1];
 +}
 +
 +template<typename _Tp> inline
 +const _Tp& Mat::at(int i0, int i1) const
 +{
 +    CV_DbgAssert( dims <= 2 && data && (unsigned)i0 < (unsigned)size.p[0] &&
 +        (unsigned)(i1 * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels()) &&
 +        CV_ELEM_SIZE1(DataType<_Tp>::depth) == elemSize1());
 +    return ((const _Tp*)(data + step.p[0] * i0))[i1];
 +}
 +
 +template<typename _Tp> inline
 +_Tp& Mat::at(Point pt)
 +{
 +    CV_DbgAssert( dims <= 2 && data && (unsigned)pt.y < (unsigned)size.p[0] &&
 +        (unsigned)(pt.x * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels()) &&
 +        CV_ELEM_SIZE1(DataType<_Tp>::depth) == elemSize1());
 +    return ((_Tp*)(data + step.p[0] * pt.y))[pt.x];
 +}
 +
 +template<typename _Tp> inline
 +const _Tp& Mat::at(Point pt) const
 +{
 +    CV_DbgAssert( dims <= 2 && data && (unsigned)pt.y < (unsigned)size.p[0] &&
 +        (unsigned)(pt.x * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels()) &&
 +        CV_ELEM_SIZE1(DataType<_Tp>::depth) == elemSize1());
 +    return ((const _Tp*)(data + step.p[0] * pt.y))[pt.x];
 +}
 +
 +template<typename _Tp> inline
 +_Tp& Mat::at(int i0)
 +{
 +    CV_DbgAssert( dims <= 2 && data &&
 +                 (unsigned)i0 < (unsigned)(size.p[0] * size.p[1]) &&
 +                 elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) );
 +    if( isContinuous() || size.p[0] == 1 )
 +        return ((_Tp*)data)[i0];
 +    if( size.p[1] == 1 )
 +        return *(_Tp*)(data + step.p[0] * i0);
 +    int i = i0 / cols, j = i0 - i * cols;
 +    return ((_Tp*)(data + step.p[0] * i))[j];
 +}
 +
 +template<typename _Tp> inline
 +const _Tp& Mat::at(int i0) const
 +{
 +    CV_DbgAssert( dims <= 2 && data &&
 +                 (unsigned)i0 < (unsigned)(size.p[0] * size.p[1]) &&
 +                 elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) );
 +    if( isContinuous() || size.p[0] == 1 )
 +        return ((const _Tp*)data)[i0];
 +    if( size.p[1] == 1 )
 +        return *(const _Tp*)(data + step.p[0] * i0);
 +    int i = i0 / cols, j = i0 - i * cols;
 +    return ((const _Tp*)(data + step.p[0] * i))[j];
 +}
 +
 +template<typename _Tp> inline
 +_Tp& Mat::at(int i0, int i1, int i2)
 +{
 +    CV_DbgAssert( elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) );
 +    return *(_Tp*)ptr(i0, i1, i2);
 +}
 +
 +template<typename _Tp> inline
 +const _Tp& Mat::at(int i0, int i1, int i2) const
 +{
 +    CV_DbgAssert( elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) );
 +    return *(const _Tp*)ptr(i0, i1, i2);
 +}
 +
 +template<typename _Tp> inline
 +_Tp& Mat::at(const int* idx)
 +{
 +    CV_DbgAssert( elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) );
 +    return *(_Tp*)ptr(idx);
 +}
 +
 +template<typename _Tp> inline
 +const _Tp& Mat::at(const int* idx) const
 +{
 +    CV_DbgAssert( elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) );
 +    return *(const _Tp*)ptr(idx);
 +}
 +
 +template<typename _Tp, int n> inline
 +_Tp& Mat::at(const Vec<int, n>& idx)
 +{
 +    CV_DbgAssert( elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) );
 +    return *(_Tp*)ptr(idx.val);
 +}
 +
 +template<typename _Tp, int n> inline
 +const _Tp& Mat::at(const Vec<int, n>& idx) const
 +{
 +    CV_DbgAssert( elemSize() == CV_ELEM_SIZE(DataType<_Tp>::type) );
 +    return *(const _Tp*)ptr(idx.val);
 +}
 +
 +template<typename _Tp> inline
 +MatConstIterator_<_Tp> Mat::begin() const
 +{
 +    CV_DbgAssert( elemSize() == sizeof(_Tp) );
 +    return MatConstIterator_<_Tp>((const Mat_<_Tp>*)this);
 +}
 +
 +template<typename _Tp> inline
 +MatConstIterator_<_Tp> Mat::end() const
 +{
 +    CV_DbgAssert( elemSize() == sizeof(_Tp) );
 +    MatConstIterator_<_Tp> it((const Mat_<_Tp>*)this);
 +    it += total();
 +    return it;
 +}
 +
 +template<typename _Tp> inline
 +MatIterator_<_Tp> Mat::begin()
 +{
 +    CV_DbgAssert( elemSize() == sizeof(_Tp) );
 +    return MatIterator_<_Tp>((Mat_<_Tp>*)this);
 +}
 +
 +template<typename _Tp> inline
 +MatIterator_<_Tp> Mat::end()
 +{
 +    CV_DbgAssert( elemSize() == sizeof(_Tp) );
 +    MatIterator_<_Tp> it((Mat_<_Tp>*)this);
 +    it += total();
 +    return it;
 +}
 +
 +template<typename _Tp> inline
 +Mat::operator std::vector<_Tp>() const
 +{
 +    std::vector<_Tp> v;
 +    copyTo(v);
 +    return v;
 +}
 +
 +template<typename _Tp, int n> inline
 +Mat::operator Vec<_Tp, n>() const
 +{
 +    CV_Assert( data && dims <= 2 && (rows == 1 || cols == 1) &&
 +               rows + cols - 1 == n && channels() == 1 );
 +
 +    if( isContinuous() && type() == DataType<_Tp>::type )
 +        return Vec<_Tp, n>((_Tp*)data);
 +    Vec<_Tp, n> v;
 +    Mat tmp(rows, cols, DataType<_Tp>::type, v.val);
 +    convertTo(tmp, tmp.type());
 +    return v;
 +}
 +
 +template<typename _Tp, int m, int n> inline
 +Mat::operator Matx<_Tp, m, n>() const
 +{
 +    CV_Assert( data && dims <= 2 && rows == m && cols == n && channels() == 1 );
 +
 +    if( isContinuous() && type() == DataType<_Tp>::type )
 +        return Matx<_Tp, m, n>((_Tp*)data);
 +    Matx<_Tp, m, n> mtx;
 +    Mat tmp(rows, cols, DataType<_Tp>::type, mtx.val);
 +    convertTo(tmp, tmp.type());
 +    return mtx;
 +}
 +
 +template<typename _Tp> inline
 +void Mat::push_back(const _Tp& elem)
 +{
 +    if( !data )
 +    {
 +        *this = Mat(1, 1, DataType<_Tp>::type, (void*)&elem).clone();
 +        return;
 +    }
 +    CV_Assert(DataType<_Tp>::type == type() && cols == 1
 +              /* && dims == 2 (cols == 1 implies dims == 2) */);
 +    uchar* tmp = dataend + step[0];
 +    if( !isSubmatrix() && isContinuous() && tmp <= datalimit )
 +    {
 +        *(_Tp*)(data + (size.p[0]++) * step.p[0]) = elem;
 +        dataend = tmp;
 +    }
 +    else
 +        push_back_(&elem);
 +}
 +
 +template<typename _Tp> inline
 +void Mat::push_back(const Mat_<_Tp>& m)
 +{
 +    push_back((const Mat&)m);
 +}
 +
 +
 +
 +///////////////////////////// Mat::MSize ////////////////////////////
 +
 +inline
 +Mat::MSize::MSize(int* _p)
 +    : p(_p) {}
 +
 +inline
 +Size Mat::MSize::operator()() const
 +{
 +    CV_DbgAssert(p[-1] <= 2);
 +    return Size(p[1], p[0]);
 +}
 +
 +inline
 +const int& Mat::MSize::operator[](int i) const
 +{
 +    return p[i];
 +}
 +
 +inline
 +int& Mat::MSize::operator[](int i)
 +{
 +    return p[i];
 +}
 +
 +inline
 +Mat::MSize::operator const int*() const
 +{
 +    return p;
 +}
 +
 +inline
 +bool Mat::MSize::operator == (const MSize& sz) const
 +{
 +    int d = p[-1];
 +    int dsz = sz.p[-1];
 +    if( d != dsz )
 +        return false;
 +    if( d == 2 )
 +        return p[0] == sz.p[0] && p[1] == sz.p[1];
 +
 +    for( int i = 0; i < d; i++ )
 +        if( p[i] != sz.p[i] )
 +            return false;
 +    return true;
 +}
 +
 +inline
 +bool Mat::MSize::operator != (const MSize& sz) const
 +{
 +    return !(*this == sz);
 +}
 +
 +
 +
 +///////////////////////////// Mat::MStep ////////////////////////////
 +
 +inline
 +Mat::MStep::MStep()
 +{
 +    p = buf; p[0] = p[1] = 0;
 +}
 +
 +inline
 +Mat::MStep::MStep(size_t s)
 +{
 +    p = buf; p[0] = s; p[1] = 0;
 +}
 +
 +inline
 +const size_t& Mat::MStep::operator[](int i) const
 +{
 +    return p[i];
 +}
 +
 +inline
 +size_t& Mat::MStep::operator[](int i)
 +{
 +    return p[i];
 +}
 +
 +inline Mat::MStep::operator size_t() const
 +{
 +    CV_DbgAssert( p == buf );
 +    return buf[0];
 +}
 +
 +inline Mat::MStep& Mat::MStep::operator = (size_t s)
 +{
 +    CV_DbgAssert( p == buf );
 +    buf[0] = s;
 +    return *this;
 +}
 +
 +
 +
 +////////////////////////////// Mat_<_Tp> ////////////////////////////
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>::Mat_()
 +    : Mat()
 +{
 +    flags = (flags & ~CV_MAT_TYPE_MASK) | DataType<_Tp>::type;
 +}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>::Mat_(int _rows, int _cols)
 +    : Mat(_rows, _cols, DataType<_Tp>::type)
 +{
 +}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>::Mat_(int _rows, int _cols, const _Tp& value)
 +    : Mat(_rows, _cols, DataType<_Tp>::type)
 +{
 +    *this = value;
 +}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>::Mat_(Size _sz)
 +    : Mat(_sz.height, _sz.width, DataType<_Tp>::type)
 +{}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>::Mat_(Size _sz, const _Tp& value)
 +    : Mat(_sz.height, _sz.width, DataType<_Tp>::type)
 +{
 +    *this = value;
 +}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>::Mat_(int _dims, const int* _sz)
 +    : Mat(_dims, _sz, DataType<_Tp>::type)
 +{}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>::Mat_(int _dims, const int* _sz, const _Tp& _s)
 +    : Mat(_dims, _sz, DataType<_Tp>::type, Scalar(_s))
 +{}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>::Mat_(const Mat_<_Tp>& m, const Range* ranges)
 +    : Mat(m, ranges)
 +{}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>::Mat_(const Mat& m)
 +    : Mat()
 +{
 +    flags = (flags & ~CV_MAT_TYPE_MASK) | DataType<_Tp>::type;
 +    *this = m;
 +}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>::Mat_(const Mat_& m)
 +    : Mat(m)
 +{}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>::Mat_(int _rows, int _cols, _Tp* _data, size_t steps)
 +    : Mat(_rows, _cols, DataType<_Tp>::type, _data, steps)
 +{}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>::Mat_(const Mat_& m, const Range& _rowRange, const Range& _colRange)
 +    : Mat(m, _rowRange, _colRange)
 +{}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>::Mat_(const Mat_& m, const Rect& roi)
 +    : Mat(m, roi)
 +{}
 +
 +template<typename _Tp> template<int n> inline
 +Mat_<_Tp>::Mat_(const Vec<typename DataType<_Tp>::channel_type, n>& vec, bool copyData)
 +    : Mat(n / DataType<_Tp>::channels, 1, DataType<_Tp>::type, (void*)&vec)
 +{
 +    CV_Assert(n%DataType<_Tp>::channels == 0);
 +    if( copyData )
 +        *this = clone();
 +}
 +
 +template<typename _Tp> template<int m, int n> inline
 +Mat_<_Tp>::Mat_(const Matx<typename DataType<_Tp>::channel_type, m, n>& M, bool copyData)
 +    : Mat(m, n / DataType<_Tp>::channels, DataType<_Tp>::type, (void*)&M)
 +{
 +    CV_Assert(n % DataType<_Tp>::channels == 0);
 +    if( copyData )
 +        *this = clone();
 +}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>::Mat_(const Point_<typename DataType<_Tp>::channel_type>& pt, bool copyData)
 +    : Mat(2 / DataType<_Tp>::channels, 1, DataType<_Tp>::type, (void*)&pt)
 +{
 +    CV_Assert(2 % DataType<_Tp>::channels == 0);
 +    if( copyData )
 +        *this = clone();
 +}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>::Mat_(const Point3_<typename DataType<_Tp>::channel_type>& pt, bool copyData)
 +    : Mat(3 / DataType<_Tp>::channels, 1, DataType<_Tp>::type, (void*)&pt)
 +{
 +    CV_Assert(3 % DataType<_Tp>::channels == 0);
 +    if( copyData )
 +        *this = clone();
 +}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>::Mat_(const MatCommaInitializer_<_Tp>& commaInitializer)
 +    : Mat(commaInitializer)
 +{}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>::Mat_(const std::vector<_Tp>& vec, bool copyData)
 +    : Mat(vec, copyData)
 +{}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>& Mat_<_Tp>::operator = (const Mat& m)
 +{
 +    if( DataType<_Tp>::type == m.type() )
 +    {
 +        Mat::operator = (m);
 +        return *this;
 +    }
 +    if( DataType<_Tp>::depth == m.depth() )
 +    {
 +        return (*this = m.reshape(DataType<_Tp>::channels, m.dims, 0));
 +    }
 +    CV_DbgAssert(DataType<_Tp>::channels == m.channels());
 +    m.convertTo(*this, type());
 +    return *this;
 +}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>& Mat_<_Tp>::operator = (const Mat_& m)
 +{
 +    Mat::operator=(m);
 +    return *this;
 +}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>& Mat_<_Tp>::operator = (const _Tp& s)
 +{
 +    typedef typename DataType<_Tp>::vec_type VT;
 +    Mat::operator=(Scalar((const VT&)s));
 +    return *this;
 +}
 +
 +template<typename _Tp> inline
 +void Mat_<_Tp>::create(int _rows, int _cols)
 +{
 +    Mat::create(_rows, _cols, DataType<_Tp>::type);
 +}
 +
 +template<typename _Tp> inline
 +void Mat_<_Tp>::create(Size _sz)
 +{
 +    Mat::create(_sz, DataType<_Tp>::type);
 +}
 +
 +template<typename _Tp> inline
 +void Mat_<_Tp>::create(int _dims, const int* _sz)
 +{
 +    Mat::create(_dims, _sz, DataType<_Tp>::type);
 +}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp> Mat_<_Tp>::cross(const Mat_& m) const
 +{
 +    return Mat_<_Tp>(Mat::cross(m));
 +}
 +
 +template<typename _Tp> template<typename T2> inline
 +Mat_<_Tp>::operator Mat_<T2>() const
 +{
 +    return Mat_<T2>(*this);
 +}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp> Mat_<_Tp>::row(int y) const
 +{
 +    return Mat_(*this, Range(y, y+1), Range::all());
 +}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp> Mat_<_Tp>::col(int x) const
 +{
 +    return Mat_(*this, Range::all(), Range(x, x+1));
 +}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp> Mat_<_Tp>::diag(int d) const
 +{
 +    return Mat_(Mat::diag(d));
 +}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp> Mat_<_Tp>::clone() const
 +{
 +    return Mat_(Mat::clone());
 +}
 +
 +template<typename _Tp> inline
 +size_t Mat_<_Tp>::elemSize() const
 +{
 +    CV_DbgAssert( Mat::elemSize() == sizeof(_Tp) );
 +    return sizeof(_Tp);
 +}
 +
 +template<typename _Tp> inline
 +size_t Mat_<_Tp>::elemSize1() const
 +{
 +    CV_DbgAssert( Mat::elemSize1() == sizeof(_Tp) / DataType<_Tp>::channels );
 +    return sizeof(_Tp) / DataType<_Tp>::channels;
 +}
 +
 +template<typename _Tp> inline
 +int Mat_<_Tp>::type() const
 +{
 +    CV_DbgAssert( Mat::type() == DataType<_Tp>::type );
 +    return DataType<_Tp>::type;
 +}
 +
 +template<typename _Tp> inline
 +int Mat_<_Tp>::depth() const
 +{
 +    CV_DbgAssert( Mat::depth() == DataType<_Tp>::depth );
 +    return DataType<_Tp>::depth;
 +}
 +
 +template<typename _Tp> inline
 +int Mat_<_Tp>::channels() const
 +{
 +    CV_DbgAssert( Mat::channels() == DataType<_Tp>::channels );
 +    return DataType<_Tp>::channels;
 +}
 +
 +template<typename _Tp> inline
 +size_t Mat_<_Tp>::stepT(int i) const
 +{
 +    return step.p[i] / elemSize();
 +}
 +
 +template<typename _Tp> inline
 +size_t Mat_<_Tp>::step1(int i) const
 +{
 +    return step.p[i] / elemSize1();
 +}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>& Mat_<_Tp>::adjustROI( int dtop, int dbottom, int dleft, int dright )
 +{
 +    return (Mat_<_Tp>&)(Mat::adjustROI(dtop, dbottom, dleft, dright));
 +}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp> Mat_<_Tp>::operator()( const Range& _rowRange, const Range& _colRange ) const
 +{
 +    return Mat_<_Tp>(*this, _rowRange, _colRange);
 +}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp> Mat_<_Tp>::operator()( const Rect& roi ) const
 +{
 +    return Mat_<_Tp>(*this, roi);
 +}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp> Mat_<_Tp>::operator()( const Range* ranges ) const
 +{
 +    return Mat_<_Tp>(*this, ranges);
 +}
 +
 +template<typename _Tp> inline
 +_Tp* Mat_<_Tp>::operator [](int y)
 +{
 +    return (_Tp*)ptr(y);
 +}
 +
 +template<typename _Tp> inline
 +const _Tp* Mat_<_Tp>::operator [](int y) const
 +{
 +    return (const _Tp*)ptr(y);
 +}
 +
 +template<typename _Tp> inline
 +_Tp& Mat_<_Tp>::operator ()(int i0, int i1)
 +{
 +    CV_DbgAssert( dims <= 2 && data &&
 +                  (unsigned)i0 < (unsigned)size.p[0] &&
 +                  (unsigned)i1 < (unsigned)size.p[1] &&
 +                  type() == DataType<_Tp>::type );
 +    return ((_Tp*)(data + step.p[0] * i0))[i1];
 +}
 +
 +template<typename _Tp> inline
 +const _Tp& Mat_<_Tp>::operator ()(int i0, int i1) const
 +{
 +    CV_DbgAssert( dims <= 2 && data &&
 +                  (unsigned)i0 < (unsigned)size.p[0] &&
 +                  (unsigned)i1 < (unsigned)size.p[1] &&
 +                  type() == DataType<_Tp>::type );
 +    return ((const _Tp*)(data + step.p[0] * i0))[i1];
 +}
 +
 +template<typename _Tp> inline
 +_Tp& Mat_<_Tp>::operator ()(Point pt)
 +{
 +    CV_DbgAssert( dims <= 2 && data &&
 +                  (unsigned)pt.y < (unsigned)size.p[0] &&
 +                  (unsigned)pt.x < (unsigned)size.p[1] &&
 +                  type() == DataType<_Tp>::type );
 +    return ((_Tp*)(data + step.p[0] * pt.y))[pt.x];
 +}
 +
 +template<typename _Tp> inline
 +const _Tp& Mat_<_Tp>::operator ()(Point pt) const
 +{
 +    CV_DbgAssert( dims <= 2 && data &&
 +                  (unsigned)pt.y < (unsigned)size.p[0] &&
 +                  (unsigned)pt.x < (unsigned)size.p[1] &&
 +                 type() == DataType<_Tp>::type );
 +    return ((const _Tp*)(data + step.p[0] * pt.y))[pt.x];
 +}
 +
 +template<typename _Tp> inline
 +_Tp& Mat_<_Tp>::operator ()(const int* idx)
 +{
 +    return Mat::at<_Tp>(idx);
 +}
 +
 +template<typename _Tp> inline
 +const _Tp& Mat_<_Tp>::operator ()(const int* idx) const
 +{
 +    return Mat::at<_Tp>(idx);
 +}
 +
 +template<typename _Tp> template<int n> inline
 +_Tp& Mat_<_Tp>::operator ()(const Vec<int, n>& idx)
 +{
 +    return Mat::at<_Tp>(idx);
 +}
 +
 +template<typename _Tp> template<int n> inline
 +const _Tp& Mat_<_Tp>::operator ()(const Vec<int, n>& idx) const
 +{
 +    return Mat::at<_Tp>(idx);
 +}
 +
 +template<typename _Tp> inline
 +_Tp& Mat_<_Tp>::operator ()(int i0)
 +{
 +    return this->at<_Tp>(i0);
 +}
 +
 +template<typename _Tp> inline
 +const _Tp& Mat_<_Tp>::operator ()(int i0) const
 +{
 +    return this->at<_Tp>(i0);
 +}
 +
 +template<typename _Tp> inline
 +_Tp& Mat_<_Tp>::operator ()(int i0, int i1, int i2)
 +{
 +    return this->at<_Tp>(i0, i1, i2);
 +}
 +
 +template<typename _Tp> inline
 +const _Tp& Mat_<_Tp>::operator ()(int i0, int i1, int i2) const
 +{
 +    return this->at<_Tp>(i0, i1, i2);
 +}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>::operator std::vector<_Tp>() const
 +{
 +    std::vector<_Tp> v;
 +    copyTo(v);
 +    return v;
 +}
 +
 +template<typename _Tp> template<int n> inline
 +Mat_<_Tp>::operator Vec<typename DataType<_Tp>::channel_type, n>() const
 +{
 +    CV_Assert(n % DataType<_Tp>::channels == 0);
 +    return this->Mat::operator Vec<typename DataType<_Tp>::channel_type, n>();
 +}
 +
 +template<typename _Tp> template<int m, int n> inline
 +Mat_<_Tp>::operator Matx<typename DataType<_Tp>::channel_type, m, n>() const
 +{
 +    CV_Assert(n % DataType<_Tp>::channels == 0);
 +    return this->Mat::operator Matx<typename DataType<_Tp>::channel_type, m, n>();
 +}
 +
 +template<typename _Tp> inline
 +MatConstIterator_<_Tp> Mat_<_Tp>::begin() const
 +{
 +    return Mat::begin<_Tp>();
 +}
 +
 +template<typename _Tp> inline
 +MatConstIterator_<_Tp> Mat_<_Tp>::end() const
 +{
 +    return Mat::end<_Tp>();
 +}
 +
 +template<typename _Tp> inline
 +MatIterator_<_Tp> Mat_<_Tp>::begin()
 +{
 +    return Mat::begin<_Tp>();
 +}
 +
 +template<typename _Tp> inline
 +MatIterator_<_Tp> Mat_<_Tp>::end()
 +{
 +    return Mat::end<_Tp>();
 +}
 +
 +
 +/*template<typename T1, typename T2, typename Op> inline
 +void process( const Mat_<T1>& m1, Mat_<T2>& m2, Op op )
 +{
 +    int y, x, rows = m1.rows, cols = m1.cols;
 +
 +    CV_DbgAssert( m1.size() == m2.size() );
 +
 +    for( y = 0; y < rows; y++ )
 +    {
 +        const T1* src = m1[y];
 +        T2* dst = m2[y];
 +
 +        for( x = 0; x < cols; x++ )
 +            dst[x] = op(src[x]);
 +    }
 +}
 +
 +template<typename T1, typename T2, typename T3, typename Op> inline
 +void process( const Mat_<T1>& m1, const Mat_<T2>& m2, Mat_<T3>& m3, Op op )
 +{
 +    int y, x, rows = m1.rows, cols = m1.cols;
 +
 +    CV_DbgAssert( m1.size() == m2.size() );
 +
 +    for( y = 0; y < rows; y++ )
 +    {
 +        const T1* src1 = m1[y];
 +        const T2* src2 = m2[y];
 +        T3* dst = m3[y];
 +
 +        for( x = 0; x < cols; x++ )
 +            dst[x] = op( src1[x], src2[x] );
 +    }
 +}*/
 +
 +
 +
 +///////////////////////////// SparseMat /////////////////////////////
 +
 +inline
 +SparseMat::SparseMat()
 +    : flags(MAGIC_VAL), hdr(0)
 +{}
 +
 +inline
 +SparseMat::SparseMat(int _dims, const int* _sizes, int _type)
 +    : flags(MAGIC_VAL), hdr(0)
 +{
 +    create(_dims, _sizes, _type);
 +}
 +
 +inline
 +SparseMat::SparseMat(const SparseMat& m)
 +    : flags(m.flags), hdr(m.hdr)
 +{
 +    addref();
 +}
 +
 +inline
 +SparseMat::~SparseMat()
 +{
 +    release();
 +}
 +
 +inline
 +SparseMat& SparseMat::operator = (const SparseMat& m)
 +{
 +    if( this != &m )
 +    {
 +        if( m.hdr )
 +            CV_XADD(&m.hdr->refcount, 1);
 +        release();
 +        flags = m.flags;
 +        hdr = m.hdr;
 +    }
 +    return *this;
 +}
 +
 +inline
 +SparseMat& SparseMat::operator = (const Mat& m)
 +{
 +    return (*this = SparseMat(m));
 +}
 +
 +inline
 +SparseMat SparseMat::clone() const
 +{
 +    SparseMat temp;
 +    this->copyTo(temp);
 +    return temp;
 +}
 +
 +inline
 +void SparseMat::assignTo( SparseMat& m, int _type ) const
 +{
 +    if( _type < 0 )
 +        m = *this;
 +    else
 +        convertTo(m, _type);
 +}
 +
 +inline
 +void SparseMat::addref()
 +{
 +    if( hdr )
 +        CV_XADD(&hdr->refcount, 1);
 +}
 +
 +inline
 +void SparseMat::release()
 +{
 +    if( hdr && CV_XADD(&hdr->refcount, -1) == 1 )
 +        delete hdr;
 +    hdr = 0;
 +}
 +
 +inline
 +size_t SparseMat::elemSize() const
 +{
 +    return CV_ELEM_SIZE(flags);
 +}
 +
 +inline
 +size_t SparseMat::elemSize1() const
 +{
 +    return CV_ELEM_SIZE1(flags);
 +}
 +
 +inline
 +int SparseMat::type() const
 +{
 +    return CV_MAT_TYPE(flags);
 +}
 +
 +inline
 +int SparseMat::depth() const
 +{
 +    return CV_MAT_DEPTH(flags);
 +}
 +
 +inline
 +int SparseMat::channels() const
 +{
 +    return CV_MAT_CN(flags);
 +}
 +
 +inline
 +const int* SparseMat::size() const
 +{
 +    return hdr ? hdr->size : 0;
 +}
 +
 +inline
 +int SparseMat::size(int i) const
 +{
 +    if( hdr )
 +    {
 +        CV_DbgAssert((unsigned)i < (unsigned)hdr->dims);
 +        return hdr->size[i];
 +    }
 +    return 0;
 +}
 +
 +inline
 +int SparseMat::dims() const
 +{
 +    return hdr ? hdr->dims : 0;
 +}
 +
 +inline
 +size_t SparseMat::nzcount() const
 +{
 +    return hdr ? hdr->nodeCount : 0;
 +}
 +
 +inline
 +size_t SparseMat::hash(int i0) const
 +{
 +    return (size_t)i0;
 +}
 +
 +inline
 +size_t SparseMat::hash(int i0, int i1) const
 +{
 +    return (size_t)(unsigned)i0 * HASH_SCALE + (unsigned)i1;
 +}
 +
 +inline
 +size_t SparseMat::hash(int i0, int i1, int i2) const
 +{
 +    return ((size_t)(unsigned)i0 * HASH_SCALE + (unsigned)i1) * HASH_SCALE + (unsigned)i2;
 +}
 +
 +inline
 +size_t SparseMat::hash(const int* idx) const
 +{
 +    size_t h = (unsigned)idx[0];
 +    if( !hdr )
 +        return 0;
 +    int d = hdr->dims;
 +    for(int i = 1; i < d; i++ )
 +        h = h * HASH_SCALE + (unsigned)idx[i];
 +    return h;
 +}
 +
 +template<typename _Tp> inline
 +_Tp& SparseMat::ref(int i0, size_t* hashval)
 +{
 +    return *(_Tp*)((SparseMat*)this)->ptr(i0, true, hashval);
 +}
 +
 +template<typename _Tp> inline
 +_Tp& SparseMat::ref(int i0, int i1, size_t* hashval)
 +{
 +    return *(_Tp*)((SparseMat*)this)->ptr(i0, i1, true, hashval);
 +}
 +
 +template<typename _Tp> inline
 +_Tp& SparseMat::ref(int i0, int i1, int i2, size_t* hashval)
 +{
 +    return *(_Tp*)((SparseMat*)this)->ptr(i0, i1, i2, true, hashval);
 +}
 +
 +template<typename _Tp> inline
 +_Tp& SparseMat::ref(const int* idx, size_t* hashval)
 +{
 +    return *(_Tp*)((SparseMat*)this)->ptr(idx, true, hashval);
 +}
 +
 +template<typename _Tp> inline
 +_Tp SparseMat::value(int i0, size_t* hashval) const
 +{
 +    const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, false, hashval);
 +    return p ? *p : _Tp();
 +}
 +
 +template<typename _Tp> inline
 +_Tp SparseMat::value(int i0, int i1, size_t* hashval) const
 +{
 +    const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, i1, false, hashval);
 +    return p ? *p : _Tp();
 +}
 +
 +template<typename _Tp> inline
 +_Tp SparseMat::value(int i0, int i1, int i2, size_t* hashval) const
 +{
 +    const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, i1, i2, false, hashval);
 +    return p ? *p : _Tp();
 +}
 +
 +template<typename _Tp> inline
 +_Tp SparseMat::value(const int* idx, size_t* hashval) const
 +{
 +    const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(idx, false, hashval);
 +    return p ? *p : _Tp();
 +}
 +
 +template<typename _Tp> inline
 +const _Tp* SparseMat::find(int i0, size_t* hashval) const
 +{
 +    return (const _Tp*)((SparseMat*)this)->ptr(i0, false, hashval);
 +}
 +
 +template<typename _Tp> inline
 +const _Tp* SparseMat::find(int i0, int i1, size_t* hashval) const
 +{
 +    return (const _Tp*)((SparseMat*)this)->ptr(i0, i1, false, hashval);
 +}
 +
 +template<typename _Tp> inline
 +const _Tp* SparseMat::find(int i0, int i1, int i2, size_t* hashval) const
 +{
 +    return (const _Tp*)((SparseMat*)this)->ptr(i0, i1, i2, false, hashval);
 +}
 +
 +template<typename _Tp> inline
 +const _Tp* SparseMat::find(const int* idx, size_t* hashval) const
 +{
 +    return (const _Tp*)((SparseMat*)this)->ptr(idx, false, hashval);
 +}
 +
 +template<typename _Tp> inline
 +_Tp& SparseMat::value(Node* n)
 +{
 +    return *(_Tp*)((uchar*)n + hdr->valueOffset);
 +}
 +
 +template<typename _Tp> inline
 +const _Tp& SparseMat::value(const Node* n) const
 +{
 +    return *(const _Tp*)((const uchar*)n + hdr->valueOffset);
 +}
 +
 +inline
 +SparseMat::Node* SparseMat::node(size_t nidx)
 +{
-     return (const Node*)&hdr->pool[nidx];
++    return (Node*)(void*)&hdr->pool[nidx];
 +}
 +
 +inline
 +const SparseMat::Node* SparseMat::node(size_t nidx) const
 +{
-     return (ptr && m && m->hdr) ? (const SparseMat::Node*)(ptr - m->hdr->valueOffset) : 0;
++    return (const Node*)(const void*)&hdr->pool[nidx];
 +}
 +
 +inline
 +SparseMatIterator SparseMat::begin()
 +{
 +    return SparseMatIterator(this);
 +}
 +
 +inline
 +SparseMatConstIterator SparseMat::begin() const
 +{
 +    return SparseMatConstIterator(this);
 +}
 +
 +inline
 +SparseMatIterator SparseMat::end()
 +{
 +    SparseMatIterator it(this);
 +    it.seekEnd();
 +    return it;
 +}
 +
 +inline
 +SparseMatConstIterator SparseMat::end() const
 +{
 +    SparseMatConstIterator it(this);
 +    it.seekEnd();
 +    return it;
 +}
 +
 +template<typename _Tp> inline
 +SparseMatIterator_<_Tp> SparseMat::begin()
 +{
 +    return SparseMatIterator_<_Tp>(this);
 +}
 +
 +template<typename _Tp> inline
 +SparseMatConstIterator_<_Tp> SparseMat::begin() const
 +{
 +    return SparseMatConstIterator_<_Tp>(this);
 +}
 +
 +template<typename _Tp> inline
 +SparseMatIterator_<_Tp> SparseMat::end()
 +{
 +    SparseMatIterator_<_Tp> it(this);
 +    it.seekEnd();
 +    return it;
 +}
 +
 +template<typename _Tp> inline
 +SparseMatConstIterator_<_Tp> SparseMat::end() const
 +{
 +    SparseMatConstIterator_<_Tp> it(this);
 +    it.seekEnd();
 +    return it;
 +}
 +
 +
 +
 +///////////////////////////// SparseMat_ ////////////////////////////
 +
 +template<typename _Tp> inline
 +SparseMat_<_Tp>::SparseMat_()
 +{
 +    flags = MAGIC_VAL | DataType<_Tp>::type;
 +}
 +
 +template<typename _Tp> inline
 +SparseMat_<_Tp>::SparseMat_(int _dims, const int* _sizes)
 +    : SparseMat(_dims, _sizes, DataType<_Tp>::type)
 +{}
 +
 +template<typename _Tp> inline
 +SparseMat_<_Tp>::SparseMat_(const SparseMat& m)
 +{
 +    if( m.type() == DataType<_Tp>::type )
 +        *this = (const SparseMat_<_Tp>&)m;
 +    else
 +        m.convertTo(this, DataType<_Tp>::type);
 +}
 +
 +template<typename _Tp> inline
 +SparseMat_<_Tp>::SparseMat_(const SparseMat_<_Tp>& m)
 +{
 +    this->flags = m.flags;
 +    this->hdr = m.hdr;
 +    if( this->hdr )
 +        CV_XADD(&this->hdr->refcount, 1);
 +}
 +
 +template<typename _Tp> inline
 +SparseMat_<_Tp>::SparseMat_(const Mat& m)
 +{
 +    SparseMat sm(m);
 +    *this = sm;
 +}
 +
 +template<typename _Tp> inline
 +SparseMat_<_Tp>& SparseMat_<_Tp>::operator = (const SparseMat_<_Tp>& m)
 +{
 +    if( this != &m )
 +    {
 +        if( m.hdr ) CV_XADD(&m.hdr->refcount, 1);
 +        release();
 +        flags = m.flags;
 +        hdr = m.hdr;
 +    }
 +    return *this;
 +}
 +
 +template<typename _Tp> inline
 +SparseMat_<_Tp>& SparseMat_<_Tp>::operator = (const SparseMat& m)
 +{
 +    if( m.type() == DataType<_Tp>::type )
 +        return (*this = (const SparseMat_<_Tp>&)m);
 +    m.convertTo(*this, DataType<_Tp>::type);
 +    return *this;
 +}
 +
 +template<typename _Tp> inline
 +SparseMat_<_Tp>& SparseMat_<_Tp>::operator = (const Mat& m)
 +{
 +    return (*this = SparseMat(m));
 +}
 +
 +template<typename _Tp> inline
 +SparseMat_<_Tp> SparseMat_<_Tp>::clone() const
 +{
 +    SparseMat_<_Tp> m;
 +    this->copyTo(m);
 +    return m;
 +}
 +
 +template<typename _Tp> inline
 +void SparseMat_<_Tp>::create(int _dims, const int* _sizes)
 +{
 +    SparseMat::create(_dims, _sizes, DataType<_Tp>::type);
 +}
 +
 +template<typename _Tp> inline
 +int SparseMat_<_Tp>::type() const
 +{
 +    return DataType<_Tp>::type;
 +}
 +
 +template<typename _Tp> inline
 +int SparseMat_<_Tp>::depth() const
 +{
 +    return DataType<_Tp>::depth;
 +}
 +
 +template<typename _Tp> inline
 +int SparseMat_<_Tp>::channels() const
 +{
 +    return DataType<_Tp>::channels;
 +}
 +
 +template<typename _Tp> inline
 +_Tp& SparseMat_<_Tp>::ref(int i0, size_t* hashval)
 +{
 +    return SparseMat::ref<_Tp>(i0, hashval);
 +}
 +
 +template<typename _Tp> inline
 +_Tp SparseMat_<_Tp>::operator()(int i0, size_t* hashval) const
 +{
 +    return SparseMat::value<_Tp>(i0, hashval);
 +}
 +
 +template<typename _Tp> inline
 +_Tp& SparseMat_<_Tp>::ref(int i0, int i1, size_t* hashval)
 +{
 +    return SparseMat::ref<_Tp>(i0, i1, hashval);
 +}
 +
 +template<typename _Tp> inline
 +_Tp SparseMat_<_Tp>::operator()(int i0, int i1, size_t* hashval) const
 +{
 +    return SparseMat::value<_Tp>(i0, i1, hashval);
 +}
 +
 +template<typename _Tp> inline
 +_Tp& SparseMat_<_Tp>::ref(int i0, int i1, int i2, size_t* hashval)
 +{
 +    return SparseMat::ref<_Tp>(i0, i1, i2, hashval);
 +}
 +
 +template<typename _Tp> inline
 +_Tp SparseMat_<_Tp>::operator()(int i0, int i1, int i2, size_t* hashval) const
 +{
 +    return SparseMat::value<_Tp>(i0, i1, i2, hashval);
 +}
 +
 +template<typename _Tp> inline
 +_Tp& SparseMat_<_Tp>::ref(const int* idx, size_t* hashval)
 +{
 +    return SparseMat::ref<_Tp>(idx, hashval);
 +}
 +
 +template<typename _Tp> inline
 +_Tp SparseMat_<_Tp>::operator()(const int* idx, size_t* hashval) const
 +{
 +    return SparseMat::value<_Tp>(idx, hashval);
 +}
 +
 +template<typename _Tp> inline
 +SparseMatIterator_<_Tp> SparseMat_<_Tp>::begin()
 +{
 +    return SparseMatIterator_<_Tp>(this);
 +}
 +
 +template<typename _Tp> inline
 +SparseMatConstIterator_<_Tp> SparseMat_<_Tp>::begin() const
 +{
 +    return SparseMatConstIterator_<_Tp>(this);
 +}
 +
 +template<typename _Tp> inline
 +SparseMatIterator_<_Tp> SparseMat_<_Tp>::end()
 +{
 +    SparseMatIterator_<_Tp> it(this);
 +    it.seekEnd();
 +    return it;
 +}
 +
 +template<typename _Tp> inline
 +SparseMatConstIterator_<_Tp> SparseMat_<_Tp>::end() const
 +{
 +    SparseMatConstIterator_<_Tp> it(this);
 +    it.seekEnd();
 +    return it;
 +}
 +
 +
 +
 +////////////////////////// MatConstIterator /////////////////////////
 +
 +inline
 +MatConstIterator::MatConstIterator()
 +    : m(0), elemSize(0), ptr(0), sliceStart(0), sliceEnd(0)
 +{}
 +
 +inline
 +MatConstIterator::MatConstIterator(const Mat* _m)
 +    : m(_m), elemSize(_m->elemSize()), ptr(0), sliceStart(0), sliceEnd(0)
 +{
 +    if( m && m->isContinuous() )
 +    {
 +        sliceStart = m->data;
 +        sliceEnd = sliceStart + m->total()*elemSize;
 +    }
 +    seek((const int*)0);
 +}
 +
 +inline
 +MatConstIterator::MatConstIterator(const Mat* _m, int _row, int _col)
 +    : m(_m), elemSize(_m->elemSize()), ptr(0), sliceStart(0), sliceEnd(0)
 +{
 +    CV_Assert(m && m->dims <= 2);
 +    if( m->isContinuous() )
 +    {
 +        sliceStart = m->data;
 +        sliceEnd = sliceStart + m->total()*elemSize;
 +    }
 +    int idx[] = {_row, _col};
 +    seek(idx);
 +}
 +
 +inline
 +MatConstIterator::MatConstIterator(const Mat* _m, Point _pt)
 +    : m(_m), elemSize(_m->elemSize()), ptr(0), sliceStart(0), sliceEnd(0)
 +{
 +    CV_Assert(m && m->dims <= 2);
 +    if( m->isContinuous() )
 +    {
 +        sliceStart = m->data;
 +        sliceEnd = sliceStart + m->total()*elemSize;
 +    }
 +    int idx[] = {_pt.y, _pt.x};
 +    seek(idx);
 +}
 +
 +inline
 +MatConstIterator::MatConstIterator(const MatConstIterator& it)
 +    : m(it.m), elemSize(it.elemSize), ptr(it.ptr), sliceStart(it.sliceStart), sliceEnd(it.sliceEnd)
 +{}
 +
 +inline
 +MatConstIterator& MatConstIterator::operator = (const MatConstIterator& it )
 +{
 +    m = it.m; elemSize = it.elemSize; ptr = it.ptr;
 +    sliceStart = it.sliceStart; sliceEnd = it.sliceEnd;
 +    return *this;
 +}
 +
 +inline
 +uchar* MatConstIterator::operator *() const
 +{
 +    return ptr;
 +}
 +
 +inline MatConstIterator& MatConstIterator::operator += (ptrdiff_t ofs)
 +{
 +    if( !m || ofs == 0 )
 +        return *this;
 +    ptrdiff_t ofsb = ofs*elemSize;
 +    ptr += ofsb;
 +    if( ptr < sliceStart || sliceEnd <= ptr )
 +    {
 +        ptr -= ofsb;
 +        seek(ofs, true);
 +    }
 +    return *this;
 +}
 +
 +inline
 +MatConstIterator& MatConstIterator::operator -= (ptrdiff_t ofs)
 +{
 +    return (*this += -ofs);
 +}
 +
 +inline
 +MatConstIterator& MatConstIterator::operator --()
 +{
 +    if( m && (ptr -= elemSize) < sliceStart )
 +    {
 +        ptr += elemSize;
 +        seek(-1, true);
 +    }
 +    return *this;
 +}
 +
 +inline
 +MatConstIterator MatConstIterator::operator --(int)
 +{
 +    MatConstIterator b = *this;
 +    *this += -1;
 +    return b;
 +}
 +
 +inline
 +MatConstIterator& MatConstIterator::operator ++()
 +{
 +    if( m && (ptr += elemSize) >= sliceEnd )
 +    {
 +        ptr -= elemSize;
 +        seek(1, true);
 +    }
 +    return *this;
 +}
 +
 +inline MatConstIterator MatConstIterator::operator ++(int)
 +{
 +    MatConstIterator b = *this;
 +    *this += 1;
 +    return b;
 +}
 +
 +
 +static inline
 +bool operator == (const MatConstIterator& a, const MatConstIterator& b)
 +{
 +    return a.m == b.m && a.ptr == b.ptr;
 +}
 +
 +static inline
 +bool operator != (const MatConstIterator& a, const MatConstIterator& b)
 +{
 +    return !(a == b);
 +}
 +
 +static inline
 +bool operator < (const MatConstIterator& a, const MatConstIterator& b)
 +{
 +    return a.ptr < b.ptr;
 +}
 +
 +static inline
 +bool operator > (const MatConstIterator& a, const MatConstIterator& b)
 +{
 +    return a.ptr > b.ptr;
 +}
 +
 +static inline
 +bool operator <= (const MatConstIterator& a, const MatConstIterator& b)
 +{
 +    return a.ptr <= b.ptr;
 +}
 +
 +static inline
 +bool operator >= (const MatConstIterator& a, const MatConstIterator& b)
 +{
 +    return a.ptr >= b.ptr;
 +}
 +
 +static inline
 +ptrdiff_t operator - (const MatConstIterator& b, const MatConstIterator& a)
 +{
 +    if( a.m != b.m )
 +        return ((size_t)(-1) >> 1);
 +    if( a.sliceEnd == b.sliceEnd )
 +        return (b.ptr - a.ptr)/b.elemSize;
 +
 +    return b.lpos() - a.lpos();
 +}
 +
 +static inline
 +MatConstIterator operator + (const MatConstIterator& a, ptrdiff_t ofs)
 +{
 +    MatConstIterator b = a;
 +    return b += ofs;
 +}
 +
 +static inline
 +MatConstIterator operator + (ptrdiff_t ofs, const MatConstIterator& a)
 +{
 +    MatConstIterator b = a;
 +    return b += ofs;
 +}
 +
 +static inline
 +MatConstIterator operator - (const MatConstIterator& a, ptrdiff_t ofs)
 +{
 +    MatConstIterator b = a;
 +    return b += -ofs;
 +}
 +
 +
 +inline
 +uchar* MatConstIterator::operator [](ptrdiff_t i) const
 +{
 +    return *(*this + i);
 +}
 +
 +
 +
 +///////////////////////// MatConstIterator_ /////////////////////////
 +
 +template<typename _Tp> inline
 +MatConstIterator_<_Tp>::MatConstIterator_()
 +{}
 +
 +template<typename _Tp> inline
 +MatConstIterator_<_Tp>::MatConstIterator_(const Mat_<_Tp>* _m)
 +    : MatConstIterator(_m)
 +{}
 +
 +template<typename _Tp> inline
 +MatConstIterator_<_Tp>::MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col)
 +    : MatConstIterator(_m, _row, _col)
 +{}
 +
 +template<typename _Tp> inline
 +MatConstIterator_<_Tp>::MatConstIterator_(const Mat_<_Tp>* _m, Point _pt)
 +    : MatConstIterator(_m, _pt)
 +{}
 +
 +template<typename _Tp> inline
 +MatConstIterator_<_Tp>::MatConstIterator_(const MatConstIterator_& it)
 +    : MatConstIterator(it)
 +{}
 +
 +template<typename _Tp> inline
 +MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator = (const MatConstIterator_& it )
 +{
 +    MatConstIterator::operator = (it);
 +    return *this;
 +}
 +
 +template<typename _Tp> inline
 +_Tp MatConstIterator_<_Tp>::operator *() const
 +{
 +    return *(_Tp*)(this->ptr);
 +}
 +
 +template<typename _Tp> inline
 +MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator += (ptrdiff_t ofs)
 +{
 +    MatConstIterator::operator += (ofs);
 +    return *this;
 +}
 +
 +template<typename _Tp> inline
 +MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator -= (ptrdiff_t ofs)
 +{
 +    return (*this += -ofs);
 +}
 +
 +template<typename _Tp> inline
 +MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator --()
 +{
 +    MatConstIterator::operator --();
 +    return *this;
 +}
 +
 +template<typename _Tp> inline
 +MatConstIterator_<_Tp> MatConstIterator_<_Tp>::operator --(int)
 +{
 +    MatConstIterator_ b = *this;
 +    MatConstIterator::operator --();
 +    return b;
 +}
 +
 +template<typename _Tp> inline
 +MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator ++()
 +{
 +    MatConstIterator::operator ++();
 +    return *this;
 +}
 +
 +template<typename _Tp> inline
 +MatConstIterator_<_Tp> MatConstIterator_<_Tp>::operator ++(int)
 +{
 +    MatConstIterator_ b = *this;
 +    MatConstIterator::operator ++();
 +    return b;
 +}
 +
 +
 +template<typename _Tp> inline
 +Point MatConstIterator_<_Tp>::pos() const
 +{
 +    if( !m )
 +        return Point();
 +    CV_DbgAssert( m->dims <= 2 );
 +    if( m->isContinuous() )
 +    {
 +        ptrdiff_t ofs = (const _Tp*)ptr - (const _Tp*)m->data;
 +        int y = (int)(ofs / m->cols);
 +        int x = (int)(ofs - (ptrdiff_t)y * m->cols);
 +        return Point(x, y);
 +    }
 +    else
 +    {
 +        ptrdiff_t ofs = (uchar*)ptr - m->data;
 +        int y = (int)(ofs / m->step);
 +        int x = (int)((ofs - y * m->step)/sizeof(_Tp));
 +        return Point(x, y);
 +    }
 +}
 +
 +
 +template<typename _Tp> static inline
 +bool operator == (const MatConstIterator_<_Tp>& a, const MatConstIterator_<_Tp>& b)
 +{
 +    return a.m == b.m && a.ptr == b.ptr;
 +}
 +
 +template<typename _Tp> static inline
 +bool operator != (const MatConstIterator_<_Tp>& a, const MatConstIterator_<_Tp>& b)
 +{
 +    return a.m != b.m || a.ptr != b.ptr;
 +}
 +
 +template<typename _Tp> static inline
 +MatConstIterator_<_Tp> operator + (const MatConstIterator_<_Tp>& a, ptrdiff_t ofs)
 +{
 +    MatConstIterator t = (const MatConstIterator&)a + ofs;
 +    return (MatConstIterator_<_Tp>&)t;
 +}
 +
 +template<typename _Tp> static inline
 +MatConstIterator_<_Tp> operator + (ptrdiff_t ofs, const MatConstIterator_<_Tp>& a)
 +{
 +    MatConstIterator t = (const MatConstIterator&)a + ofs;
 +    return (MatConstIterator_<_Tp>&)t;
 +}
 +
 +template<typename _Tp> static inline
 +MatConstIterator_<_Tp> operator - (const MatConstIterator_<_Tp>& a, ptrdiff_t ofs)
 +{
 +    MatConstIterator t = (const MatConstIterator&)a - ofs;
 +    return (MatConstIterator_<_Tp>&)t;
 +}
 +
 +template<typename _Tp> inline
 +_Tp MatConstIterator_<_Tp>::operator [](ptrdiff_t i) const
 +{
 +    return *(_Tp*)MatConstIterator::operator [](i);
 +}
 +
 +
 +
 +//////////////////////////// MatIterator_ ///////////////////////////
 +
 +template<typename _Tp> inline
 +MatIterator_<_Tp>::MatIterator_()
 +    : MatConstIterator_<_Tp>()
 +{}
 +
 +template<typename _Tp> inline
 +MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m)
 +    : MatConstIterator_<_Tp>(_m)
 +{}
 +
 +template<typename _Tp> inline
 +MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m, int _row, int _col)
 +    : MatConstIterator_<_Tp>(_m, _row, _col)
 +{}
 +
 +template<typename _Tp> inline
 +MatIterator_<_Tp>::MatIterator_(const Mat_<_Tp>* _m, Point _pt)
 +    : MatConstIterator_<_Tp>(_m, _pt)
 +{}
 +
 +template<typename _Tp> inline
 +MatIterator_<_Tp>::MatIterator_(const Mat_<_Tp>* _m, const int* _idx)
 +    : MatConstIterator_<_Tp>(_m, _idx)
 +{}
 +
 +template<typename _Tp> inline
 +MatIterator_<_Tp>::MatIterator_(const MatIterator_& it)
 +    : MatConstIterator_<_Tp>(it)
 +{}
 +
 +template<typename _Tp> inline
 +MatIterator_<_Tp>& MatIterator_<_Tp>::operator = (const MatIterator_<_Tp>& it )
 +{
 +    MatConstIterator::operator = (it);
 +    return *this;
 +}
 +
 +template<typename _Tp> inline
 +_Tp& MatIterator_<_Tp>::operator *() const
 +{
 +    return *(_Tp*)(this->ptr);
 +}
 +
 +template<typename _Tp> inline
 +MatIterator_<_Tp>& MatIterator_<_Tp>::operator += (ptrdiff_t ofs)
 +{
 +    MatConstIterator::operator += (ofs);
 +    return *this;
 +}
 +
 +template<typename _Tp> inline
 +MatIterator_<_Tp>& MatIterator_<_Tp>::operator -= (ptrdiff_t ofs)
 +{
 +    MatConstIterator::operator += (-ofs);
 +    return *this;
 +}
 +
 +template<typename _Tp> inline
 +MatIterator_<_Tp>& MatIterator_<_Tp>::operator --()
 +{
 +    MatConstIterator::operator --();
 +    return *this;
 +}
 +
 +template<typename _Tp> inline
 +MatIterator_<_Tp> MatIterator_<_Tp>::operator --(int)
 +{
 +    MatIterator_ b = *this;
 +    MatConstIterator::operator --();
 +    return b;
 +}
 +
 +template<typename _Tp> inline
 +MatIterator_<_Tp>& MatIterator_<_Tp>::operator ++()
 +{
 +    MatConstIterator::operator ++();
 +    return *this;
 +}
 +
 +template<typename _Tp> inline
 +MatIterator_<_Tp> MatIterator_<_Tp>::operator ++(int)
 +{
 +    MatIterator_ b = *this;
 +    MatConstIterator::operator ++();
 +    return b;
 +}
 +
 +template<typename _Tp> inline
 +_Tp& MatIterator_<_Tp>::operator [](ptrdiff_t i) const
 +{
 +    return *(*this + i);
 +}
 +
 +
 +template<typename _Tp> static inline
 +bool operator == (const MatIterator_<_Tp>& a, const MatIterator_<_Tp>& b)
 +{
 +    return a.m == b.m && a.ptr == b.ptr;
 +}
 +
 +template<typename _Tp> static inline
 +bool operator != (const MatIterator_<_Tp>& a, const MatIterator_<_Tp>& b)
 +{
 +    return a.m != b.m || a.ptr != b.ptr;
 +}
 +
 +template<typename _Tp> static inline
 +MatIterator_<_Tp> operator + (const MatIterator_<_Tp>& a, ptrdiff_t ofs)
 +{
 +    MatConstIterator t = (const MatConstIterator&)a + ofs;
 +    return (MatIterator_<_Tp>&)t;
 +}
 +
 +template<typename _Tp> static inline
 +MatIterator_<_Tp> operator + (ptrdiff_t ofs, const MatIterator_<_Tp>& a)
 +{
 +    MatConstIterator t = (const MatConstIterator&)a + ofs;
 +    return (MatIterator_<_Tp>&)t;
 +}
 +
 +template<typename _Tp> static inline
 +MatIterator_<_Tp> operator - (const MatIterator_<_Tp>& a, ptrdiff_t ofs)
 +{
 +    MatConstIterator t = (const MatConstIterator&)a - ofs;
 +    return (MatIterator_<_Tp>&)t;
 +}
 +
 +
 +
 +/////////////////////// SparseMatConstIterator //////////////////////
 +
 +inline
 +SparseMatConstIterator::SparseMatConstIterator()
 +    : m(0), hashidx(0), ptr(0)
 +{}
 +
 +inline
 +SparseMatConstIterator::SparseMatConstIterator(const SparseMatConstIterator& it)
 +    : m(it.m), hashidx(it.hashidx), ptr(it.ptr)
 +{}
 +
 +inline SparseMatConstIterator& SparseMatConstIterator::operator = (const SparseMatConstIterator& it)
 +{
 +    if( this != &it )
 +    {
 +        m = it.m;
 +        hashidx = it.hashidx;
 +        ptr = it.ptr;
 +    }
 +    return *this;
 +}
 +
 +template<typename _Tp> inline
 +const _Tp& SparseMatConstIterator::value() const
 +{
 +    return *(_Tp*)ptr;
 +}
 +
 +inline
 +const SparseMat::Node* SparseMatConstIterator::node() const
 +{
++    return (ptr && m && m->hdr) ? (const SparseMat::Node*)(const void*)(ptr - m->hdr->valueOffset) : 0;
 +}
 +
 +inline
 +SparseMatConstIterator SparseMatConstIterator::operator ++(int)
 +{
 +    SparseMatConstIterator it = *this;
 +    ++*this;
 +    return it;
 +}
 +
 +inline
 +void SparseMatConstIterator::seekEnd()
 +{
 +    if( m && m->hdr )
 +    {
 +        hashidx = m->hdr->hashtab.size();
 +        ptr = 0;
 +    }
 +}
 +
 +
 +static inline
 +bool operator == (const SparseMatConstIterator& it1, const SparseMatConstIterator& it2)
 +{
 +    return it1.m == it2.m && it1.ptr == it2.ptr;
 +}
 +
 +static inline
 +bool operator != (const SparseMatConstIterator& it1, const SparseMatConstIterator& it2)
 +{
 +    return !(it1 == it2);
 +}
 +
 +
 +
 +///////////////////////// SparseMatIterator /////////////////////////
 +
 +inline
 +SparseMatIterator::SparseMatIterator()
 +{}
 +
 +inline
 +SparseMatIterator::SparseMatIterator(SparseMat* _m)
 +    : SparseMatConstIterator(_m)
 +{}
 +
 +inline
 +SparseMatIterator::SparseMatIterator(const SparseMatIterator& it)
 +    : SparseMatConstIterator(it)
 +{}
 +
 +inline
 +SparseMatIterator& SparseMatIterator::operator = (const SparseMatIterator& it)
 +{
 +    (SparseMatConstIterator&)*this = it;
 +    return *this;
 +}
 +
 +template<typename _Tp> inline
 +_Tp& SparseMatIterator::value() const
 +{
 +    return *(_Tp*)ptr;
 +}
 +
 +inline
 +SparseMat::Node* SparseMatIterator::node() const
 +{
 +    return (SparseMat::Node*)SparseMatConstIterator::node();
 +}
 +
 +inline
 +SparseMatIterator& SparseMatIterator::operator ++()
 +{
 +    SparseMatConstIterator::operator ++();
 +    return *this;
 +}
 +
 +inline
 +SparseMatIterator SparseMatIterator::operator ++(int)
 +{
 +    SparseMatIterator it = *this;
 +    ++*this;
 +    return it;
 +}
 +
 +
 +
 +////////////////////// SparseMatConstIterator_ //////////////////////
 +
 +template<typename _Tp> inline
 +SparseMatConstIterator_<_Tp>::SparseMatConstIterator_()
 +{}
 +
 +template<typename _Tp> inline
 +SparseMatConstIterator_<_Tp>::SparseMatConstIterator_(const SparseMat_<_Tp>* _m)
 +    : SparseMatConstIterator(_m)
 +{}
 +
 +template<typename _Tp> inline
 +SparseMatConstIterator_<_Tp>::SparseMatConstIterator_(const SparseMat* _m)
 +    : SparseMatConstIterator(_m)
 +{
 +    CV_Assert( _m->type() == DataType<_Tp>::type );
 +}
 +
 +template<typename _Tp> inline
 +SparseMatConstIterator_<_Tp>::SparseMatConstIterator_(const SparseMatConstIterator_<_Tp>& it)
 +    : SparseMatConstIterator(it)
 +{}
 +
 +template<typename _Tp> inline
 +SparseMatConstIterator_<_Tp>& SparseMatConstIterator_<_Tp>::operator = (const SparseMatConstIterator_<_Tp>& it)
 +{
 +    return reinterpret_cast<SparseMatConstIterator_<_Tp>&>
 +         (*reinterpret_cast<SparseMatConstIterator*>(this) =
 +           reinterpret_cast<const SparseMatConstIterator&>(it));
 +}
 +
 +template<typename _Tp> inline
 +const _Tp& SparseMatConstIterator_<_Tp>::operator *() const
 +{
 +    return *(const _Tp*)this->ptr;
 +}
 +
 +template<typename _Tp> inline
 +SparseMatConstIterator_<_Tp>& SparseMatConstIterator_<_Tp>::operator ++()
 +{
 +    SparseMatConstIterator::operator ++();
 +    return *this;
 +}
 +
 +template<typename _Tp> inline
 +SparseMatConstIterator_<_Tp> SparseMatConstIterator_<_Tp>::operator ++(int)
 +{
 +    SparseMatConstIterator it = *this;
 +    SparseMatConstIterator::operator ++();
 +    return it;
 +}
 +
 +
 +
 +///////////////////////// SparseMatIterator_ ////////////////////////
 +
 +template<typename _Tp> inline
 +SparseMatIterator_<_Tp>::SparseMatIterator_()
 +{}
 +
 +template<typename _Tp> inline
 +SparseMatIterator_<_Tp>::SparseMatIterator_(SparseMat_<_Tp>* _m)
 +    : SparseMatConstIterator_<_Tp>(_m)
 +{}
 +
 +template<typename _Tp> inline
 +SparseMatIterator_<_Tp>::SparseMatIterator_(SparseMat* _m)
 +    : SparseMatConstIterator_<_Tp>(_m)
 +{}
 +
 +template<typename _Tp> inline
 +SparseMatIterator_<_Tp>::SparseMatIterator_(const SparseMatIterator_<_Tp>& it)
 +    : SparseMatConstIterator_<_Tp>(it)
 +{}
 +
 +template<typename _Tp> inline
 +SparseMatIterator_<_Tp>& SparseMatIterator_<_Tp>::operator = (const SparseMatIterator_<_Tp>& it)
 +{
 +    return reinterpret_cast<SparseMatIterator_<_Tp>&>
 +         (*reinterpret_cast<SparseMatConstIterator*>(this) =
 +           reinterpret_cast<const SparseMatConstIterator&>(it));
 +}
 +
 +template<typename _Tp> inline
 +_Tp& SparseMatIterator_<_Tp>::operator *() const
 +{
 +    return *(_Tp*)this->ptr;
 +}
 +
 +template<typename _Tp> inline
 +SparseMatIterator_<_Tp>& SparseMatIterator_<_Tp>::operator ++()
 +{
 +    SparseMatConstIterator::operator ++();
 +    return *this;
 +}
 +
 +template<typename _Tp> inline
 +SparseMatIterator_<_Tp> SparseMatIterator_<_Tp>::operator ++(int)
 +{
 +    SparseMatIterator it = *this;
 +    SparseMatConstIterator::operator ++();
 +    return it;
 +}
 +
 +
 +
 +//////////////////////// MatCommaInitializer_ ///////////////////////
 +
 +template<typename _Tp> inline
 +MatCommaInitializer_<_Tp>::MatCommaInitializer_(Mat_<_Tp>* _m)
 +    : it(_m)
 +{}
 +
 +template<typename _Tp> template<typename T2> inline
 +MatCommaInitializer_<_Tp>& MatCommaInitializer_<_Tp>::operator , (T2 v)
 +{
 +    CV_DbgAssert( this->it < ((const Mat_<_Tp>*)this->it.m)->end() );
 +    *this->it = _Tp(v);
 +    ++this->it;
 +    return *this;
 +}
 +
 +template<typename _Tp> inline
 +MatCommaInitializer_<_Tp>::operator Mat_<_Tp>() const
 +{
 +    CV_DbgAssert( this->it == ((const Mat_<_Tp>*)this->it.m)->end() );
 +    return Mat_<_Tp>(*this->it.m);
 +}
 +
 +
 +template<typename _Tp, typename T2> static inline
 +MatCommaInitializer_<_Tp> operator << (const Mat_<_Tp>& m, T2 val)
 +{
 +    MatCommaInitializer_<_Tp> commaInitializer((Mat_<_Tp>*)&m);
 +    return (commaInitializer, val);
 +}
 +
 +
 +
 +///////////////////////// Matrix Expressions ////////////////////////
 +
 +inline
 +Mat& Mat::operator = (const MatExpr& e)
 +{
 +    e.op->assign(e, *this);
 +    return *this;
 +}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>::Mat_(const MatExpr& e)
 +{
 +    e.op->assign(e, *this, DataType<_Tp>::type);
 +}
 +
 +template<typename _Tp> inline
 +Mat_<_Tp>& Mat_<_Tp>::operator = (const MatExpr& e)
 +{
 +    e.op->assign(e, *this, DataType<_Tp>::type);
 +    return *this;
 +}
 +
 +template<typename _Tp> inline
 +MatExpr Mat_<_Tp>::zeros(int rows, int cols)
 +{
 +    return Mat::zeros(rows, cols, DataType<_Tp>::type);
 +}
 +
 +template<typename _Tp> inline
 +MatExpr Mat_<_Tp>::zeros(Size sz)
 +{
 +    return Mat::zeros(sz, DataType<_Tp>::type);
 +}
 +
 +template<typename _Tp> inline
 +MatExpr Mat_<_Tp>::ones(int rows, int cols)
 +{
 +    return Mat::ones(rows, cols, DataType<_Tp>::type);
 +}
 +
 +template<typename _Tp> inline
 +MatExpr Mat_<_Tp>::ones(Size sz)
 +{
 +    return Mat::ones(sz, DataType<_Tp>::type);
 +}
 +
 +template<typename _Tp> inline
 +MatExpr Mat_<_Tp>::eye(int rows, int cols)
 +{
 +    return Mat::eye(rows, cols, DataType<_Tp>::type);
 +}
 +
 +template<typename _Tp> inline
 +MatExpr Mat_<_Tp>::eye(Size sz)
 +{
 +    return Mat::eye(sz, DataType<_Tp>::type);
 +}
 +
 +inline
 +MatExpr::MatExpr()
 +    : op(0), flags(0), a(Mat()), b(Mat()), c(Mat()), alpha(0), beta(0), s()
 +{}
 +
 +inline
 +MatExpr::MatExpr(const MatOp* _op, int _flags, const Mat& _a, const Mat& _b,
 +                 const Mat& _c, double _alpha, double _beta, const Scalar& _s)
 +    : op(_op), flags(_flags), a(_a), b(_b), c(_c), alpha(_alpha), beta(_beta), s(_s)
 +{}
 +
 +inline
 +MatExpr::operator Mat() const
 +{
 +    Mat m;
 +    op->assign(*this, m);
 +    return m;
 +}
 +
 +template<typename _Tp> inline
 +MatExpr::operator Mat_<_Tp>() const
 +{
 +    Mat_<_Tp> m;
 +    op->assign(*this, m, DataType<_Tp>::type);
 +    return m;
 +}
 +
 +
 +template<typename _Tp> static inline
 +MatExpr min(const Mat_<_Tp>& a, const Mat_<_Tp>& b)
 +{
 +    return cv::min((const Mat&)a, (const Mat&)b);
 +}
 +
 +template<typename _Tp> static inline
 +MatExpr min(const Mat_<_Tp>& a, double s)
 +{
 +    return cv::min((const Mat&)a, s);
 +}
 +
 +template<typename _Tp> static inline
 +MatExpr min(double s, const Mat_<_Tp>& a)
 +{
 +    return cv::min((const Mat&)a, s);
 +}
 +
 +template<typename _Tp> static inline
 +MatExpr max(const Mat_<_Tp>& a, const Mat_<_Tp>& b)
 +{
 +    return cv::max((const Mat&)a, (const Mat&)b);
 +}
 +
 +template<typename _Tp> static inline
 +MatExpr max(const Mat_<_Tp>& a, double s)
 +{
 +    return cv::max((const Mat&)a, s);
 +}
 +
 +template<typename _Tp> static inline
 +MatExpr max(double s, const Mat_<_Tp>& a)
 +{
 +    return cv::max((const Mat&)a, s);
 +}
 +
 +template<typename _Tp> static inline
 +MatExpr abs(const Mat_<_Tp>& m)
 +{
 +    return cv::abs((const Mat&)m);
 +}
 +
 +
 +static inline
 +Mat& operator += (Mat& a, const MatExpr& b)
 +{
 +    b.op->augAssignAdd(b, a);
 +    return a;
 +}
 +
 +static inline
 +const Mat& operator += (const Mat& a, const MatExpr& b)
 +{
 +    b.op->augAssignAdd(b, (Mat&)a);
 +    return a;
 +}
 +
 +template<typename _Tp> static inline
 +Mat_<_Tp>& operator += (Mat_<_Tp>& a, const MatExpr& b)
 +{
 +    b.op->augAssignAdd(b, a);
 +    return a;
 +}
 +
 +template<typename _Tp> static inline
 +const Mat_<_Tp>& operator += (const Mat_<_Tp>& a, const MatExpr& b)
 +{
 +    b.op->augAssignAdd(b, (Mat&)a);
 +    return a;
 +}
 +
 +static inline
 +Mat& operator -= (Mat& a, const MatExpr& b)
 +{
 +    b.op->augAssignSubtract(b, a);
 +    return a;
 +}
 +
 +static inline
 +const Mat& operator -= (const Mat& a, const MatExpr& b)
 +{
 +    b.op->augAssignSubtract(b, (Mat&)a);
 +    return a;
 +}
 +
 +template<typename _Tp> static inline
 +Mat_<_Tp>& operator -= (Mat_<_Tp>& a, const MatExpr& b)
 +{
 +    b.op->augAssignSubtract(b, a);
 +    return a;
 +}
 +
 +template<typename _Tp> static inline
 +const Mat_<_Tp>& operator -= (const Mat_<_Tp>& a, const MatExpr& b)
 +{
 +    b.op->augAssignSubtract(b, (Mat&)a);
 +    return a;
 +}
 +
 +static inline
 +Mat& operator *= (Mat& a, const MatExpr& b)
 +{
 +    b.op->augAssignMultiply(b, a);
 +    return a;
 +}
 +
 +static inline
 +const Mat& operator *= (const Mat& a, const MatExpr& b)
 +{
 +    b.op->augAssignMultiply(b, (Mat&)a);
 +    return a;
 +}
 +
 +template<typename _Tp> static inline
 +Mat_<_Tp>& operator *= (Mat_<_Tp>& a, const MatExpr& b)
 +{
 +    b.op->augAssignMultiply(b, a);
 +    return a;
 +}
 +
 +template<typename _Tp> static inline
 +const Mat_<_Tp>& operator *= (const Mat_<_Tp>& a, const MatExpr& b)
 +{
 +    b.op->augAssignMultiply(b, (Mat&)a);
 +    return a;
 +}
 +
 +static inline
 +Mat& operator /= (Mat& a, const MatExpr& b)
 +{
 +    b.op->augAssignDivide(b, a);
 +    return a;
 +}
 +
 +static inline
 +const Mat& operator /= (const Mat& a, const MatExpr& b)
 +{
 +    b.op->augAssignDivide(b, (Mat&)a);
 +    return a;
 +}
 +
 +template<typename _Tp> static inline
 +Mat_<_Tp>& operator /= (Mat_<_Tp>& a, const MatExpr& b)
 +{
 +    b.op->augAssignDivide(b, a);
 +    return a;
 +}
 +
 +template<typename _Tp> static inline
 +const Mat_<_Tp>& operator /= (const Mat_<_Tp>& a, const MatExpr& b)
 +{
 +    b.op->augAssignDivide(b, (Mat&)a);
 +    return a;
 +}
 +
 +} //cv
 +
 +#endif
index f568761,0000000..8f515c5
mode 100644,000000..100644
--- /dev/null
@@@ -1,870 -1,0 +1,870 @@@
- inline FileNode FileNodeIterator::operator *() const  { return FileNode(fs, (const CvFileNode*)reader.ptr); }
- inline FileNode FileNodeIterator::operator ->() const { return FileNode(fs, (const CvFileNode*)reader.ptr); }
 +/*M///////////////////////////////////////////////////////////////////////////////////////
 +//
 +//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
 +//
 +//  By downloading, copying, installing or using the software you agree to this license.
 +//  If you do not agree to this license, do not download, install,
 +//  copy or use the software.
 +//
 +//
 +//                          License Agreement
 +//                For Open Source Computer Vision Library
 +//
 +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
 +// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
 +// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
 +// Third party copyrights are property of their respective owners.
 +//
 +// Redistribution and use in source and binary forms, with or without modification,
 +// are permitted provided that the following conditions are met:
 +//
 +//   * Redistribution's of source code must retain the above copyright notice,
 +//     this list of conditions and the following disclaimer.
 +//
 +//   * Redistribution's in binary form must reproduce the above copyright notice,
 +//     this list of conditions and the following disclaimer in the documentation
 +//     and/or other materials provided with the distribution.
 +//
 +//   * The name of the copyright holders may not be used to endorse or promote products
 +//     derived from this software without specific prior written permission.
 +//
 +// This software is provided by the copyright holders and contributors "as is" and
 +// any express or implied warranties, including, but not limited to, the implied
 +// warranties of merchantability and fitness for a particular purpose are disclaimed.
 +// In no event shall the Intel Corporation or contributors be liable for any direct,
 +// indirect, incidental, special, exemplary, or consequential damages
 +// (including, but not limited to, procurement of substitute goods or services;
 +// loss of use, data, or profits; or business interruption) however caused
 +// and on any theory of liability, whether in contract, strict liability,
 +// or tort (including negligence or otherwise) arising in any way out of
 +// the use of this software, even if advised of the possibility of such damage.
 +//
 +//M*/
 +
 +#ifndef __OPENCV_CORE_PERSISTENCE_HPP__
 +#define __OPENCV_CORE_PERSISTENCE_HPP__
 +
 +#ifndef __cplusplus
 +#  error persistence.hpp header must be compiled as C++
 +#endif
 +
 +// black-box structures used by FileStorage
 +typedef struct CvFileStorage CvFileStorage;
 +typedef struct CvFileNode CvFileNode;
 +
 +#include "opencv2/core/types.hpp"
 +#include "opencv2/core/mat.hpp"
 +
 +namespace cv {
 +
 +////////////////////////// XML & YAML I/O //////////////////////////
 +
 +class CV_EXPORTS FileNode;
 +class CV_EXPORTS FileNodeIterator;
 +
 +/*!
 + XML/YAML File Storage Class.
 +
 + The class describes an object associated with XML or YAML file.
 + It can be used to store data to such a file or read and decode the data.
 +
 + The storage is organized as a tree of nested sequences (or lists) and mappings.
 + Sequence is a heterogenious array, which elements are accessed by indices or sequentially using an iterator.
 + Mapping is analogue of std::map or C structure, which elements are accessed by names.
 + The most top level structure is a mapping.
 + Leaves of the file storage tree are integers, floating-point numbers and text strings.
 +
 + For example, the following code:
 +
 + \code
 + // open file storage for writing. Type of the file is determined from the extension
 + FileStorage fs("test.yml", FileStorage::WRITE);
 + fs << "test_int" << 5 << "test_real" << 3.1 << "test_string" << "ABCDEFGH";
 + fs << "test_mat" << Mat::eye(3,3,CV_32F);
 +
 + fs << "test_list" << "[" << 0.0000000000001 << 2 << CV_PI << -3435345 << "2-502 2-029 3egegeg" <<
 + "{:" << "month" << 12 << "day" << 31 << "year" << 1969 << "}" << "]";
 + fs << "test_map" << "{" << "x" << 1 << "y" << 2 << "width" << 100 << "height" << 200 << "lbp" << "[:";
 +
 + const uchar arr[] = {0, 1, 1, 0, 1, 1, 0, 1};
 + fs.writeRaw("u", arr, (int)(sizeof(arr)/sizeof(arr[0])));
 +
 + fs << "]" << "}";
 + \endcode
 +
 + will produce the following file:
 +
 + \verbatim
 + %YAML:1.0
 + test_int: 5
 + test_real: 3.1000000000000001e+00
 + test_string: ABCDEFGH
 + test_mat: !!opencv-matrix
 +     rows: 3
 +     cols: 3
 +     dt: f
 +     data: [ 1., 0., 0., 0., 1., 0., 0., 0., 1. ]
 + test_list:
 +     - 1.0000000000000000e-13
 +     - 2
 +     - 3.1415926535897931e+00
 +     - -3435345
 +     - "2-502 2-029 3egegeg"
 +     - { month:12, day:31, year:1969 }
 + test_map:
 +     x: 1
 +     y: 2
 +     width: 100
 +     height: 200
 +     lbp: [ 0, 1, 1, 0, 1, 1, 0, 1 ]
 + \endverbatim
 +
 + and to read the file above, the following code can be used:
 +
 + \code
 + // open file storage for reading.
 + // Type of the file is determined from the content, not the extension
 + FileStorage fs("test.yml", FileStorage::READ);
 + int test_int = (int)fs["test_int"];
 + double test_real = (double)fs["test_real"];
 + String test_string = (String)fs["test_string"];
 +
 + Mat M;
 + fs["test_mat"] >> M;
 +
 + FileNode tl = fs["test_list"];
 + CV_Assert(tl.type() == FileNode::SEQ && tl.size() == 6);
 + double tl0 = (double)tl[0];
 + int tl1 = (int)tl[1];
 + double tl2 = (double)tl[2];
 + int tl3 = (int)tl[3];
 + String tl4 = (String)tl[4];
 + CV_Assert(tl[5].type() == FileNode::MAP && tl[5].size() == 3);
 +
 + int month = (int)tl[5]["month"];
 + int day = (int)tl[5]["day"];
 + int year = (int)tl[5]["year"];
 +
 + FileNode tm = fs["test_map"];
 +
 + int x = (int)tm["x"];
 + int y = (int)tm["y"];
 + int width = (int)tm["width"];
 + int height = (int)tm["height"];
 +
 + int lbp_val = 0;
 + FileNodeIterator it = tm["lbp"].begin();
 +
 + for(int k = 0; k < 8; k++, ++it)
 +    lbp_val |= ((int)*it) << k;
 + \endcode
 +*/
 +class CV_EXPORTS_W FileStorage
 +{
 +public:
 +    //! file storage mode
 +    enum
 +    {
 +        READ        = 0, //! read mode
 +        WRITE       = 1, //! write mode
 +        APPEND      = 2, //! append mode
 +        MEMORY      = 4,
 +        FORMAT_MASK = (7<<3),
 +        FORMAT_AUTO = 0,
 +        FORMAT_XML  = (1<<3),
 +        FORMAT_YAML = (2<<3)
 +    };
 +    enum
 +    {
 +        UNDEFINED      = 0,
 +        VALUE_EXPECTED = 1,
 +        NAME_EXPECTED  = 2,
 +        INSIDE_MAP     = 4
 +    };
 +    //! the default constructor
 +    CV_WRAP FileStorage();
 +    //! the full constructor that opens file storage for reading or writing
 +    CV_WRAP FileStorage(const String& source, int flags, const String& encoding=String());
 +    //! the constructor that takes pointer to the C FileStorage structure
 +    FileStorage(CvFileStorage* fs, bool owning=true);
 +    //! the destructor. calls release()
 +    virtual ~FileStorage();
 +
 +    //! opens file storage for reading or writing. The previous storage is closed with release()
 +    CV_WRAP virtual bool open(const String& filename, int flags, const String& encoding=String());
 +    //! returns true if the object is associated with currently opened file.
 +    CV_WRAP virtual bool isOpened() const;
 +    //! closes the file and releases all the memory buffers
 +    CV_WRAP virtual void release();
 +    //! closes the file, releases all the memory buffers and returns the text string
 +    CV_WRAP virtual String releaseAndGetString();
 +
 +    //! returns the first element of the top-level mapping
 +    CV_WRAP FileNode getFirstTopLevelNode() const;
 +    //! returns the top-level mapping. YAML supports multiple streams
 +    CV_WRAP FileNode root(int streamidx=0) const;
 +    //! returns the specified element of the top-level mapping
 +    FileNode operator[](const String& nodename) const;
 +    //! returns the specified element of the top-level mapping
 +    CV_WRAP FileNode operator[](const char* nodename) const;
 +
 +    //! returns pointer to the underlying C FileStorage structure
 +    CvFileStorage* operator *() { return fs.get(); }
 +    //! returns pointer to the underlying C FileStorage structure
 +    const CvFileStorage* operator *() const { return fs.get(); }
 +    //! writes one or more numbers of the specified format to the currently written structure
 +    void writeRaw( const String& fmt, const uchar* vec, size_t len );
 +    //! writes the registered C structure (CvMat, CvMatND, CvSeq). See cvWrite()
 +    void writeObj( const String& name, const void* obj );
 +
 +    //! returns the normalized object name for the specified file name
 +    static String getDefaultObjectName(const String& filename);
 +
 +    Ptr<CvFileStorage> fs; //!< the underlying C FileStorage structure
 +    String elname; //!< the currently written element
 +    std::vector<char> structs; //!< the stack of written structures
 +    int state; //!< the writer state
 +};
 +
 +template<> CV_EXPORTS void DefaultDeleter<CvFileStorage>::operator ()(CvFileStorage* obj) const;
 +
 +/*!
 + File Storage Node class
 +
 + The node is used to store each and every element of the file storage opened for reading -
 + from the primitive objects, such as numbers and text strings, to the complex nodes:
 + sequences, mappings and the registered objects.
 +
 + Note that file nodes are only used for navigating file storages opened for reading.
 + When a file storage is opened for writing, no data is stored in memory after it is written.
 +*/
 +class CV_EXPORTS_W_SIMPLE FileNode
 +{
 +public:
 +    //! type of the file storage node
 +    enum
 +    {
 +        NONE      = 0, //!< empty node
 +        INT       = 1, //!< an integer
 +        REAL      = 2, //!< floating-point number
 +        FLOAT     = REAL, //!< synonym or REAL
 +        STR       = 3, //!< text string in UTF-8 encoding
 +        STRING    = STR, //!< synonym for STR
 +        REF       = 4, //!< integer of size size_t. Typically used for storing complex dynamic structures where some elements reference the others
 +        SEQ       = 5, //!< sequence
 +        MAP       = 6, //!< mapping
 +        TYPE_MASK = 7,
 +        FLOW      = 8,  //!< compact representation of a sequence or mapping. Used only by YAML writer
 +        USER      = 16, //!< a registered object (e.g. a matrix)
 +        EMPTY     = 32, //!< empty structure (sequence or mapping)
 +        NAMED     = 64  //!< the node has a name (i.e. it is element of a mapping)
 +    };
 +    //! the default constructor
 +    CV_WRAP FileNode();
 +    //! the full constructor wrapping CvFileNode structure.
 +    FileNode(const CvFileStorage* fs, const CvFileNode* node);
 +    //! the copy constructor
 +    FileNode(const FileNode& node);
 +    //! returns element of a mapping node
 +    FileNode operator[](const String& nodename) const;
 +    //! returns element of a mapping node
 +    CV_WRAP FileNode operator[](const char* nodename) const;
 +    //! returns element of a sequence node
 +    CV_WRAP FileNode operator[](int i) const;
 +    //! returns type of the node
 +    CV_WRAP int type() const;
 +
 +    //! returns true if the node is empty
 +    CV_WRAP bool empty() const;
 +    //! returns true if the node is a "none" object
 +    CV_WRAP bool isNone() const;
 +    //! returns true if the node is a sequence
 +    CV_WRAP bool isSeq() const;
 +    //! returns true if the node is a mapping
 +    CV_WRAP bool isMap() const;
 +    //! returns true if the node is an integer
 +    CV_WRAP bool isInt() const;
 +    //! returns true if the node is a floating-point number
 +    CV_WRAP bool isReal() const;
 +    //! returns true if the node is a text string
 +    CV_WRAP bool isString() const;
 +    //! returns true if the node has a name
 +    CV_WRAP bool isNamed() const;
 +    //! returns the node name or an empty string if the node is nameless
 +    CV_WRAP String name() const;
 +    //! returns the number of elements in the node, if it is a sequence or mapping, or 1 otherwise.
 +    CV_WRAP size_t size() const;
 +    //! returns the node content as an integer. If the node stores floating-point number, it is rounded.
 +    operator int() const;
 +    //! returns the node content as float
 +    operator float() const;
 +    //! returns the node content as double
 +    operator double() const;
 +    //! returns the node content as text string
 +    operator String() const;
 +#ifndef OPENCV_NOSTL
 +    operator std::string() const;
 +#endif
 +
 +    //! returns pointer to the underlying file node
 +    CvFileNode* operator *();
 +    //! returns pointer to the underlying file node
 +    const CvFileNode* operator* () const;
 +
 +    //! returns iterator pointing to the first node element
 +    FileNodeIterator begin() const;
 +    //! returns iterator pointing to the element following the last node element
 +    FileNodeIterator end() const;
 +
 +    //! reads node elements to the buffer with the specified format
 +    void readRaw( const String& fmt, uchar* vec, size_t len ) const;
 +    //! reads the registered object and returns pointer to it
 +    void* readObj() const;
 +
 +    // do not use wrapper pointer classes for better efficiency
 +    const CvFileStorage* fs;
 +    const CvFileNode* node;
 +};
 +
 +
 +/*!
 + File Node Iterator
 +
 + The class is used for iterating sequences (usually) and mappings.
 + */
 +class CV_EXPORTS FileNodeIterator
 +{
 +public:
 +    //! the default constructor
 +    FileNodeIterator();
 +    //! the full constructor set to the ofs-th element of the node
 +    FileNodeIterator(const CvFileStorage* fs, const CvFileNode* node, size_t ofs=0);
 +    //! the copy constructor
 +    FileNodeIterator(const FileNodeIterator& it);
 +    //! returns the currently observed element
 +    FileNode operator *() const;
 +    //! accesses the currently observed element methods
 +    FileNode operator ->() const;
 +
 +    //! moves iterator to the next node
 +    FileNodeIterator& operator ++ ();
 +    //! moves iterator to the next node
 +    FileNodeIterator operator ++ (int);
 +    //! moves iterator to the previous node
 +    FileNodeIterator& operator -- ();
 +    //! moves iterator to the previous node
 +    FileNodeIterator operator -- (int);
 +    //! moves iterator forward by the specified offset (possibly negative)
 +    FileNodeIterator& operator += (int ofs);
 +    //! moves iterator backward by the specified offset (possibly negative)
 +    FileNodeIterator& operator -= (int ofs);
 +
 +    //! reads the next maxCount elements (or less, if the sequence/mapping last element occurs earlier) to the buffer with the specified format
 +    FileNodeIterator& readRaw( const String& fmt, uchar* vec,
 +                               size_t maxCount=(size_t)INT_MAX );
 +
 +    struct SeqReader
 +    {
 +      int          header_size;
 +      void*        seq;        /* sequence, beign read; CvSeq      */
 +      void*        block;      /* current block;        CvSeqBlock */
 +      schar*       ptr;        /* pointer to element be read next */
 +      schar*       block_min;  /* pointer to the beginning of block */
 +      schar*       block_max;  /* pointer to the end of block */
 +      int          delta_index;/* = seq->first->start_index   */
 +      schar*       prev_elem;  /* pointer to previous element */
 +    };
 +
 +    const CvFileStorage* fs;
 +    const CvFileNode* container;
 +    SeqReader reader;
 +    size_t remaining;
 +};
 +
 +
 +
 +/////////////////// XML & YAML I/O implementation //////////////////
 +
 +CV_EXPORTS void write( FileStorage& fs, const String& name, int value );
 +CV_EXPORTS void write( FileStorage& fs, const String& name, float value );
 +CV_EXPORTS void write( FileStorage& fs, const String& name, double value );
 +CV_EXPORTS void write( FileStorage& fs, const String& name, const String& value );
 +CV_EXPORTS void write( FileStorage& fs, const String& name, const Mat& value );
 +CV_EXPORTS void write( FileStorage& fs, const String& name, const SparseMat& value );
 +CV_EXPORTS void write( FileStorage& fs, const String& name, const std::vector<KeyPoint>& value);
 +
 +CV_EXPORTS void writeScalar( FileStorage& fs, int value );
 +CV_EXPORTS void writeScalar( FileStorage& fs, float value );
 +CV_EXPORTS void writeScalar( FileStorage& fs, double value );
 +CV_EXPORTS void writeScalar( FileStorage& fs, const String& value );
 +
 +CV_EXPORTS void read(const FileNode& node, int& value, int default_value);
 +CV_EXPORTS void read(const FileNode& node, float& value, float default_value);
 +CV_EXPORTS void read(const FileNode& node, double& value, double default_value);
 +CV_EXPORTS void read(const FileNode& node, String& value, const String& default_value);
 +CV_EXPORTS void read(const FileNode& node, Mat& mat, const Mat& default_mat = Mat() );
 +CV_EXPORTS void read(const FileNode& node, SparseMat& mat, const SparseMat& default_mat = SparseMat() );
 +CV_EXPORTS void read(const FileNode& node, std::vector<KeyPoint>& keypoints);
 +
 +template<typename _Tp> static inline void read(const FileNode& node, Point_<_Tp>& value, const Point_<_Tp>& default_value)
 +{
 +    std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp;
 +    value = temp.size() != 2 ? default_value : Point_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]));
 +}
 +
 +template<typename _Tp> static inline void read(const FileNode& node, Point3_<_Tp>& value, const Point3_<_Tp>& default_value)
 +{
 +    std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp;
 +    value = temp.size() != 3 ? default_value : Point3_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]),
 +                                                            saturate_cast<_Tp>(temp[2]));
 +}
 +
 +template<typename _Tp> static inline void read(const FileNode& node, Size_<_Tp>& value, const Size_<_Tp>& default_value)
 +{
 +    std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp;
 +    value = temp.size() != 2 ? default_value : Size_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]));
 +}
 +
 +template<typename _Tp> static inline void read(const FileNode& node, Complex<_Tp>& value, const Complex<_Tp>& default_value)
 +{
 +    std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp;
 +    value = temp.size() != 2 ? default_value : Complex<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]));
 +}
 +
 +template<typename _Tp> static inline void read(const FileNode& node, Rect_<_Tp>& value, const Rect_<_Tp>& default_value)
 +{
 +    std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp;
 +    value = temp.size() != 4 ? default_value : Rect_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]),
 +                                                          saturate_cast<_Tp>(temp[2]), saturate_cast<_Tp>(temp[3]));
 +}
 +
 +template<typename _Tp, int cn> static inline void read(const FileNode& node, Vec<_Tp, cn>& value, const Vec<_Tp, cn>& default_value)
 +{
 +    std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp;
 +    value = temp.size() != cn ? default_value : Vec<_Tp, cn>(&temp[0]);
 +}
 +
 +template<typename _Tp> static inline void read(const FileNode& node, Scalar_<_Tp>& value, const Scalar_<_Tp>& default_value)
 +{
 +    std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp;
 +    value = temp.size() != 4 ? default_value : Scalar_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]),
 +                                                            saturate_cast<_Tp>(temp[2]), saturate_cast<_Tp>(temp[3]));
 +}
 +
 +static inline void read(const FileNode& node, Range& value, const Range& default_value)
 +{
 +    Point2i temp(value.start, value.end); const Point2i default_temp = Point2i(default_value.start, default_value.end);
 +    read(node, temp, default_temp);
 +    value.start = temp.x; value.end = temp.y;
 +}
 +
 +
 +CV_EXPORTS FileStorage& operator << (FileStorage& fs, const String& str);
 +
 +
 +namespace internal
 +{
 +    class CV_EXPORTS WriteStructContext
 +    {
 +    public:
 +        WriteStructContext(FileStorage& _fs, const String& name, int flags, const String& typeName = String());
 +        ~WriteStructContext();
 +    private:
 +        FileStorage* fs;
 +    };
 +
 +    template<typename _Tp, int numflag> class VecWriterProxy
 +    {
 +    public:
 +        VecWriterProxy( FileStorage* _fs ) : fs(_fs) {}
 +        void operator()(const std::vector<_Tp>& vec) const
 +        {
 +            size_t count = vec.size();
 +            for (size_t i = 0; i < count; i++)
 +                write(*fs, vec[i]);
 +        }
 +    private:
 +        FileStorage* fs;
 +    };
 +
 +    template<typename _Tp> class VecWriterProxy<_Tp, 1>
 +    {
 +    public:
 +        VecWriterProxy( FileStorage* _fs ) : fs(_fs) {}
 +        void operator()(const std::vector<_Tp>& vec) const
 +        {
 +            int _fmt = DataType<_Tp>::fmt;
 +            char fmt[] = { (char)((_fmt >> 8) + '1'), (char)_fmt, '\0' };
 +            fs->writeRaw(fmt, !vec.empty() ? (uchar*)&vec[0] : 0, vec.size() * sizeof(_Tp));
 +        }
 +    private:
 +        FileStorage* fs;
 +    };
 +
 +    template<typename _Tp, int numflag> class VecReaderProxy
 +    {
 +    public:
 +        VecReaderProxy( FileNodeIterator* _it ) : it(_it) {}
 +        void operator()(std::vector<_Tp>& vec, size_t count) const
 +        {
 +            count = std::min(count, it->remaining);
 +            vec.resize(count);
 +            for (size_t i = 0; i < count; i++, ++(*it))
 +                read(**it, vec[i], _Tp());
 +        }
 +    private:
 +        FileNodeIterator* it;
 +    };
 +
 +    template<typename _Tp> class VecReaderProxy<_Tp, 1>
 +    {
 +    public:
 +        VecReaderProxy( FileNodeIterator* _it ) : it(_it) {}
 +        void operator()(std::vector<_Tp>& vec, size_t count) const
 +        {
 +            size_t remaining = it->remaining;
 +            size_t cn = DataType<_Tp>::channels;
 +            int _fmt = DataType<_Tp>::fmt;
 +            char fmt[] = { (char)((_fmt >> 8)+'1'), (char)_fmt, '\0' };
 +            size_t remaining1 = remaining / cn;
 +            count = count < remaining1 ? count : remaining1;
 +            vec.resize(count);
 +            it->readRaw(fmt, !vec.empty() ? (uchar*)&vec[0] : 0, count*sizeof(_Tp));
 +        }
 +    private:
 +        FileNodeIterator* it;
 +    };
 +
 +} // internal
 +
 +
 +
 +template<typename _Tp> static inline
 +void write(FileStorage& fs, const _Tp& value)
 +{
 +    write(fs, String(), value);
 +}
 +
 +template<> inline
 +void write( FileStorage& fs, const int& value )
 +{
 +    writeScalar(fs, value);
 +}
 +
 +template<> inline
 +void write( FileStorage& fs, const float& value )
 +{
 +    writeScalar(fs, value);
 +}
 +
 +template<> inline
 +void write( FileStorage& fs, const double& value )
 +{
 +    writeScalar(fs, value);
 +}
 +
 +template<> inline
 +void write( FileStorage& fs, const String& value )
 +{
 +    writeScalar(fs, value);
 +}
 +
 +template<typename _Tp> static inline
 +void write(FileStorage& fs, const Point_<_Tp>& pt )
 +{
 +    write(fs, pt.x);
 +    write(fs, pt.y);
 +}
 +
 +template<typename _Tp> static inline
 +void write(FileStorage& fs, const Point3_<_Tp>& pt )
 +{
 +    write(fs, pt.x);
 +    write(fs, pt.y);
 +    write(fs, pt.z);
 +}
 +
 +template<typename _Tp> static inline
 +void write(FileStorage& fs, const Size_<_Tp>& sz )
 +{
 +    write(fs, sz.width);
 +    write(fs, sz.height);
 +}
 +
 +template<typename _Tp> static inline
 +void write(FileStorage& fs, const Complex<_Tp>& c )
 +{
 +    write(fs, c.re);
 +    write(fs, c.im);
 +}
 +
 +template<typename _Tp> static inline
 +void write(FileStorage& fs, const Rect_<_Tp>& r )
 +{
 +    write(fs, r.x);
 +    write(fs, r.y);
 +    write(fs, r.width);
 +    write(fs, r.height);
 +}
 +
 +template<typename _Tp, int cn> static inline
 +void write(FileStorage& fs, const Vec<_Tp, cn>& v )
 +{
 +    for(int i = 0; i < cn; i++)
 +        write(fs, v.val[i]);
 +}
 +
 +template<typename _Tp> static inline
 +void write(FileStorage& fs, const Scalar_<_Tp>& s )
 +{
 +    write(fs, s.val[0]);
 +    write(fs, s.val[1]);
 +    write(fs, s.val[2]);
 +    write(fs, s.val[3]);
 +}
 +
 +static inline
 +void write(FileStorage& fs, const Range& r )
 +{
 +    write(fs, r.start);
 +    write(fs, r.end);
 +}
 +
 +template<typename _Tp> static inline
 +void write( FileStorage& fs, const std::vector<_Tp>& vec )
 +{
 +    internal::VecWriterProxy<_Tp, DataType<_Tp>::fmt != 0> w(&fs);
 +    w(vec);
 +}
 +
 +
 +template<typename _Tp> static inline
 +void write(FileStorage& fs, const String& name, const Point_<_Tp>& pt )
 +{
 +    internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
 +    write(fs, pt);
 +}
 +
 +template<typename _Tp> static inline
 +void write(FileStorage& fs, const String& name, const Point3_<_Tp>& pt )
 +{
 +    internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
 +    write(fs, pt);
 +}
 +
 +template<typename _Tp> static inline
 +void write(FileStorage& fs, const String& name, const Size_<_Tp>& sz )
 +{
 +    internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
 +    write(fs, sz);
 +}
 +
 +template<typename _Tp> static inline
 +void write(FileStorage& fs, const String& name, const Complex<_Tp>& c )
 +{
 +    internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
 +    write(fs, c);
 +}
 +
 +template<typename _Tp> static inline
 +void write(FileStorage& fs, const String& name, const Rect_<_Tp>& r )
 +{
 +    internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
 +    write(fs, r);
 +}
 +
 +template<typename _Tp, int cn> static inline
 +void write(FileStorage& fs, const String& name, const Vec<_Tp, cn>& v )
 +{
 +    internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
 +    write(fs, v);
 +}
 +
 +template<typename _Tp> static inline
 +void write(FileStorage& fs, const String& name, const Scalar_<_Tp>& s )
 +{
 +    internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
 +    write(fs, s);
 +}
 +
 +static inline
 +void write(FileStorage& fs, const String& name, const Range& r )
 +{
 +    internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW);
 +    write(fs, r);
 +}
 +
 +template<typename _Tp> static inline
 +void write( FileStorage& fs, const String& name, const std::vector<_Tp>& vec )
 +{
 +    internal::WriteStructContext ws(fs, name, FileNode::SEQ+(DataType<_Tp>::fmt != 0 ? FileNode::FLOW : 0));
 +    write(fs, vec);
 +}
 +
 +
 +static inline
 +void read(const FileNode& node, bool& value, bool default_value)
 +{
 +    int temp;
 +    read(node, temp, (int)default_value);
 +    value = temp != 0;
 +}
 +
 +static inline
 +void read(const FileNode& node, uchar& value, uchar default_value)
 +{
 +    int temp;
 +    read(node, temp, (int)default_value);
 +    value = saturate_cast<uchar>(temp);
 +}
 +
 +static inline
 +void read(const FileNode& node, schar& value, schar default_value)
 +{
 +    int temp;
 +    read(node, temp, (int)default_value);
 +    value = saturate_cast<schar>(temp);
 +}
 +
 +static inline
 +void read(const FileNode& node, ushort& value, ushort default_value)
 +{
 +    int temp;
 +    read(node, temp, (int)default_value);
 +    value = saturate_cast<ushort>(temp);
 +}
 +
 +static inline
 +void read(const FileNode& node, short& value, short default_value)
 +{
 +    int temp;
 +    read(node, temp, (int)default_value);
 +    value = saturate_cast<short>(temp);
 +}
 +
 +template<typename _Tp> static inline
 +void read( FileNodeIterator& it, std::vector<_Tp>& vec, size_t maxCount = (size_t)INT_MAX )
 +{
 +    internal::VecReaderProxy<_Tp, DataType<_Tp>::fmt != 0> r(&it);
 +    r(vec, maxCount);
 +}
 +
 +template<typename _Tp> static inline
 +void read( const FileNode& node, std::vector<_Tp>& vec, const std::vector<_Tp>& default_value = std::vector<_Tp>() )
 +{
 +    if(!node.node)
 +        vec = default_value;
 +    else
 +    {
 +        FileNodeIterator it = node.begin();
 +        read( it, vec );
 +    }
 +}
 +
 +
 +template<typename _Tp> static inline
 +FileStorage& operator << (FileStorage& fs, const _Tp& value)
 +{
 +    if( !fs.isOpened() )
 +        return fs;
 +    if( fs.state == FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP )
 +        CV_Error( Error::StsError, "No element name has been given" );
 +    write( fs, fs.elname, value );
 +    if( fs.state & FileStorage::INSIDE_MAP )
 +        fs.state = FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP;
 +    return fs;
 +}
 +
 +static inline
 +FileStorage& operator << (FileStorage& fs, const char* str)
 +{
 +    return (fs << String(str));
 +}
 +
 +static inline
 +FileStorage& operator << (FileStorage& fs, char* value)
 +{
 +    return (fs << String(value));
 +}
 +
 +template<typename _Tp> static inline
 +FileNodeIterator& operator >> (FileNodeIterator& it, _Tp& value)
 +{
 +    read( *it, value, _Tp());
 +    return ++it;
 +}
 +
 +template<typename _Tp> static inline
 +FileNodeIterator& operator >> (FileNodeIterator& it, std::vector<_Tp>& vec)
 +{
 +    internal::VecReaderProxy<_Tp, DataType<_Tp>::fmt != 0> r(&it);
 +    r(vec, (size_t)INT_MAX);
 +    return it;
 +}
 +
 +template<typename _Tp> static inline
 +void operator >> (const FileNode& n, _Tp& value)
 +{
 +    read( n, value, _Tp());
 +}
 +
 +template<typename _Tp> static inline
 +void operator >> (const FileNode& n, std::vector<_Tp>& vec)
 +{
 +    FileNodeIterator it = n.begin();
 +    it >> vec;
 +}
 +
 +
 +static inline
 +bool operator == (const FileNodeIterator& it1, const FileNodeIterator& it2)
 +{
 +    return it1.fs == it2.fs && it1.container == it2.container &&
 +        it1.reader.ptr == it2.reader.ptr && it1.remaining == it2.remaining;
 +}
 +
 +static inline
 +bool operator != (const FileNodeIterator& it1, const FileNodeIterator& it2)
 +{
 +    return !(it1 == it2);
 +}
 +
 +static inline
 +ptrdiff_t operator - (const FileNodeIterator& it1, const FileNodeIterator& it2)
 +{
 +    return it2.remaining - it1.remaining;
 +}
 +
 +static inline
 +bool operator < (const FileNodeIterator& it1, const FileNodeIterator& it2)
 +{
 +    return it1.remaining > it2.remaining;
 +}
 +
 +inline FileNode FileStorage::getFirstTopLevelNode() const { FileNode r = root(); FileNodeIterator it = r.begin(); return it != r.end() ? *it : FileNode(); }
 +inline FileNode::FileNode() : fs(0), node(0) {}
 +inline FileNode::FileNode(const CvFileStorage* _fs, const CvFileNode* _node) : fs(_fs), node(_node) {}
 +inline FileNode::FileNode(const FileNode& _node) : fs(_node.fs), node(_node.node) {}
 +inline bool FileNode::empty() const    { return node   == 0;    }
 +inline bool FileNode::isNone() const   { return type() == NONE; }
 +inline bool FileNode::isSeq() const    { return type() == SEQ;  }
 +inline bool FileNode::isMap() const    { return type() == MAP;  }
 +inline bool FileNode::isInt() const    { return type() == INT;  }
 +inline bool FileNode::isReal() const   { return type() == REAL; }
 +inline bool FileNode::isString() const { return type() == STR;  }
 +inline CvFileNode* FileNode::operator *() { return (CvFileNode*)node; }
 +inline const CvFileNode* FileNode::operator* () const { return node; }
 +inline FileNode::operator int() const    { int value;    read(*this, value, 0);     return value; }
 +inline FileNode::operator float() const  { float value;  read(*this, value, 0.f);   return value; }
 +inline FileNode::operator double() const { double value; read(*this, value, 0.);    return value; }
 +inline FileNode::operator String() const { String value; read(*this, value, value); return value; }
 +inline FileNodeIterator FileNode::begin() const { return FileNodeIterator(fs, node); }
 +inline FileNodeIterator FileNode::end() const   { return FileNodeIterator(fs, node, size()); }
 +inline void FileNode::readRaw( const String& fmt, uchar* vec, size_t len ) const { begin().readRaw( fmt, vec, len ); }
++inline FileNode FileNodeIterator::operator *() const  { return FileNode(fs, (const CvFileNode*)(const void*)reader.ptr); }
++inline FileNode FileNodeIterator::operator ->() const { return FileNode(fs, (const CvFileNode*)(const void*)reader.ptr); }
 +inline String::String(const FileNode& fn): cstr_(0), len_(0) { read(fn, *this, *this); }
 +
 +} // cv
 +
 +#endif // __OPENCV_CORE_PERSISTENCE_HPP__
index bafc1d0,0000000..dae3828
mode 100644,000000..100644
--- /dev/null
@@@ -1,471 -1,0 +1,472 @@@
 +/*M///////////////////////////////////////////////////////////////////////////////////////
 +//
 +//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
 +//
 +//  By downloading, copying, installing or using the software you agree to this license.
 +//  If you do not agree to this license, do not download, install,
 +//  copy or use the software.
 +//
 +//
 +//                          License Agreement
 +//                For Open Source Computer Vision Library
 +//
 +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
 +// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
 +// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
 +// Third party copyrights are property of their respective owners.
 +//
 +// Redistribution and use in source and binary forms, with or without modification,
 +// are permitted provided that the following conditions are met:
 +//
 +//   * Redistribution's of source code must retain the above copyright notice,
 +//     this list of conditions and the following disclaimer.
 +//
 +//   * Redistribution's in binary form must reproduce the above copyright notice,
 +//     this list of conditions and the following disclaimer in the documentation
 +//     and/or other materials provided with the distribution.
 +//
 +//   * The name of the copyright holders may not be used to endorse or promote products
 +//     derived from this software without specific prior written permission.
 +//
 +// This software is provided by the copyright holders and contributors "as is" and
 +// any express or implied warranties, including, but not limited to, the implied
 +// warranties of merchantability and fitness for a particular purpose are disclaimed.
 +// In no event shall the Intel Corporation or contributors be liable for any direct,
 +// indirect, incidental, special, exemplary, or consequential damages
 +// (including, but not limited to, procurement of substitute goods or services;
 +// loss of use, data, or profits; or business interruption) however caused
 +// and on any theory of liability, whether in contract, strict liability,
 +// or tort (including negligence or otherwise) arising in any way out of
 +// the use of this software, even if advised of the possibility of such damage.
 +//
 +//M*/
 +
 +#ifndef __OPENCV_CORE_UTILITY_H__
 +#define __OPENCV_CORE_UTILITY_H__
 +
 +#ifndef __cplusplus
 +#  error utility.hpp header must be compiled as C++
 +#endif
 +
 +#include "opencv2/core.hpp"
 +
 +namespace cv
 +{
 +
 +/*!
 + Automatically Allocated Buffer Class
 +
 + The class is used for temporary buffers in functions and methods.
 + If a temporary buffer is usually small (a few K's of memory),
 + but its size depends on the parameters, it makes sense to create a small
 + fixed-size array on stack and use it if it's large enough. If the required buffer size
 + is larger than the fixed size, another buffer of sufficient size is allocated dynamically
 + and released after the processing. Therefore, in typical cases, when the buffer size is small,
 + there is no overhead associated with malloc()/free().
 + At the same time, there is no limit on the size of processed data.
 +
 + This is what AutoBuffer does. The template takes 2 parameters - type of the buffer elements and
 + the number of stack-allocated elements. Here is how the class is used:
 +
 + \code
 + void my_func(const cv::Mat& m)
 + {
 +    cv::AutoBuffer<float> buf; // create automatic buffer containing 1000 floats
 +
 +    buf.allocate(m.rows); // if m.rows <= 1000, the pre-allocated buffer is used,
 +                          // otherwise the buffer of "m.rows" floats will be allocated
 +                          // dynamically and deallocated in cv::AutoBuffer destructor
 +    ...
 + }
 + \endcode
 +*/
 +template<typename _Tp, size_t fixed_size = 1024/sizeof(_Tp)+8> class AutoBuffer
 +{
 +public:
 +    typedef _Tp value_type;
 +
 +    //! the default contructor
 +    AutoBuffer();
 +    //! constructor taking the real buffer size
 +    AutoBuffer(size_t _size);
 +
 +    //! the copy constructor
 +    AutoBuffer(const AutoBuffer<_Tp, fixed_size>& buf);
 +    //! the assignment operator
 +    AutoBuffer<_Tp, fixed_size>& operator = (const AutoBuffer<_Tp, fixed_size>& buf);
 +
 +    //! destructor. calls deallocate()
 +    ~AutoBuffer();
 +
 +    //! allocates the new buffer of size _size. if the _size is small enough, stack-allocated buffer is used
 +    void allocate(size_t _size);
 +    //! deallocates the buffer if it was dynamically allocated
 +    void deallocate();
 +    //! resizes the buffer and preserves the content
 +    void resize(size_t _size);
 +    //! returns the current buffer size
 +    size_t size() const;
 +    //! returns pointer to the real buffer, stack-allocated or head-allocated
 +    operator _Tp* ();
 +    //! returns read-only pointer to the real buffer, stack-allocated or head-allocated
 +    operator const _Tp* () const;
 +
 +protected:
 +    //! pointer to the real buffer, can point to buf if the buffer is small enough
 +    _Tp* ptr;
 +    //! size of the real buffer
 +    size_t sz;
 +    //! pre-allocated buffer. At least 1 element to confirm C++ standard reqirements
 +    _Tp buf[(fixed_size > 0) ? fixed_size : 1];
 +};
 +
 +//! Sets/resets the break-on-error mode.
 +
 +/*!
 +  When the break-on-error mode is set, the default error handler
 +  issues a hardware exception, which can make debugging more convenient.
 +
 +  \return the previous state
 + */
 +CV_EXPORTS bool setBreakOnError(bool flag);
 +
 +extern "C" typedef int (*ErrorCallback)( int status, const char* func_name,
 +                                       const char* err_msg, const char* file_name,
 +                                       int line, void* userdata );
 +
 +//! Sets the new error handler and the optional user data.
 +
 +/*!
 +  The function sets the new error handler, called from cv::error().
 +
 +  \param errCallback the new error handler. If NULL, the default error handler is used.
 +  \param userdata the optional user data pointer, passed to the callback.
 +  \param prevUserdata the optional output parameter where the previous user data pointer is stored
 +
 +  \return the previous error handler
 +*/
 +CV_EXPORTS ErrorCallback redirectError( ErrorCallback errCallback, void* userdata=0, void** prevUserdata=0);
 +
 +CV_EXPORTS String format( const char* fmt, ... );
 +CV_EXPORTS String tempfile( const char* suffix = 0);
 +CV_EXPORTS void glob(String pattern, std::vector<String>& result, bool recursive = false);
 +CV_EXPORTS void setNumThreads(int nthreads);
 +CV_EXPORTS int getNumThreads();
 +CV_EXPORTS int getThreadNum();
 +
 +CV_EXPORTS_W const String& getBuildInformation();
 +
 +//! Returns the number of ticks.
 +
 +/*!
 +  The function returns the number of ticks since the certain event (e.g. when the machine was turned on).
 +  It can be used to initialize cv::RNG or to measure a function execution time by reading the tick count
 +  before and after the function call. The granularity of ticks depends on the hardware and OS used. Use
 +  cv::getTickFrequency() to convert ticks to seconds.
 +*/
 +CV_EXPORTS_W int64 getTickCount();
 +
 +/*!
 +  Returns the number of ticks per seconds.
 +
 +  The function returns the number of ticks (as returned by cv::getTickCount()) per second.
 +  The following code computes the execution time in milliseconds:
 +
 +  \code
 +  double exec_time = (double)getTickCount();
 +  // do something ...
 +  exec_time = ((double)getTickCount() - exec_time)*1000./getTickFrequency();
 +  \endcode
 +*/
 +CV_EXPORTS_W double getTickFrequency();
 +
 +/*!
 +  Returns the number of CPU ticks.
 +
 +  On platforms where the feature is available, the function returns the number of CPU ticks
 +  since the certain event (normally, the system power-on moment). Using this function
 +  one can accurately measure the execution time of very small code fragments,
 +  for which cv::getTickCount() granularity is not enough.
 +*/
 +CV_EXPORTS_W int64 getCPUTickCount();
 +
 +//! Available CPU features. Currently, the following features are recognized:
 +enum {
 +      CPU_MMX       = 1,
 +      CPU_SSE       = 2,
 +      CPU_SSE2      = 3,
 +      CPU_SSE3      = 4,
 +      CPU_SSSE3     = 5,
 +      CPU_SSE4_1    = 6,
 +      CPU_SSE4_2    = 7,
 +      CPU_POPCNT    = 8,
 +      CPU_AVX       = 10,
 +      CPU_NEON      = 11
 +     };
 +// remember to keep this list identical to the one in cvdef.h
 +
 +/*!
 +  Returns SSE etc. support status
 +
 +  The function returns true if certain hardware features are available.
 +
 +  \note {Note that the function output is not static. Once you called cv::useOptimized(false),
 +  most of the hardware acceleration is disabled and thus the function will returns false,
 +  until you call cv::useOptimized(true)}
 +*/
 +CV_EXPORTS_W bool checkHardwareSupport(int feature);
 +
 +//! returns the number of CPUs (including hyper-threading)
 +CV_EXPORTS_W int getNumberOfCPUs();
 +
 +
 +/*!
 +  Aligns pointer by the certain number of bytes
 +
 +  This small inline function aligns the pointer by the certian number of bytes by shifting
 +  it forward by 0 or a positive offset.
 +*/
 +template<typename _Tp> static inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp))
 +{
 +    return (_Tp*)(((size_t)ptr + n-1) & -n);
 +}
 +
 +/*!
 +  Aligns buffer size by the certain number of bytes
 +
 +  This small inline function aligns a buffer size by the certian number of bytes by enlarging it.
 +*/
 +static inline size_t alignSize(size_t sz, int n)
 +{
++    CV_DbgAssert((n & (n - 1)) == 0); // n is a power of 2
 +    return (sz + n-1) & -n;
 +}
 +
 +/*!
 +  Turns on/off available optimization
 +
 +  The function turns on or off the optimized code in OpenCV. Some optimization can not be enabled
 +  or disabled, but, for example, most of SSE code in OpenCV can be temporarily turned on or off this way.
 +
 +  \note{Since optimization may imply using special data structures, it may be unsafe
 +  to call this function anywhere in the code. Instead, call it somewhere at the top level.}
 +*/
 +CV_EXPORTS_W void setUseOptimized(bool onoff);
 +
 +/*!
 +  Returns the current optimization status
 +
 +  The function returns the current optimization status, which is controlled by cv::setUseOptimized().
 +*/
 +CV_EXPORTS_W bool useOptimized();
 +
 +static inline size_t getElemSize(int type) { return CV_ELEM_SIZE(type); }
 +
 +/////////////////////////////// Parallel Primitives //////////////////////////////////
 +
 +// a base body class
 +class CV_EXPORTS ParallelLoopBody
 +{
 +public:
 +    virtual ~ParallelLoopBody();
 +    virtual void operator() (const Range& range) const = 0;
 +};
 +
 +CV_EXPORTS void parallel_for_(const Range& range, const ParallelLoopBody& body, double nstripes=-1.);
 +
 +/////////////////////////// Synchronization Primitives ///////////////////////////////
 +
 +class CV_EXPORTS Mutex
 +{
 +public:
 +    Mutex();
 +    ~Mutex();
 +    Mutex(const Mutex& m);
 +    Mutex& operator = (const Mutex& m);
 +
 +    void lock();
 +    bool trylock();
 +    void unlock();
 +
 +    struct Impl;
 +protected:
 +    Impl* impl;
 +};
 +
 +class CV_EXPORTS AutoLock
 +{
 +public:
 +    AutoLock(Mutex& m) : mutex(&m) { mutex->lock(); }
 +    ~AutoLock() { mutex->unlock(); }
 +protected:
 +    Mutex* mutex;
 +private:
 +    AutoLock(const AutoLock&);
 +    AutoLock& operator = (const AutoLock&);
 +};
 +
 +// The CommandLineParser class is designed for command line arguments parsing
 +
 +class CV_EXPORTS CommandLineParser
 +{
 +    public:
 +    CommandLineParser(int argc, const char* const argv[], const String& keys);
 +    CommandLineParser(const CommandLineParser& parser);
 +    CommandLineParser& operator = (const CommandLineParser& parser);
 +
 +    String getPathToApplication() const;
 +
 +    template <typename T>
 +    T get(const String& name, bool space_delete = true) const
 +    {
 +        T val = T();
 +        getByName(name, space_delete, ParamType<T>::type, (void*)&val);
 +        return val;
 +    }
 +
 +    template <typename T>
 +    T get(int index, bool space_delete = true) const
 +    {
 +        T val = T();
 +        getByIndex(index, space_delete, ParamType<T>::type, (void*)&val);
 +        return val;
 +    }
 +
 +    bool has(const String& name) const;
 +
 +    bool check() const;
 +
 +    void about(const String& message);
 +
 +    void printMessage() const;
 +    void printErrors() const;
 +
 +protected:
 +    void getByName(const String& name, bool space_delete, int type, void* dst) const;
 +    void getByIndex(int index, bool space_delete, int type, void* dst) const;
 +
 +    struct Impl;
 +    Impl* impl;
 +};
 +
 +/////////////////////////////// AutoBuffer implementation ////////////////////////////////////////
 +
 +template<typename _Tp, size_t fixed_size> inline
 +AutoBuffer<_Tp, fixed_size>::AutoBuffer()
 +{
 +    ptr = buf;
 +    sz = fixed_size;
 +}
 +
 +template<typename _Tp, size_t fixed_size> inline
 +AutoBuffer<_Tp, fixed_size>::AutoBuffer(size_t _size)
 +{
 +    ptr = buf;
 +    sz = fixed_size;
 +    allocate(_size);
 +}
 +
 +template<typename _Tp, size_t fixed_size> inline
 +AutoBuffer<_Tp, fixed_size>::AutoBuffer(const AutoBuffer<_Tp, fixed_size>& abuf )
 +{
 +    ptr = buf;
 +    sz = fixed_size;
 +    allocate(abuf.size());
 +    for( size_t i = 0; i < sz; i++ )
 +        ptr[i] = abuf.ptr[i];
 +}
 +
 +template<typename _Tp, size_t fixed_size> inline AutoBuffer<_Tp, fixed_size>&
 +AutoBuffer<_Tp, fixed_size>::operator = (const AutoBuffer<_Tp, fixed_size>& abuf)
 +{
 +    if( this != &abuf )
 +    {
 +        deallocate();
 +        allocate(abuf.size());
 +        for( size_t i = 0; i < sz; i++ )
 +            ptr[i] = abuf.ptr[i];
 +    }
 +    return *this;
 +}
 +
 +template<typename _Tp, size_t fixed_size> inline
 +AutoBuffer<_Tp, fixed_size>::~AutoBuffer()
 +{ deallocate(); }
 +
 +template<typename _Tp, size_t fixed_size> inline void
 +AutoBuffer<_Tp, fixed_size>::allocate(size_t _size)
 +{
 +    if(_size <= sz)
 +    {
 +        sz = _size;
 +        return;
 +    }
 +    deallocate();
 +    if(_size > fixed_size)
 +    {
 +        ptr = new _Tp[_size];
 +        sz = _size;
 +    }
 +}
 +
 +template<typename _Tp, size_t fixed_size> inline void
 +AutoBuffer<_Tp, fixed_size>::deallocate()
 +{
 +    if( ptr != buf )
 +    {
 +        delete[] ptr;
 +        ptr = buf;
 +        sz = fixed_size;
 +    }
 +}
 +
 +template<typename _Tp, size_t fixed_size> inline void
 +AutoBuffer<_Tp, fixed_size>::resize(size_t _size)
 +{
 +    if(_size <= sz)
 +    {
 +        sz = _size;
 +        return;
 +    }
 +    size_t i, prevsize = sz, minsize = MIN(prevsize, _size);
 +    _Tp* prevptr = ptr;
 +
 +    ptr = _size > fixed_size ? new _Tp[_size] : buf;
 +    sz = _size;
 +
 +    if( ptr != prevptr )
 +        for( i = 0; i < minsize; i++ )
 +            ptr[i] = prevptr[i];
 +    for( i = prevsize; i < _size; i++ )
 +        ptr[i] = _Tp();
 +
 +    if( prevptr != buf )
 +        delete[] prevptr;
 +}
 +
 +template<typename _Tp, size_t fixed_size> inline size_t
 +AutoBuffer<_Tp, fixed_size>::size() const
 +{ return sz; }
 +
 +template<typename _Tp, size_t fixed_size> inline
 +AutoBuffer<_Tp, fixed_size>::operator _Tp* ()
 +{ return ptr; }
 +
 +template<typename _Tp, size_t fixed_size> inline
 +AutoBuffer<_Tp, fixed_size>::operator const _Tp* () const
 +{ return ptr; }
 +
 +#ifndef OPENCV_NOSTL
 +template<> inline std::string CommandLineParser::get<std::string>(int index, bool space_delete) const
 +{
 +    return get<String>(index, space_delete);
 +}
 +template<> inline std::string CommandLineParser::get<std::string>(const String& name, bool space_delete) const
 +{
 +    return get<String>(name, space_delete);
 +}
 +#endif // OPENCV_NOSTL
 +
 +} //namespace cv
 +
 +#endif //__OPENCV_CORE_UTILITY_H__
Simple merge
Simple merge
                                      Base Image Filter
  \****************************************************************************************/
  
 -/*
 - Various border types, image boundaries are denoted with '|'
 -
 - * BORDER_REPLICATE:     aaaaaa|abcdefgh|hhhhhhh
 - * BORDER_REFLECT:       fedcba|abcdefgh|hgfedcb
 - * BORDER_REFLECT_101:   gfedcb|abcdefgh|gfedcba
 - * BORDER_WRAP:          cdefgh|abcdefgh|abcdefg
 - * BORDER_CONSTANT:      iiiiii|abcdefgh|iiiiiii  with some specified 'i'
 - */
 -int cv::borderInterpolate( int p, int len, int borderType )
 -{
 -    if( (unsigned)p < (unsigned)len )
 -        ;
 -    else if( borderType == BORDER_REPLICATE )
 -        p = p < 0 ? 0 : len - 1;
 -    else if( borderType == BORDER_REFLECT || borderType == BORDER_REFLECT_101 )
 -    {
 -        int delta = borderType == BORDER_REFLECT_101;
 -        if( len == 1 )
 -            return 0;
 -        do
 -        {
 -            if( p < 0 )
 -                p = -p - 1 + delta;
 -            else
 -                p = len - 1 - (p - len) - delta;
 -        }
 -        while( (unsigned)p >= (unsigned)len );
 -    }
 -    else if( borderType == BORDER_WRAP )
 -    {
 -        if( p < 0 )
 -            p -= ((p-len+1)/len)*len;
 -        if( p >= len )
 -            p %= len;
 -    }
 -    else if( borderType == BORDER_CONSTANT )
 -        p = -1;
 -    else
 -        CV_Error( CV_StsBadArg, "Unknown/unsupported border type" );
 -    return p;
 -}
 -
 -
+ #if defined HAVE_IPP && IPP_VERSION_MAJOR*100 + IPP_VERSION_MINOR >= 701
+ #define USE_IPP_SEP_FILTERS 1
+ #else
+ #undef USE_IPP_SEP_FILTERS
+ #endif
  namespace cv
  {
  
Simple merge
Simple merge
Simple merge
Simple merge
@@@ -224,145 -311,4 +311,37 @@@ Builds transformation maps for affine t
  
      :param ymap: Y values with  ``CV_32FC1`` type.
  
 -.. seealso:: :ocv:func:`ocl::warpAffine` , :ocv:func:`ocl::remap`
 +.. seealso:: :ocv:func:`ocl::warpAffine` , :ocv:func:`ocl::remap`
 +
- ocl::PyrLKOpticalFlow
- ---------------------
- .. ocv:class:: ocl::PyrLKOpticalFlow
- Class used for calculating an optical flow. ::
-     class PyrLKOpticalFlow
-     {
-     public:
-         PyrLKOpticalFlow();
-         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();
-     };
- 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`
- .. note::
-    (Ocl) An example the Lucas Kanade optical flow pyramid method can be found at opencv_source_code/samples/ocl/pyrlk_optical_flow.cpp
-    (Ocl) An example for square detection can be found at opencv_source_code/samples/ocl/squares.cpp
- ocl::PyrLKOpticalFlow::sparse
- -----------------------------
- Calculate an optical flow for a sparse feature set.
- .. ocv:function:: void ocl::PyrLKOpticalFlow::sparse(const oclMat& prevImg, const oclMat& nextImg, const oclMat& prevPts, oclMat& nextPts, oclMat& status, oclMat* 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`
- ocl::PyrLKOpticalFlow::dense
- -----------------------------
- Calculate dense optical flow.
- .. ocv:function:: void ocl::PyrLKOpticalFlow::dense(const oclMat& prevImg, const oclMat& nextImg, oclMat& u, oclMat& v, oclMat* 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.
- ocl::PyrLKOpticalFlow::releaseMemory
- ------------------------------------
- Releases inner buffers memory.
- .. ocv:function:: void ocl::PyrLKOpticalFlow::releaseMemory()
- ocl::interpolateFrames
- ----------------------
- Interpolate frames (images) using provided optical flow (displacement field).
- .. ocv:function:: void ocl::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)
-     :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 oclMat: 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.
 +ocl::HoughCircles
 +-----------------
 +Finds circles in a grayscale image using the Hough transform.
 +
 +.. ocv:function:: void ocl::HoughCircles(const oclMat& src, oclMat& circles, int method, float dp, float minDist, int cannyThreshold, int votesThreshold, int minRadius, int maxRadius, int maxCircles = 4096)
 +
 +.. ocv:function:: void ocl::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)
 +
 +    :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)` .
 +
 +    :param method: Detection method to use. Currently, the only implemented method is  ``CV_HOUGH_GRADIENT`` , which is basically  *21HT* , described in  [Yuen90]_.
 +
 +    :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  the :ocv:func:`ocl::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.
 +
 +    :param buf: Optional buffer to avoid extra memory allocations (for many calls with the same sizes).
 +
 +.. note:: Currently only non-ROI oclMat is supported for src.
 +.. seealso:: :ocv:func:`HoughCircles`
@@@ -21,16 -23,14 +21,16 @@@ Cascade classifier class used for objec
  
     (Ocl) A face detection example using cascade classifiers can be found at opencv_source_code/samples/ocl/facedetect.cpp
  
--ocl::OclCascadeClassifier::oclHaarDetectObjects
++ocl::OclCascadeClassifier::detectMultiScale
  ------------------------------------------------------
  Detects objects of different sizes in the input image.
  
 -.. ocv:function:: CvSeq* ocl::OclCascadeClassifier::oclHaarDetectObjects(oclMat &gimg, CvMemStorage *storage, double scaleFactor, int minNeighbors, int flags, CvSize minSize = cvSize(0, 0), CvSize maxSize = cvSize(0, 0))
 +.. ocv:function:: void ocl::OclCascadeClassifier::detectMultiScale(oclMat &image, std::vector<cv::Rect>& faces, double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0, Size minSize = Size(), Size maxSize = Size())
  
-     :param image:  Matrix of type CV_8U containing an image where objects should be detected.
 -    :param gimage:  Matrix of type CV_8U containing an image where objects should be detected.
 +    :param faces: Vector of rectangles where each rectangle contains the detected object.
 +
++    :param image:  Matrix of type CV_8U containing an image where objects should be detected.
      :param scaleFactor: Parameter specifying how much the image size is reduced at each image scale.
  
      :param minNeighbors: Parameter specifying how many neighbors each candidate rectangle should have to retain it.
index fc7c114,0000000..5591b3f
mode 100644,000000..100644
--- /dev/null
@@@ -1,1968 -1,0 +1,2033 @@@
-             bool supportsFeature(int ftype);
-             size_t computeUnits();
 +/*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"
++#include "opencv2/ml.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};
-             //! copies the oclMatrix content to "m".
++            bool supportsFeature(int ftype) const;
++            size_t computeUnits() const;
 +            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;
-             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;
++
++            //! copies those oclMatrix elements to "m" that are marked with non-zero mask elements.
 +            // It calls m.create(this->size(), this->type()).
 +            // It supports any data type
-         //#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);
++            void copyTo( oclMat &m, const oclMat &mask = oclMat()) 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 ///////////////////////////////////
-         // supports CV_32FC1 only
++
++        //! adds one matrix to another with scale (dst = src1 * alpha + src2 * beta + gama)
++        CV_EXPORTS void addWeighted(const oclMat &src1, double  alpha, const oclMat &src2, double beta, double gama, oclMat &dst);
++
++        //! adds one matrix to another (dst = src1 + src2)
++        // supports all data types
++        CV_EXPORTS void add(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask = oclMat());
++        //! adds scalar to a matrix (dst = src1 + s)
++        // supports all data types
++        CV_EXPORTS void add(const oclMat &src1, const Scalar &s, oclMat &dst, const oclMat &mask = oclMat());
++
++        //! subtracts one matrix from another (dst = src1 - src2)
++        // supports all data types
++        CV_EXPORTS void subtract(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask = oclMat());
++        //! subtracts scalar from a matrix (dst = src1 - s)
++        // supports all data types
++        CV_EXPORTS void subtract(const oclMat &src1, const Scalar &s, oclMat &dst, const oclMat &mask = oclMat());
++
++        //! computes element-wise product of the two arrays (dst = src1 * scale * src2)
++        // supports all data types
++        CV_EXPORTS void multiply(const oclMat &src1, const oclMat &src2, oclMat &dst, double scale = 1);
 +        //! multiplies matrix to a number (dst = scalar * src)
-         //! 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);
++        // supports all data types
 +        CV_EXPORTS void multiply(double scalar, const oclMat &src, oclMat &dst);
-         //! 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);
 +
-         // supports  CV_8UC1, 8UC4, 8SC4, 16UC2, 16SC2, 32SC1 and 32FC1.(the same as cuda)
++        //! computes element-wise quotient of the two arrays (dst = src1 * scale / src2)
++        // supports all data types
++        CV_EXPORTS void divide(const oclMat &src1, const oclMat &src2, oclMat &dst, double scale = 1);
++        //! computes element-wise quotient of the two arrays (dst = scale / src)
++        // supports all data types
++        CV_EXPORTS void divide(double scale, const oclMat &src1, oclMat &dst);
++
++        //! compares elements of two arrays (dst = src1 <cmpop> src2)
++        // supports all data types
++        CV_EXPORTS void compare(const oclMat &src1, const oclMat &src2, oclMat &dst, int cmpop);
 +
 +        //! transposes the matrix
-         //! 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);
++        // supports all data types
 +        CV_EXPORTS void transpose(const oclMat &src, oclMat &dst);
 +
-         CV_EXPORTS void flip(const oclMat &a, oclMat &b, int flipCode);
++        //! computes element-wise absolute difference of two arrays (dst = abs(src1 - src2))
++        // supports all data types
++        CV_EXPORTS void absdiff(const oclMat &src1, const oclMat &src2, oclMat &dst);
++        //! computes element-wise absolute difference of array and scalar (dst = abs(src1 - s))
++        // supports all data types
++        CV_EXPORTS void absdiff(const oclMat &src1, const Scalar &s, oclMat &dst);
 +
 +        //! 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 &src, oclMat &dst, 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
-         //  supports 8UC1 8UC3
 +        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 sigmaSpace, int borderType=BORDER_DEFAULT);
 +
 +        //! Applies an adaptive bilateral filter to the input image
 +        //  This is not truly a bilateral filter. Instead of using user provided fixed parameters,
 +        //  the function calculates a constant at each window based on local standard deviation,
 +        //  and use this constant to do filtering.
-         //! computes exponent of each matrix element (b = e**a)
-         // supports only CV_32FC1 type
-         CV_EXPORTS void exp(const oclMat &a, oclMat &b);
++        //  supports 8UC1, 8UC3
 +        CV_EXPORTS void adaptiveBilateralFilter(const oclMat& src, oclMat& dst, Size ksize, double sigmaSpace, Point anchor = Point(-1, -1), int borderType=BORDER_DEFAULT);
 +
-         //! 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 exponent of each matrix element (dst = e**src)
++        // supports only CV_32FC1, CV_64FC1 type
++        CV_EXPORTS void exp(const oclMat &src, oclMat &dst);
 +
-         // supports only CV_32F CV_64F type
++        //! computes natural logarithm of absolute value of each matrix element: dst = log(abs(src))
++        // supports only CV_32FC1, CV_64FC1 type
++        CV_EXPORTS void log(const oclMat &src, oclMat &dst);
 +
 +        //! computes magnitude of each (x(i), y(i)) vector
-         CV_EXPORTS void magnitudeSqr(const oclMat &x, const oclMat &y, oclMat &magnitude);
-         CV_EXPORTS void magnitudeSqr(const oclMat &x, oclMat &magnitude);
++        // supports only CV_32F, CV_64F type
 +        CV_EXPORTS void magnitude(const oclMat &x, const oclMat &y, oclMat &magnitude);
-         // supports only CV_32F CV_64F type
 +
 +        //! computes angle (angle(i)) of each (x(i), y(i)) vector
-         //! support only CV_32F CV_64F type
++        // 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_32FC1 type
++        // 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
-         CV_EXPORTS void dft(const oclMat &src, oclMat &dst, Size dft_size = Size(0, 0), int flags = 0);
++        // 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);
 +
++        CV_EXPORTS void setIdentity(oclMat& src, double val);
++
 +        //////////////////////////////// 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,
 +                const 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(), 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);
 +        /*!Base class for MOG and MOG2!*/
 +        class CV_EXPORTS BackgroundSubtractor
 +        {
 +        public:
 +            //! the virtual destructor
 +            virtual ~BackgroundSubtractor();
 +            //! the update operator that takes the next video frame and returns the current foreground mask as 8-bit binary image.
 +            virtual void operator()(const oclMat& image, oclMat& fgmask, float learningRate);
 +
 +            //! computes a background image
 +            virtual void getBackgroundImage(oclMat& backgroundImage) const = 0;
 +        };
 +                /*!
 +        Gaussian Mixture-based Backbround/Foreground Segmentation Algorithm
 +
 +        The class implements the following algorithm:
 +        "An improved adaptive background mixture model for real-time tracking with shadow detection"
 +        P. KadewTraKuPong and R. Bowden,
 +        Proc. 2nd European Workshp on Advanced Video-Based Surveillance Systems, 2001."
 +        http://personal.ee.surrey.ac.uk/Personal/R.Bowden/publications/avbs01/avbs01.pdf
 +        */
 +        class CV_EXPORTS MOG: public cv::ocl::BackgroundSubtractor
 +        {
 +        public:
 +            //! the default constructor
 +            MOG(int nmixtures = -1);
 +
 +            //! re-initiaization method
 +            void initialize(Size frameSize, int frameType);
 +
 +            //! the update operator
 +            void operator()(const oclMat& frame, oclMat& fgmask, float learningRate = 0.f);
 +
 +            //! computes a background image which are the mean of all background gaussians
 +            void getBackgroundImage(oclMat& backgroundImage) const;
 +
 +            //! releases all inner buffers
 +            void release();
 +
 +            int history;
 +            float varThreshold;
 +            float backgroundRatio;
 +            float noiseSigma;
 +
 +        private:
 +            int nmixtures_;
 +
 +            Size frameSize_;
 +            int frameType_;
 +            int nframes_;
 +
 +            oclMat weight_;
 +            oclMat sortKey_;
 +            oclMat mean_;
 +            oclMat var_;
 +        };
 +
 +        /*!
 +        The class implements the following algorithm:
 +        "Improved adaptive Gausian mixture model for background subtraction"
 +        Z.Zivkovic
 +        International Conference Pattern Recognition, UK, August, 2004.
 +        http://www.zoranz.net/Publications/zivkovic2004ICPR.pdf
 +        */
 +        class CV_EXPORTS MOG2: public cv::ocl::BackgroundSubtractor
 +        {
 +        public:
 +            //! the default constructor
 +            MOG2(int nmixtures = -1);
 +
 +            //! re-initiaization method
 +            void initialize(Size frameSize, int frameType);
 +
 +            //! the update operator
 +            void operator()(const oclMat& frame, oclMat& fgmask, float learningRate = -1.0f);
 +
 +            //! computes a background image which are the mean of all background gaussians
 +            void getBackgroundImage(oclMat& backgroundImage) const;
 +
 +            //! releases all inner buffers
 +            void release();
 +
 +            // parameters
 +            // you should call initialize after parameters changes
 +
 +            int history;
 +
 +            //! here it is the maximum allowed number of mixture components.
 +            //! Actual number is determined dynamically per pixel
 +            float varThreshold;
 +            // threshold on the squared Mahalanobis distance to decide if it is well described
 +            // by the background model or not. Related to Cthr from the paper.
 +            // This does not influence the update of the background. A typical value could be 4 sigma
 +            // and that is varThreshold=4*4=16; Corresponds to Tb in the paper.
 +
 +            /////////////////////////
 +            // less important parameters - things you might change but be carefull
 +            ////////////////////////
 +
 +            float backgroundRatio;
 +            // corresponds to fTB=1-cf from the paper
 +            // TB - threshold when the component becomes significant enough to be included into
 +            // the background model. It is the TB=1-cf from the paper. So I use cf=0.1 => TB=0.
 +            // For alpha=0.001 it means that the mode should exist for approximately 105 frames before
 +            // it is considered foreground
 +            // float noiseSigma;
 +            float varThresholdGen;
 +
 +            //correspondts to Tg - threshold on the squared Mahalan. dist. to decide
 +            //when a sample is close to the existing components. If it is not close
 +            //to any a new component will be generated. I use 3 sigma => Tg=3*3=9.
 +            //Smaller Tg leads to more generated components and higher Tg might make
 +            //lead to small number of components but they can grow too large
 +            float fVarInit;
 +            float fVarMin;
 +            float fVarMax;
 +
 +            //initial variance  for the newly generated components.
 +            //It will will influence the speed of adaptation. A good guess should be made.
 +            //A simple way is to estimate the typical standard deviation from the images.
 +            //I used here 10 as a reasonable value
 +            // min and max can be used to further control the variance
 +            float fCT; //CT - complexity reduction prior
 +            //this is related to the number of samples needed to accept that a component
 +            //actually exists. We use CT=0.05 of all the samples. By setting CT=0 you get
 +            //the standard Stauffer&Grimson algorithm (maybe not exact but very similar)
 +
 +            //shadow detection parameters
 +            bool bShadowDetection; //default 1 - do shadow detection
 +            unsigned char nShadowDetection; //do shadow detection - insert this value as the detection result - 127 default value
 +            float fTau;
 +            // Tau - shadow threshold. The shadow is detected if the pixel is darker
 +            //version of the background. Tau is a threshold on how much darker the shadow can be.
 +            //Tau= 0.5 means that if pixel is more than 2 times darker then it is not shadow
 +            //See: Prati,Mikic,Trivedi,Cucchiarra,"Detecting Moving Shadows...",IEEE PAMI,2003.
 +
 +        private:
 +            int nmixtures_;
 +
 +            Size frameSize_;
 +            int frameType_;
 +            int nframes_;
 +
 +            oclMat weight_;
 +            oclMat variance_;
 +            oclMat mean_;
 +
 +            oclMat bgmodelUsedModes_; //keep track of number of modes per pixel
 +        };
++
++        /*!***************Kalman Filter*************!*/
++        class CV_EXPORTS KalmanFilter
++        {
++        public:
++            KalmanFilter();
++            //! the full constructor taking the dimensionality of the state, of the measurement and of the control vector
++            KalmanFilter(int dynamParams, int measureParams, int controlParams=0, int type=CV_32F);
++            //! re-initializes Kalman filter. The previous content is destroyed.
++            void init(int dynamParams, int measureParams, int controlParams=0, int type=CV_32F);
++
++            const oclMat& predict(const oclMat& control=oclMat());
++            const oclMat& correct(const oclMat& measurement);
++
++            oclMat statePre;           //!< predicted state (x'(k)): x(k)=A*x(k-1)+B*u(k)
++            oclMat statePost;          //!< corrected state (x(k)): x(k)=x'(k)+K(k)*(z(k)-H*x'(k))
++            oclMat transitionMatrix;   //!< state transition matrix (A)
++            oclMat controlMatrix;      //!< control matrix (B) (not used if there is no control)
++            oclMat measurementMatrix;  //!< measurement matrix (H)
++            oclMat processNoiseCov;    //!< process noise covariance matrix (Q)
++            oclMat measurementNoiseCov;//!< measurement noise covariance matrix (R)
++            oclMat errorCovPre;        //!< priori error estimate covariance matrix (P'(k)): P'(k)=A*P(k-1)*At + Q)*/
++            oclMat gain;               //!< Kalman gain matrix (K(k)): K(k)=P'(k)*Ht*inv(H*P'(k)*Ht+R)
++            oclMat errorCovPost;       //!< posteriori error estimate covariance matrix (P(k)): P(k)=(I-K(k)*H)*P'(k)
++        private:
++            oclMat temp1;
++            oclMat temp2;
++            oclMat temp3;
++            oclMat temp4;
++            oclMat temp5;
++        };
++
++        static inline size_t divUp(size_t total, size_t grain)
++        {
++            return (total + grain - 1) / grain;
++        }
++
++        /*!***************K Nearest Neighbour*************!*/
++        class CV_EXPORTS KNearestNeighbour: public CvKNearest
++        {
++        public:
++            KNearestNeighbour();
++            ~KNearestNeighbour();
++
++            bool train(const Mat& trainData, Mat& labels, Mat& sampleIdx = Mat().setTo(Scalar::all(0)),
++                bool isRegression = false, int max_k = 32, bool updateBase = false);
++
++            void clear();
++
++            void find_nearest(const oclMat& samples, int k, oclMat& lables);
++
++        private:
++            oclMat samples_ocl;
++        };
++        /*!***************  SVM  *************!*/
++        class CV_EXPORTS CvSVM_OCL : public CvSVM
++        {
++        public:
++            CvSVM_OCL();
++
++            CvSVM_OCL(const cv::Mat& trainData, const cv::Mat& responses,
++                      const cv::Mat& varIdx=cv::Mat(), const cv::Mat& sampleIdx=cv::Mat(),
++                      CvSVMParams params=CvSVMParams());
++            CV_WRAP float predict( const int row_index, Mat& src, bool returnDFVal=false ) const;
++            CV_WRAP void predict( cv::InputArray samples, cv::OutputArray results ) const;
++            CV_WRAP float predict( const cv::Mat& sample, bool returnDFVal=false ) const;
++            float predict( const CvMat* samples, CV_OUT CvMat* results ) const;
++
++        protected:
++            float predict( const int row_index, int row_len, Mat& src, bool returnDFVal=false ) const;
++            void create_kernel();
++            void create_solver();
++        };
++        /*!***************  END  *************!*/
 +    }
 +}
 +#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__ */
@@@ -167,13 -167,7 +167,15 @@@ namespace c
          template<>
          bool CV_EXPORTS queryDeviceInfo<IS_CPU_DEVICE, bool>(cl_kernel kernel);
  
 +        //only these three specializations are implemented at the moment
 +        template<>
 +        int CV_EXPORTS queryDeviceInfo<WAVEFRONT_SIZE, int>(cl_kernel kernel);
 +        template<>
 +        size_t CV_EXPORTS queryDeviceInfo<WAVEFRONT_SIZE, size_t>(cl_kernel kernel);
 +        template<>
 +        bool CV_EXPORTS queryDeviceInfo<IS_CPU_DEVICE, bool>(cl_kernel kernel);
++
+         unsigned long CV_EXPORTS queryLocalMemInfo();
      }//namespace ocl
  
  }//namespace cv
@@@ -254,12 -258,13 +258,13 @@@ PERF_TEST_P(Video_MOG2GetBackgroundImag
              background.release();
              for (int i = 0; i < nFrame; i++)
              {
 -                mog2(frame_buffer[i], foreground);
 +                mog2->apply(frame_buffer[i], foreground);
              }
 -            mog2.getBackgroundImage(background);
 +            mog2->getBackgroundImage(background);
          }
          SANITY_CHECK(background);
-     }else if(RUN_OCL_IMPL)
+     }
+     else if(RUN_OCL_IMPL)
      {
          prepareData(frame_buffer, frame_buffer_ocl);
          CV_Assert((int)(frame_buffer_ocl.size()) == nFrame);
@@@ -109,344 -100,113 +99,113 @@@ namespace c
  //////////////////////////////////////////////////////////////////////////////
  /////////////////////// add subtract multiply divide /////////////////////////
  //////////////////////////////////////////////////////////////////////////////
- template<typename T>
- void arithmetic_run(const oclMat &src1, const oclMat &src2, oclMat &dst,
-                     String kernelName, const char **kernelString, void *_scalar, int op_type = 0)
- {
-     if(!src1.clCxt->supportsFeature(Context::CL_DOUBLE) && src1.type() == CV_64F)
-     {
-         CV_Error(Error::GpuNotSupported, "Selected device don't support double\r\n");
-         return;
-     }
-     dst.create(src1.size(), src1.type());
-     CV_Assert(src1.cols == src2.cols && src2.cols == dst.cols &&
-               src1.rows == src2.rows && src2.rows == dst.rows);
-     CV_Assert(src1.type() == src2.type() && src1.type() == dst.type());
-     CV_Assert(src1.depth() != CV_8S);
-     Context  *clCxt = src1.clCxt;
-     int channels = dst.oclchannels();
-     int depth = dst.depth();
-     int vector_lengths[4][7] = {{4, 0, 4, 4, 1, 1, 1},
-         {4, 0, 4, 4, 1, 1, 1},
-         {4, 0, 4, 4, 1, 1, 1},
-         {4, 0, 4, 4, 1, 1, 1}
-     };
-     size_t vector_length = vector_lengths[channels - 1][depth];
-     int offset_cols = (dst.offset / dst.elemSize1()) & (vector_length - 1);
-     int cols = divUp(dst.cols * channels + offset_cols, vector_length);
  
-     size_t localThreads[3]  = { 64, 4, 1 };
-     size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
-                                 divUp(dst.rows, localThreads[1]) *localThreads[1],
-                                 1
-                               };
+ enum { ADD = 0, SUB, MUL, DIV, ABS_DIFF };
  
-     int dst_step1 = dst.cols * dst.elemSize();
-     std::vector<std::pair<size_t , const void *> > args;
-     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.offset ));
-     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.offset ));
-     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.rows ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step1 ));
-     T scalar;
-     if(_scalar != NULL)
-     {
-         double scalar1 = *((double *)_scalar);
-         scalar = (T)scalar1;
-         args.push_back( std::make_pair( sizeof(T), (void *)&scalar ));
-     }
-     switch(op_type)
-     {
-         case MAT_ADD:
-             openCLExecuteKernel(clCxt, kernelString, kernelName, globalThreads, localThreads, args, -1, depth, "-D ARITHM_ADD");
-             break;
-         case MAT_SUB:
-             openCLExecuteKernel(clCxt, kernelString, kernelName, globalThreads, localThreads, args, -1, depth, "-D ARITHM_SUB");
-             break;
-         default:
-             openCLExecuteKernel(clCxt, kernelString, kernelName, globalThreads, localThreads, args, -1, depth);
-     }
- }
- static void arithmetic_run(const oclMat &src1, const oclMat &src2, oclMat &dst,
-                            String kernelName, const char **kernelString, int op_type = 0)
- {
-     arithmetic_run<char>(src1, src2, dst, kernelName, kernelString, (void *)NULL, op_type);
- }
- static void arithmetic_run(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask,
-                            String kernelName, const char **kernelString, int op_type = 0)
+ static void arithmetic_run_generic(const oclMat &src1, const oclMat &src2, const Scalar & scalar, const oclMat & mask,
+                             oclMat &dst, int op_type, bool use_scalar = false)
  {
-     if(!src1.clCxt->supportsFeature(Context::CL_DOUBLE) && src1.type() == CV_64F)
+     Context *clCxt = src1.clCxt;
+     bool hasDouble = clCxt->supportsFeature(Context::CL_DOUBLE);
+     if (!hasDouble && (src1.depth() == CV_64F || src2.depth() == CV_64F || dst.depth() == CV_64F))
      {
-         CV_Error(Error::GpuNotSupported, "Selected device don't support double\r\n");
 -        CV_Error(CV_GpuNotSupported, "Selected device doesn't support double\r\n");
++        CV_Error(Error::GpuNotSupported, "Selected device doesn't support double\r\n");
          return;
      }
  
+     CV_Assert(src2.empty() || (!src2.empty() && src1.type() == src2.type() && src1.size() == src2.size()));
+     CV_Assert(mask.empty() || (!mask.empty() && mask.type() == CV_8UC1 && mask.size() == src1.size()));
+     CV_Assert(op_type >= ADD && op_type <= ABS_DIFF);
      dst.create(src1.size(), src1.type());
-     CV_Assert(src1.cols == src2.cols && src2.cols == dst.cols &&
-               src1.rows == src2.rows && src2.rows == dst.rows &&
-               src1.rows == mask.rows && src1.cols == mask.cols);
  
-     CV_Assert(src1.type() == src2.type() && src1.type() == dst.type());
-     CV_Assert(src1.depth() != CV_8S);
-     CV_Assert(mask.type() == CV_8U);
+     int oclChannels = src1.oclchannels(), depth = src1.depth();
+     int src1step1 = src1.step / src1.elemSize(), src1offset1 = src1.offset / src1.elemSize();
+     int src2step1 = src2.step / src2.elemSize(), src2offset1 = src2.offset / src2.elemSize();
+     int maskstep1 = mask.step, maskoffset1 = mask.offset / mask.elemSize();
+     int dststep1 = dst.step / dst.elemSize(), dstoffset1 = dst.offset / dst.elemSize();
+     oclMat m;
  
-     Context  *clCxt = src1.clCxt;
-     int channels = dst.oclchannels();
-     int depth = dst.depth();
+     size_t localThreads[3]  = { 16, 16, 1 };
+     size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
  
-     int vector_lengths[4][7] = {{4, 4, 2, 2, 1, 1, 1},
-         {2, 2, 1, 1, 1, 1, 1},
-         {4, 4, 2, 2 , 1, 1, 1},
-         {1, 1, 1, 1, 1, 1, 1}
-     };
+     std::string kernelName = op_type == ABS_DIFF ? "arithm_absdiff" : "arithm_binary_op";
  
-     size_t vector_length = vector_lengths[channels - 1][depth];
-     int offset_cols = ((dst.offset % dst.step) / dst.elemSize()) & (vector_length - 1);
-     int cols = divUp(dst.cols + offset_cols, vector_length);
+     const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
+     const char * const WTypeMap[] = { "short", "short", "int", "int", "int", "float", "double" };
+     const char operationsMap[] = { '+', '-', '*', '/', '-' };
+     const char * const channelMap[] = { "", "", "2", "4", "4" };
+     bool haveScalar = use_scalar || src2.empty();
  
-     size_t localThreads[3]  = { 64, 4, 1 };
-     size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
-                                 divUp(dst.rows, localThreads[1]) *localThreads[1],
-                                 1
-                               };
+     int WDepth = depth;
+     if (haveScalar)
+         WDepth = hasDouble && WDepth == CV_64F ? CV_64F : CV_32F;
+     if (op_type == DIV)
+         WDepth = hasDouble ? CV_64F : CV_32F;
+     else if (op_type == MUL)
+         WDepth = hasDouble && (depth == CV_32S || depth == CV_64F) ? CV_64F : CV_32F;
+     std::string buildOptions = format("-D T=%s%s -D WT=%s%s -D convertToT=convert_%s%s%s -D Operation=%c"
+                                       " -D convertToWT=convert_%s%s",
+                                       typeMap[depth], channelMap[oclChannels],
+                                       WTypeMap[WDepth], channelMap[oclChannels],
+                                       typeMap[depth], channelMap[oclChannels], (depth >= CV_32F ? "" : (depth == CV_32S ? "_rte" : "_sat_rte")),
+                                       operationsMap[op_type], WTypeMap[WDepth], channelMap[oclChannels]);
  
-     int dst_step1 = dst.cols * dst.elemSize();
 -    vector<pair<size_t , const void *> > args;
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src1.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1step1 ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1offset1 ));
 +    std::vector<std::pair<size_t , const void *> > args;
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.offset ));
-     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.offset ));
-     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mask.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&mask.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&mask.offset ));
-     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.rows ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1step1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1offset1 ));
  
-     switch (op_type)
+     if (!src2.empty())
      {
-         case MAT_ADD:
-             openCLExecuteKernel(clCxt, kernelString, kernelName, globalThreads, localThreads, args, channels, depth, "-D ARITHM_ADD");
-             break;
-         case MAT_SUB:
-             openCLExecuteKernel(clCxt, kernelString, kernelName, globalThreads, localThreads, args, channels, depth, "-D ARITHM_SUB");
-             break;
-         default:
-             openCLExecuteKernel(clCxt, kernelString, kernelName, globalThreads, localThreads, args, channels, depth);
-     }
- }
- void cv::ocl::add(const oclMat &src1, const oclMat &src2, oclMat &dst)
- {
-     arithmetic_run(src1, src2, dst, "arithm_add", &arithm_add, MAT_ADD);
- }
- void cv::ocl::add(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask)
- {
-     arithmetic_run(src1, src2, dst, mask, "arithm_add_with_mask", &arithm_add, MAT_ADD);
- }
- void cv::ocl::subtract(const oclMat &src1, const oclMat &src2, oclMat &dst)
- {
-     arithmetic_run(src1, src2, dst, "arithm_add", &arithm_add, MAT_SUB);
- }
- void cv::ocl::subtract(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask)
- {
-     arithmetic_run(src1, src2, dst, mask, "arithm_add_with_mask", &arithm_add, MAT_SUB);
- }
- typedef void (*MulDivFunc)(const oclMat &src1, const oclMat &src2, oclMat &dst, String kernelName,
-                            const char **kernelString, void *scalar);
- void cv::ocl::multiply(const oclMat &src1, const oclMat &src2, oclMat &dst, double scalar)
- {
-     if(src1.clCxt->supportsFeature(Context::CL_DOUBLE) && (src1.depth() == CV_64F))
-         arithmetic_run<double>(src1, src2, dst, "arithm_mul", &arithm_mul, (void *)(&scalar));
-     else
-         arithmetic_run<float>(src1, src2, dst, "arithm_mul", &arithm_mul, (void *)(&scalar));
- }
- void cv::ocl::divide(const oclMat &src1, const oclMat &src2, oclMat &dst, double scalar)
- {
-     if(src1.clCxt->supportsFeature(Context::CL_DOUBLE))
-         arithmetic_run<double>(src1, src2, dst, "arithm_div", &arithm_div, (void *)(&scalar));
-     else
-         arithmetic_run<float>(src1, src2, dst, "arithm_div", &arithm_div, (void *)(&scalar));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&src2.data ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&src2step1 ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&src2offset1 ));
++        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
++        args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2step1 ));
++        args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2offset1 ));
  
- }
- template <typename WT , typename CL_WT>
- void arithmetic_scalar_run(const oclMat &src1, const Scalar &src2, oclMat &dst, const oclMat &mask, String kernelName, const char **kernelString, int isMatSubScalar)
- {
-     if(!src1.clCxt->supportsFeature(Context::CL_DOUBLE) && src1.type() == CV_64F)
-     {
-         CV_Error(Error::GpuNotSupported, "Selected device don't support double\r\n");
-         return;
+         kernelName += "_mat";
      }
  
-     dst.create(src1.size(), src1.type());
-     CV_Assert(src1.cols == dst.cols && src1.rows == dst.rows &&
-               src1.type() == dst.type());
-     //CV_Assert(src1.depth() != CV_8S);
-     if(mask.data)
+     if (haveScalar)
      {
-         CV_Assert(mask.type() == CV_8U && src1.rows == mask.rows && src1.cols == mask.cols);
-     }
-     Context  *clCxt = src1.clCxt;
-     int channels = dst.oclchannels();
-     int depth = dst.depth();
-     WT s[4] = { saturate_cast<WT>(src2.val[0]), saturate_cast<WT>(src2.val[1]),
-                 saturate_cast<WT>(src2.val[2]), saturate_cast<WT>(src2.val[3])
-               };
-     int vector_lengths[4][7] = {{4, 0, 2, 2, 1, 1, 1},
-         {2, 0, 1, 1, 1, 1, 1},
-         {4, 0, 2, 2 , 1, 1, 1},
-         {1, 0, 1, 1, 1, 1, 1}
-     };
-     size_t vector_length = vector_lengths[channels - 1][depth];
-     int offset_cols = ((dst.offset % dst.step) / dst.elemSize()) & (vector_length - 1);
-     int cols = divUp(dst.cols + offset_cols, vector_length);
+         const int WDepthMap[] = { CV_16S, CV_16S, CV_32S, CV_32S, CV_32S, CV_32F, CV_64F };
+         m.create(1, 1, CV_MAKE_TYPE(WDepthMap[WDepth], oclChannels));
+         m.setTo(scalar);
  
-     size_t localThreads[3]  = { 64, 4, 1 };
-     size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
-                                 divUp(dst.rows, localThreads[1]) *localThreads[1],
-                                 1
-                               };
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&m.data ));
++        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&m.data ));
  
-     int dst_step1 = dst.cols * dst.elemSize();
-     std::vector<std::pair<size_t , const void *> > args;
-     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src1.data ));
-     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src1.step ));
-     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src1.offset));
-     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst.data ));
-     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst.step ));
-     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst.offset));
-     if(mask.data)
-     {
-         args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&mask.data ));
-         args.push_back( std::make_pair( sizeof(cl_int) , (void *)&mask.step ));
-         args.push_back( std::make_pair( sizeof(cl_int) , (void *)&mask.offset));
+         kernelName += "_scalar";
      }
-     args.push_back( std::make_pair( sizeof(CL_WT) ,  (void *)&s ));
-     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src1.rows ));
-     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&cols ));
-     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst_step1 ));
-     if(isMatSubScalar != 0)
-         openCLExecuteKernel(clCxt, kernelString, kernelName, globalThreads, localThreads, args, channels, depth, "-D ARITHM_SUB");
-     else
-         openCLExecuteKernel(clCxt, kernelString, kernelName, globalThreads, localThreads, args, channels, depth, "-D ARITHM_ADD");
- }
  
- static void arithmetic_scalar_run(const oclMat &src, oclMat &dst, String kernelName, const char **kernelString, double scalar)
- {
-     if(!src.clCxt->supportsFeature(Context::CL_DOUBLE) && src.type() == CV_64F)
+     if (!mask.empty())
      {
-         CV_Error(Error::GpuNotSupported, "Selected device don't support double\r\n");
-         return;
-     }
-     dst.create(src.size(), src.type());
-     CV_Assert(src.cols == dst.cols && src.rows == dst.rows);
-     CV_Assert(src.type() == dst.type());
-     CV_Assert(src.depth() != CV_8S);
-     Context  *clCxt = src.clCxt;
-     int channels = dst.oclchannels();
-     int depth = dst.depth();
-     int vector_lengths[4][7] = {{4, 0, 4, 4, 1, 1, 1},
-         {4, 0, 4, 4, 1, 1, 1},
-         {4, 0, 4, 4 , 1, 1, 1},
-         {4, 0, 4, 4, 1, 1, 1}
-     };
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&mask.data ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&maskstep1 ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&maskoffset1 ));
++        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mask.data ));
++        args.push_back( std::make_pair( sizeof(cl_int), (void *)&maskstep1 ));
++        args.push_back( std::make_pair( sizeof(cl_int), (void *)&maskoffset1 ));
  
-     size_t vector_length = vector_lengths[channels - 1][depth];
-     int offset_cols = (dst.offset / dst.elemSize1()) & (vector_length - 1);
-     int cols = divUp(dst.cols * channels + offset_cols, vector_length);
+         kernelName += "_mask";
+     }
  
-     size_t localThreads[3]  = { 64, 4, 1 };
-     size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
-                                 divUp(dst.rows, localThreads[1]) *localThreads[1],
-                                 1
-                               };
+     if (op_type == DIV)
+         kernelName += "_div";
  
-     int dst_step1 = dst.cols * dst.elemSize();
-     std::vector<std::pair<size_t , const void *> > args;
-     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.offset ));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dststep1 ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dstoffset1 ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.rows ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dststep1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dstoffset1 ));
  
-     float f_scalar = (float)scalar;
-     if(src.clCxt->supportsFeature(Context::CL_DOUBLE))
-         args.push_back( std::make_pair( sizeof(cl_double), (void *)&scalar ));
-     else
-     {
-         args.push_back( std::make_pair( sizeof(cl_float), (void *)&f_scalar));
-     }
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1.cols ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1.rows ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.cols ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.rows ));
  
-     openCLExecuteKernel(clCxt, kernelString, kernelName, globalThreads, localThreads, args, -1, depth);
+     openCLExecuteKernel(clCxt, mask.empty() ?
+                             (!src2.empty() ? &arithm_add : &arithm_add_scalar) :
+                             (!src2.empty() ? &arithm_add_mask : &arithm_add_scalar_mask),
+                         kernelName, globalThreads, localThreads,
+                         args, -1, -1, buildOptions.c_str());
  }
  
- typedef void (*ArithmeticFuncS)(const oclMat &src1, const Scalar &src2, oclMat &dst, const oclMat &mask, String kernelName, const char **kernelString, int isMatSubScalar);
- static void arithmetic_scalar(const oclMat &src1, const Scalar &src2, oclMat &dst, const oclMat &mask, String kernelName, const char **kernelString, int isMatSubScalar)
- {
-     static ArithmeticFuncS tab[8] =
-     {
-         arithmetic_scalar_run<int, cl_int4>,
-         arithmetic_scalar_run<int, cl_int4>,
-         arithmetic_scalar_run<int, cl_int4>,
-         arithmetic_scalar_run<int, cl_int4>,
-         arithmetic_scalar_run<int, cl_int4>,
-         arithmetic_scalar_run<float, cl_float4>,
-         arithmetic_scalar_run<double, cl_double4>,
-         0
-     };
-     ArithmeticFuncS func = tab[src1.depth()];
-     if(func == 0)
-         cv::error(Error::StsBadArg, "Unsupported arithmetic operation", "", __FILE__, __LINE__);
-     func(src1, src2, dst, mask, kernelName, kernelString, isMatSubScalar);
- }
- static void arithmetic_scalar(const oclMat &src1, const Scalar &src2, oclMat &dst, const oclMat &mask, String kernelName, const char **kernelString)
+ void cv::ocl::add(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask)
  {
-     arithmetic_scalar(src1, src2, dst, mask, kernelName, kernelString, 0);
+     arithmetic_run_generic(src1, src2, Scalar(), mask, dst, ADD);
  }
  
  void cv::ocl::add(const oclMat &src1, const Scalar &src2, oclMat &dst, const oclMat &mask)
@@@ -503,78 -263,55 +262,55 @@@ void cv::ocl::absdiff(const oclMat &src
  //////////////////////////////////////////////////////////////////////////////
  /////////////////////////////////  compare ///////////////////////////////////
  //////////////////////////////////////////////////////////////////////////////
- static void compare_run(const oclMat &src1, const oclMat &src2, oclMat &dst, String kernelName, const char **kernelString)
+ static void compare_run(const oclMat &src1, const oclMat &src2, oclMat &dst, int cmpOp,
 -                        string kernelName, const char **kernelString)
++                        String kernelName, const char **kernelString)
  {
-     dst.create(src1.size(), CV_8UC1);
-     CV_Assert(src1.oclchannels() == 1);
      CV_Assert(src1.type() == src2.type());
-     Context  *clCxt = src1.clCxt;
+     dst.create(src1.size(), CV_8UC1);
+     Context *clCxt = src1.clCxt;
      int depth = src1.depth();
-     int vector_lengths[7] = {4, 0, 4, 4, 4, 4, 4};
-     size_t vector_length = vector_lengths[depth];
-     int offset_cols = (dst.offset / dst.elemSize1()) & (vector_length - 1);
-     int cols = divUp(dst.cols  + offset_cols, vector_length);
      size_t localThreads[3]  = { 64, 4, 1 };
-     size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
-                                 divUp(dst.rows, localThreads[1]) *localThreads[1],
-                                 1
-                               };
-     int dst_step1 = dst.cols * dst.elemSize();
+     size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
+     int src1step1 = src1.step1(), src1offset1 = src1.offset / src1.elemSize1();
+     int src2step1 = src2.step1(), src2offset1 = src2.offset / src2.elemSize1();
+     int dststep1 = dst.step1(), dstoffset1 = dst.offset / dst.elemSize1();
+     const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
+     const char * operationMap[] = { "==", ">", ">=", "<", "<=", "!=" };
+     std::string buildOptions = format("-D T=%s -D Operation=%s", typeMap[depth], operationMap[cmpOp]);
 -    vector<pair<size_t , const void *> > args;
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src1.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1step1 ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1offset1 ));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src2.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src2step1 ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src2offset1 ));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dststep1 ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dstoffset1 ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1.cols ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1.rows ));
 +    std::vector<std::pair<size_t , const void *> > args;
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.offset ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1step1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1offset1 ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.offset ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2step1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2offset1 ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dststep1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dstoffset1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.cols ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.rows ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step1 ));
-     openCLExecuteKernel(clCxt, kernelString, kernelName, globalThreads, localThreads, args, -1, depth);
+     openCLExecuteKernel(clCxt, kernelString, kernelName, globalThreads, localThreads,
+                         args, -1, -1, buildOptions.c_str());
  }
  
  void cv::ocl::compare(const oclMat &src1, const oclMat &src2, oclMat &dst , int cmpOp)
  {
-     if(!src1.clCxt->supportsFeature(Context::CL_DOUBLE) && src1.type() == CV_64F)
+     if (!src1.clCxt->supportsFeature(Context::CL_DOUBLE) && src1.depth() == CV_64F)
      {
 -        cout << "Selected device do not support double" << endl;
 +        std::cout << "Selected device do not support double" << std::endl;
          return;
      }
-     String kernelName;
-     const char **kernelString = NULL;
-     switch( cmpOp )
-     {
-     case CMP_EQ:
-         kernelName = "arithm_compare_eq";
-         kernelString = &arithm_compare_eq;
-         break;
-     case CMP_GT:
-         kernelName = "arithm_compare_gt";
-         kernelString = &arithm_compare_eq;
-         break;
-     case CMP_GE:
-         kernelName = "arithm_compare_ge";
-         kernelString = &arithm_compare_eq;
-         break;
-     case CMP_NE:
-         kernelName = "arithm_compare_ne";
-         kernelString = &arithm_compare_ne;
-         break;
-     case CMP_LT:
-         kernelName = "arithm_compare_lt";
-         kernelString = &arithm_compare_ne;
-         break;
-     case CMP_LE:
-         kernelName = "arithm_compare_le";
-         kernelString = &arithm_compare_ne;
-         break;
-     default:
-         CV_Error(Error::StsBadArg, "Unknown comparison method");
-     }
-     compare_run(src1, src2, dst, kernelName, kernelString);
+     CV_Assert(src1.channels() == 1 && src2.channels() == 1);
+     CV_Assert(cmpOp >= CMP_EQ && cmpOp <= CMP_NE);
+     compare_run(src1, src2, dst, cmpOp, "arithm_compare", &arithm_compare);
  }
  
  //////////////////////////////////////////////////////////////////////////////
@@@ -596,15 -333,15 +332,15 @@@ static void arithmetic_sum_buffer_run(c
      char build_options[512];
      CV_Assert(type == 0 || type == 1 || type == 2);
      sprintf(build_options, "-D DEPTH_%d -D REPEAT_S%d -D REPEAT_E%d -D FUNC_TYPE_%d", src.depth(), repeat_s, repeat_e, type);
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&cols ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&invalid_cols ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&offset));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&elemnum));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&groupnum));
 -    args.push_back( make_pair( sizeof(cl_mem) , (void *)&src.data));
 -    args.push_back( make_pair( sizeof(cl_mem) , (void *)&dst ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&cols ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&invalid_cols ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&offset));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&elemnum));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&groupnum));
 +    args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src.data));
 +    args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst ));
      size_t gt[3] = {groupnum * 256, 1, 1}, lt[3] = {256, 1, 1};
-     if(src.oclchannels() != 3)
+     if (src.oclchannels() != 3)
          openCLExecuteKernel(src.clCxt, &arithm_sum, "arithm_op_sum", gt, lt, args, -1, -1, build_options);
      else
          openCLExecuteKernel(src.clCxt, &arithm_sum_3, "arithm_op_sum_3", gt, lt, args, -1, -1, build_options);
@@@ -641,9 -376,9 +375,9 @@@ Scalar arithmetic_sum(const oclMat &src
  typedef Scalar (*sumFunc)(const oclMat &src, int type);
  Scalar cv::ocl::sum(const oclMat &src)
  {
-     if(!src.clCxt->supportsFeature(Context::CL_DOUBLE) && src.depth() == CV_64F)
+     if (!src.clCxt->supportsFeature(Context::CL_DOUBLE) && src.depth() == CV_64F)
      {
-         CV_Error(Error::GpuNotSupported, "select device don't support double");
 -        CV_Error(CV_GpuNotSupported, "Selected device doesn't support double");
++        CV_Error(Error::GpuNotSupported, "Selected device doesn't support double");
      }
      static sumFunc functab[2] =
      {
  
  Scalar cv::ocl::absSum(const oclMat &src)
  {
-     if(!src.clCxt->supportsFeature(Context::CL_DOUBLE) && src.depth() == CV_64F)
+     if (!src.clCxt->supportsFeature(Context::CL_DOUBLE) && src.depth() == CV_64F)
      {
-         CV_Error(Error::GpuNotSupported, "select device don't support double");
 -        CV_Error(CV_GpuNotSupported, "Selected device doesn't support double");
++        CV_Error(Error::GpuNotSupported, "Selected device doesn't support double");
      }
      static sumFunc functab[2] =
      {
  
  Scalar cv::ocl::sqrSum(const oclMat &src)
  {
-     if(!src.clCxt->supportsFeature(Context::CL_DOUBLE) && src.depth() == CV_64F)
+     if (!src.clCxt->supportsFeature(Context::CL_DOUBLE) && src.depth() == CV_64F)
      {
-         CV_Error(Error::GpuNotSupported, "select device don't support double");
 -        CV_Error(CV_GpuNotSupported, "Selected device doesn't support double");
++        CV_Error(Error::GpuNotSupported, "Selected device doesn't support double");
      }
      static sumFunc functab[2] =
      {
@@@ -715,9 -454,10 +453,10 @@@ void cv::ocl::meanStdDev(const oclMat &
  //////////////////////////////////////////////////////////////////////////////
  //////////////////////////////////// minMax  /////////////////////////////////
  //////////////////////////////////////////////////////////////////////////////
 -static void arithmetic_minMax_run(const oclMat &src, const oclMat &mask, cl_mem &dst, int vlen , int groupnum, string kernelName)
 +static void arithmetic_minMax_run(const oclMat &src, const oclMat &mask, cl_mem &dst, int vlen , int groupnum, String kernelName)
  {
 -    vector<pair<size_t , const void *> > args;
 +    std::vector<std::pair<size_t , const void *> > args;
      int all_cols = src.step / (vlen * src.elemSize1());
      int pre_cols = (src.offset % src.step) / (vlen * src.elemSize1());
      int sec_cols = all_cols - (src.offset % src.step + src.cols * src.elemSize() - 1) / (vlen * src.elemSize1()) - 1;
      int repeat_e = (offset + cols) * vlen - src.offset / src.elemSize1() - src.cols * src.oclchannels();
      char build_options[50];
      sprintf(build_options, "-D DEPTH_%d -D REPEAT_S%d -D REPEAT_E%d", src.depth(), repeat_s, repeat_e);
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&cols ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&invalid_cols ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&offset));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&elemnum));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&groupnum));
 -    args.push_back( make_pair( sizeof(cl_mem) , (void *)&src.data));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&cols ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&invalid_cols ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&offset));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&elemnum));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&groupnum));
 +    args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src.data));
-     if(!mask.empty())
+     if (!mask.empty())
      {
          int mall_cols = mask.step / (vlen * mask.elemSize1());
          int mpre_cols = (mask.offset % mask.step) / (vlen * mask.elemSize1());
  }
  
  
 -static void arithmetic_minMax_mask_run(const oclMat &src, const oclMat &mask, cl_mem &dst, int vlen, int groupnum, string kernelName)
 +static void arithmetic_minMax_mask_run(const oclMat &src, const oclMat &mask, cl_mem &dst, int vlen, int groupnum, String kernelName)
  {
 -    vector<pair<size_t , const void *> > args;
 +    std::vector<std::pair<size_t , const void *> > args;
      size_t gt[3] = {groupnum * 256, 1, 1}, lt[3] = {256, 1, 1};
      char build_options[50];
-     if(src.oclchannels() == 1)
+     if (src.oclchannels() == 1)
      {
          int cols = (src.cols - 1) / vlen + 1;
          int invalid_cols = src.step / (vlen * src.elemSize1()) - cols;
          int moffset = mask.offset / mask.elemSize1();
          int elemnum = cols * src.rows;
          sprintf(build_options, "-D DEPTH_%d -D REPEAT_E%d", src.depth(), repeat_me);
 -        args.push_back( make_pair( sizeof(cl_int) , (void *)&cols ));
 -        args.push_back( make_pair( sizeof(cl_int) , (void *)&invalid_cols ));
 -        args.push_back( make_pair( sizeof(cl_int) , (void *)&offset));
 -        args.push_back( make_pair( sizeof(cl_int) , (void *)&elemnum));
 -        args.push_back( make_pair( sizeof(cl_int) , (void *)&groupnum));
 -        args.push_back( make_pair( sizeof(cl_mem) , (void *)&src.data));
 -        args.push_back( make_pair( sizeof(cl_int) , (void *)&minvalid_cols ));
 -        args.push_back( make_pair( sizeof(cl_int) , (void *)&moffset ));
 -        args.push_back( make_pair( sizeof(cl_mem) , (void *)&mask.data ));
 -        args.push_back( make_pair( sizeof(cl_mem) , (void *)&dst ));
 +        args.push_back( std::make_pair( sizeof(cl_int) , (void *)&cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int) , (void *)&invalid_cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int) , (void *)&offset));
 +        args.push_back( std::make_pair( sizeof(cl_int) , (void *)&elemnum));
 +        args.push_back( std::make_pair( sizeof(cl_int) , (void *)&groupnum));
 +        args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src.data));
 +        args.push_back( std::make_pair( sizeof(cl_int) , (void *)&minvalid_cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int) , (void *)&moffset ));
 +        args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&mask.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst ));
-         //        printf("elemnum:%d,cols:%d,invalid_cols:%d,offset:%d,minvalid_cols:%d,moffset:%d,repeat_e:%d\r\n",
-         //               elemnum,cols,invalid_cols,offset,minvalid_cols,moffset,repeat_me);
          openCLExecuteKernel(src.clCxt, &arithm_minMax_mask, kernelName, gt, lt, args, -1, -1, build_options);
      }
  }
@@@ -834,9 -573,9 +572,9 @@@ void cv::ocl::minMax(const oclMat &src
  void cv::ocl::minMax_buf(const oclMat &src, double *minVal, double *maxVal, const oclMat &mask, oclMat &buf)
  {
      CV_Assert(src.oclchannels() == 1);
-     if(!src.clCxt->supportsFeature(Context::CL_DOUBLE) && src.depth() == CV_64F)
+     if (!src.clCxt->supportsFeature(Context::CL_DOUBLE) && src.depth() == CV_64F)
      {
-         CV_Error(Error::GpuNotSupported, "select device don't support double");
 -        CV_Error(CV_GpuNotSupported, "Selected device doesn't support double");
++        CV_Error(Error::GpuNotSupported, "Selected device doesn't support double");
      }
      static minMaxFunc functab[8] =
      {
@@@ -916,11 -656,12 +655,12 @@@ double cv::ocl::norm(const oclMat &src1
  //////////////////////////////////////////////////////////////////////////////
  ////////////////////////////////// flip //////////////////////////////////////
  //////////////////////////////////////////////////////////////////////////////
 -static void arithmetic_flip_rows_run(const oclMat &src, oclMat &dst, string kernelName)
 +static void arithmetic_flip_rows_run(const oclMat &src, oclMat &dst, String kernelName)
  {
-     if(!src.clCxt->supportsFeature(Context::CL_DOUBLE) && src.type() == CV_64F)
+     if (!src.clCxt->supportsFeature(Context::CL_DOUBLE) && src.type() == CV_64F)
      {
-         CV_Error(Error::GpuNotSupported, "Selected device don't support double\r\n");
 -        CV_Error(CV_GpuNotSupported, "Selected device doesn't support double\r\n");
++        CV_Error(Error::GpuNotSupported, "Selected device doesn't support double\r\n");
          return;
      }
  
      int rows = divUp(dst.rows, 2);
  
      size_t localThreads[3]  = { 64, 4, 1 };
-     size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
-                                 divUp(rows, localThreads[1]) *localThreads[1],
-                                 1
-                               };
+     size_t globalThreads[3] = { cols, rows, 1 };
  
      int dst_step1 = dst.cols * dst.elemSize();
 -    vector<pair<size_t , const void *> > args;
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src.offset ));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.offset ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.rows ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&cols ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&rows ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst_step1 ));
 +    std::vector<std::pair<size_t , const void *> > args;
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.offset ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.rows ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&rows ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step1 ));
  
      openCLExecuteKernel(clCxt, &arithm_flip, kernelName, globalThreads, localThreads, args, -1, depth);
  }
 -static void arithmetic_flip_cols_run(const oclMat &src, oclMat &dst, string kernelName, bool isVertical)
 +static void arithmetic_flip_cols_run(const oclMat &src, oclMat &dst, String kernelName, bool isVertical)
  {
-     if(!src.clCxt->supportsFeature(Context::CL_DOUBLE) && src.type() == CV_64F)
+     if (!src.clCxt->supportsFeature(Context::CL_DOUBLE) && src.type() == CV_64F)
      {
-         CV_Error(Error::GpuNotSupported, "Selected device don't support double\r\n");
 -        CV_Error(CV_GpuNotSupported, "Selected device doesn't support double\r\n");
++        CV_Error(Error::GpuNotSupported, "Selected device doesn't support double\r\n");
          return;
      }
  
      int rows = isVertical ?  divUp(dst.rows, 2) : dst.rows;
  
      size_t localThreads[3]  = { 64, 4, 1 };
-     size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
-                                 divUp(rows, localThreads[1]) *localThreads[1],
-                                 1
-                               };
+     size_t globalThreads[3] = { cols, rows, 1 };
  
      int dst_step1 = dst.cols * dst.elemSize();
 -    vector<pair<size_t , const void *> > args;
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src.offset ));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.offset ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.rows ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.cols ));
 +    std::vector<std::pair<size_t , const void *> > args;
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.offset ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.rows ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.cols ));
  
-     if(isVertical)
+     if (isVertical)
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&rows ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&rows ));
      else
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
  
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst_step1 ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step1 ));
  
      const char **kernelString = isVertical ? &arithm_flip_rc : &arithm_flip;
  
@@@ -1036,143 -773,90 +772,90 @@@ void cv::ocl::flip(const oclMat &src, o
  //////////////////////////////////////////////////////////////////////////////
  ////////////////////////////////// LUT  //////////////////////////////////////
  //////////////////////////////////////////////////////////////////////////////
- static void arithmetic_lut_run(const oclMat &src1, const oclMat &src2, oclMat &dst, String kernelName)
 -static void arithmetic_lut_run(const oclMat &src, const oclMat &lut, oclMat &dst, string kernelName)
++static void arithmetic_lut_run(const oclMat &src, const oclMat &lut, oclMat &dst, String kernelName)
  {
-     Context *clCxt = src1.clCxt;
-     int channels = src1.oclchannels();
-     int rows = src1.rows;
-     int cols = src1.cols;
-     //int step = src1.step;
-     int src_step = src1.step / src1.elemSize();
-     int dst_step = dst.step / dst.elemSize();
-     int whole_rows = src1.wholerows;
-     int whole_cols = src1.wholecols;
-     int src_offset = src1.offset / src1.elemSize();
-     int dst_offset = dst.offset / dst.elemSize();
-     int lut_offset = src2.offset / src2.elemSize();
-     int left_col = 0, right_col = 0;
-     size_t localSize[] = {16, 16, 1};
-     //cl_kernel kernel = openCLGetKernelFromSource(clCxt,&arithm_LUT,kernelName);
-     size_t globalSize[] = {(cols + localSize[0] - 1) / localSize[0] *localSize[0], (rows + localSize[1] - 1) / localSize[1] *localSize[1], 1};
-     if(channels == 1 && cols > 6)
-     {
-         left_col = 4 - (dst_offset & 3);
-         left_col &= 3;
-         dst_offset += left_col;
-         src_offset += left_col;
-         cols -= left_col;
-         right_col = cols & 3;
-         cols -= right_col;
-         globalSize[0] = (cols / 4 + localSize[0] - 1) / localSize[0] * localSize[0];
-     }
-     else if(channels == 1)
-     {
-         left_col = cols;
-         right_col = 0;
-         cols = 0;
-         globalSize[0] = 0;
-     }
-     CV_Assert(clCxt == dst.clCxt);
-     CV_Assert(src1.cols == dst.cols);
-     CV_Assert(src1.rows == dst.rows);
-     CV_Assert(src1.oclchannels() == dst.oclchannels());
-     //  CV_Assert(src1.step == dst.step);
-     std::vector<std::pair<size_t , const void *> > args;
+     Context *clCxt = src.clCxt;
+     int sdepth = src.depth();
+     int src_step1 = src.step1(), dst_step1 = dst.step1();
+     int src_offset1 = src.offset / src.elemSize1(), dst_offset1 = dst.offset / dst.elemSize1();
+     int lut_offset1 = lut.offset / lut.elemSize1() + (sdepth == CV_8U ? 0 : 128) * lut.channels();
+     int cols1 = src.cols * src.oclchannels();
  
-     if(globalSize[0] != 0)
-     {
-         args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
-         args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
-         args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
-         args.push_back( std::make_pair( sizeof(cl_int), (void *)&rows ));
-         args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
-         args.push_back( std::make_pair( sizeof(cl_int), (void *)&channels ));
-         args.push_back( std::make_pair( sizeof(cl_int), (void *)&whole_rows ));
-         args.push_back( std::make_pair( sizeof(cl_int), (void *)&whole_cols ));
-         args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_offset ));
-         args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_offset ));
-         args.push_back( std::make_pair( sizeof(cl_int), (void *)&lut_offset ));
-         args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_step ));
-         args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step ));
-         openCLExecuteKernel(clCxt, &arithm_LUT, kernelName, globalSize, localSize, args, src1.oclchannels(), src1.depth());
-     }
-     if(channels == 1 && (left_col != 0 || right_col != 0))
-     {
-         src_offset = src1.offset;
-         dst_offset = dst.offset;
-         localSize[0] = 1;
-         localSize[1] = 256;
-         globalSize[0] = left_col + right_col;
-         globalSize[1] = (rows + localSize[1] - 1) / localSize[1] * localSize[1];
-         //kernel = openCLGetKernelFromSource(clCxt,&arithm_LUT,"LUT2");
-         args.clear();
-         args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
-         args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
-         args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
-         args.push_back( std::make_pair( sizeof(cl_int), (void *)&rows ));
-         args.push_back( std::make_pair( sizeof(cl_int), (void *)&left_col ));
-         args.push_back( std::make_pair( sizeof(cl_int), (void *)&channels ));
-         args.push_back( std::make_pair( sizeof(cl_int), (void *)&whole_rows ));
-         args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
-         args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_offset ));
-         args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_offset ));
-         args.push_back( std::make_pair( sizeof(cl_int), (void *)&lut_offset ));
-         args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_step ));
-         args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step ));
-         openCLExecuteKernel(clCxt, &arithm_LUT, "LUT2", globalSize, localSize, args, src1.oclchannels(), src1.depth());
-     }
- }
+     size_t localSize[] = { 16, 16, 1 };
+     size_t globalSize[] = { lut.channels() == 1 ? cols1 : src.cols, src.rows, 1 };
  
- void cv::ocl::LUT(const oclMat &src, const oclMat &lut, oclMat &dst)
+     const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
+     std::string buildOptions = format("-D srcT=%s -D dstT=%s", typeMap[sdepth], typeMap[dst.depth()]);
 -    vector<pair<size_t , const void *> > args;
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src.data ));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&lut.data ));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&cols1));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src.rows ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src_offset1 ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&lut_offset1 ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst_offset1 ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src_step1 ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst_step1 ));
++    std::vector<std::pair<size_t , const void *> > args;
++    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&lut.data ));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols1));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.rows ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_offset1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&lut_offset1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_offset1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_step1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step1 ));
+     openCLExecuteKernel(clCxt, &arithm_LUT, kernelName, globalSize, localSize,
+                         args, lut.oclchannels(), -1, buildOptions.c_str());
+ }
+ void cv::ocl::LUT(const oclMat &src, const oclMat &lut, oclMat &dst)
  {
-     int cn = src.channels();
-     CV_Assert(src.depth() == CV_8U);
-     CV_Assert((lut.oclchannels() == 1 || lut.oclchannels() == cn) && lut.rows == 1 && lut.cols == 256);
+     int cn = src.channels(), depth = src.depth();
+     CV_Assert(depth == CV_8U || depth == CV_8S);
+     CV_Assert(lut.channels() == 1 || lut.channels() == src.channels());
+     CV_Assert(lut.rows == 1 && lut.cols == 256);
      dst.create(src.size(), CV_MAKETYPE(lut.depth(), cn));
-     //oclMat _lut(lut);
 -    string kernelName = "LUT";
 +    String kernelName = "LUT";
      arithmetic_lut_run(src, lut, dst, kernelName);
  }
  
  //////////////////////////////////////////////////////////////////////////////
  //////////////////////////////// exp log /////////////////////////////////////
  //////////////////////////////////////////////////////////////////////////////
 -static void arithmetic_exp_log_run(const oclMat &src, oclMat &dst, string kernelName, const char **kernelString)
 +static void arithmetic_exp_log_run(const oclMat &src, oclMat &dst, String kernelName, const char **kernelString)
  {
-     dst.create(src.size(), src.type());
-     CV_Assert(src.cols == dst.cols &&
-               src.rows == dst.rows );
-     CV_Assert(src.type() == dst.type());
-     CV_Assert( src.type() == CV_32F || src.type() == CV_64F);
      Context  *clCxt = src.clCxt;
-     if(!clCxt->supportsFeature(Context::CL_DOUBLE) && src.type() == CV_64F)
+     if (!clCxt->supportsFeature(Context::CL_DOUBLE) && src.depth() == CV_64F)
      {
-         CV_Error(Error::GpuNotSupported, "Selected device don't support double\r\n");
 -        CV_Error(CV_GpuNotSupported, "Selected device doesn't support double\r\n");
++        CV_Error(Error::GpuNotSupported, "Selected device doesn't support double\r\n");
          return;
      }
-     //int channels = dst.oclchannels();
-     int depth = dst.depth();
+     CV_Assert( src.depth() == CV_32F || src.depth() == CV_64F);
+     dst.create(src.size(), src.type());
+     int ddepth = dst.depth();
+     int cols1 = src.cols * src.oclchannels();
+     int srcoffset1 = src.offset / src.elemSize1(), dstoffset1 = dst.offset / dst.elemSize1();
+     int srcstep1 = src.step1(), dststep1 = dst.step1();
  
      size_t localThreads[3]  = { 64, 4, 1 };
-     size_t globalThreads[3] = { divUp(dst.cols, localThreads[0]) *localThreads[0],
-                                 divUp(dst.rows, localThreads[1]) *localThreads[1],
-                                 1
-                               };
+     size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
+     std::string buildOptions = format("-D srcT=%s",
+                                       ddepth == CV_32F ? "float" : "double");
  
 -    vector<pair<size_t , const void *> > args;
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src.data ));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&cols1 ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src.rows ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&srcoffset1 ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dstoffset1 ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&srcstep1 ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dststep1 ));
 +    std::vector<std::pair<size_t , const void *> > args;
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.rows ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.cols ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.offset ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.rows ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&srcoffset1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dstoffset1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&srcstep1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dststep1 ));
  
-     openCLExecuteKernel(clCxt, kernelString, kernelName, globalThreads, localThreads, args, -1, depth);
+     openCLExecuteKernel(clCxt, kernelString, kernelName, globalThreads, localThreads,
+                         args, src.oclchannels(), -1, buildOptions.c_str());
  }
  void cv::ocl::exp(const oclMat &src, oclMat &dst)
  {
      arithmetic_exp_log_run(src, dst, "arithm_exp", &arithm_exp);
@@@ -1186,11 -870,12 +869,12 @@@ void cv::ocl::log(const oclMat &src, oc
  //////////////////////////////////////////////////////////////////////////////
  ////////////////////////////// magnitude phase ///////////////////////////////
  //////////////////////////////////////////////////////////////////////////////
 -static void arithmetic_magnitude_phase_run(const oclMat &src1, const oclMat &src2, oclMat &dst, string kernelName)
 +static void arithmetic_magnitude_phase_run(const oclMat &src1, const oclMat &src2, oclMat &dst, String kernelName)
  {
-     if(!src1.clCxt->supportsFeature(Context::CL_DOUBLE) && src1.type() == CV_64F)
+     if (!src1.clCxt->supportsFeature(Context::CL_DOUBLE) && src1.type() == CV_64F)
      {
-         CV_Error(Error::GpuNotSupported, "Selected device don't support double\r\n");
 -        CV_Error(CV_GpuNotSupported, "Selected device doesn't support double\r\n");
++        CV_Error(Error::GpuNotSupported, "Selected device doesn't support double\r\n");
          return;
      }
  
      size_t vector_length = 1;
      int offset_cols = ((dst.offset % dst.step) / dst.elemSize1()) & (vector_length - 1);
      int cols = divUp(dst.cols * channels + offset_cols, vector_length);
-     int rows = dst.rows;
  
      size_t localThreads[3]  = { 64, 4, 1 };
-     size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
-                                 divUp(rows, localThreads[1]) *localThreads[1],
-                                 1
-                               };
+     size_t globalThreads[3] = { cols, dst.rows, 1 };
  
 -    vector<pair<size_t , const void *> > args;
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src1.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1.offset ));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src2.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src2.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src2.offset ));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.offset ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.rows ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&cols ));
 +    std::vector<std::pair<size_t , const void *> > args;
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.offset ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.offset ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.rows ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
  
      openCLExecuteKernel(clCxt, &arithm_magnitude, kernelName, globalThreads, localThreads, args, -1, depth);
  }
@@@ -1234,11 -915,11 +914,11 @@@ void cv::ocl::magnitude(const oclMat &s
      arithmetic_magnitude_phase_run(src1, src2, dst, "arithm_magnitude");
  }
  
 -static void arithmetic_phase_run(const oclMat &src1, const oclMat &src2, oclMat &dst, string kernelName, const char **kernelString)
 +static void arithmetic_phase_run(const oclMat &src1, const oclMat &src2, oclMat &dst, String kernelName, const char **kernelString)
  {
-     if(!src1.clCxt->supportsFeature(Context::CL_DOUBLE) && src1.type() == CV_64F)
+     if (!src1.clCxt->supportsFeature(Context::CL_DOUBLE) && src1.type() == CV_64F)
      {
-         CV_Error(Error::GpuNotSupported, "Selected device don't support double\r\n");
 -        CV_Error(CV_GpuNotSupported, "Selected device doesn't support double\r\n");
++        CV_Error(Error::GpuNotSupported, "Selected device doesn't support double\r\n");
          return;
      }
  
      size_t vector_length = 1;
      int offset_cols = ((dst.offset % dst.step) / dst.elemSize1()) & (vector_length - 1);
      int cols = divUp(dst.cols * channels + offset_cols, vector_length);
-     int rows = dst.rows;
  
      size_t localThreads[3]  = { 64, 4, 1 };
-     size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
-                                 divUp(rows, localThreads[1]) *localThreads[1],
-                                 1
-                               };
+     size_t globalThreads[3] = { cols, dst.rows, 1 };
  
      int dst_step1 = dst.cols * dst.elemSize();
 -    vector<pair<size_t , const void *> > args;
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src1.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1.offset ));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src2.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src2.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src2.offset ));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.offset ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.rows ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&cols ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst_step1 ));
 +    std::vector<std::pair<size_t , const void *> > args;
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.offset ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.offset ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.rows ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step1 ));
  
      openCLExecuteKernel(clCxt, kernelString, kernelName, globalThreads, localThreads, args, -1, depth);
  }
@@@ -1281,28 -959,23 +958,23 @@@ void cv::ocl::phase(const oclMat &x, co
  {
      CV_Assert(x.type() == y.type() && x.size() == y.size() && (x.depth() == CV_32F || x.depth() == CV_64F));
      Angle.create(x.size(), x.type());
 -    string kernelName = angleInDegrees ? "arithm_phase_indegrees" : "arithm_phase_inradians";
 +    String kernelName = angleInDegrees ? "arithm_phase_indegrees" : "arithm_phase_inradians";
-     if(angleInDegrees)
-     {
+     if (angleInDegrees)
          arithmetic_phase_run(x, y, Angle, kernelName, &arithm_phase);
-         //std::cout<<"1"<<std::endl;
-     }
      else
-     {
          arithmetic_phase_run(x, y, Angle, kernelName, &arithm_phase);
-         //std::cout<<"2"<<std::endl;
-     }
  }
  
  //////////////////////////////////////////////////////////////////////////////
  ////////////////////////////////// cartToPolar ///////////////////////////////
  //////////////////////////////////////////////////////////////////////////////
  static void arithmetic_cartToPolar_run(const oclMat &src1, const oclMat &src2, oclMat &dst_mag, oclMat &dst_cart,
 -                                string kernelName, bool angleInDegrees)
 +                                String kernelName, bool angleInDegrees)
  {
-     if(!src1.clCxt->supportsFeature(Context::CL_DOUBLE) && src1.type() == CV_64F)
+     if (!src1.clCxt->supportsFeature(Context::CL_DOUBLE) && src1.type() == CV_64F)
      {
-         CV_Error(Error::GpuNotSupported, "Selected device don't support double\r\n");
 -        CV_Error(CV_GpuNotSupported, "Selected device doesn't support double\r\n");
++        CV_Error(Error::GpuNotSupported, "Selected device doesn't support double\r\n");
          return;
      }
  
      int depth = src1.depth();
  
      int cols = src1.cols * channels;
-     int rows = src1.rows;
  
      size_t localThreads[3]  = { 64, 4, 1 };
-     size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
-                                 divUp(rows, localThreads[1]) *localThreads[1],
-                                 1
-                               };
+     size_t globalThreads[3] = { cols, src1.rows, 1 };
  
      int tmp = angleInDegrees ? 1 : 0;
 -    vector<pair<size_t , const void *> > args;
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src1.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1.offset ));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src2.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src2.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src2.offset ));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&dst_mag.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst_mag.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst_mag.offset ));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&dst_cart.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst_cart.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst_cart.offset ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1.rows ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&cols ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&tmp ));
 +    std::vector<std::pair<size_t , const void *> > args;
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.offset ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.offset ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst_mag.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_mag.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_mag.offset ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst_cart.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_cart.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_cart.offset ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&rows ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.rows ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&tmp ));
  
      openCLExecuteKernel(clCxt, &arithm_cartToPolar, kernelName, globalThreads, localThreads, args, -1, depth);
  }
@@@ -1352,12 -1022,13 +1021,13 @@@ void cv::ocl::cartToPolar(const oclMat 
  //////////////////////////////////////////////////////////////////////////////
  ////////////////////////////////// polarToCart ///////////////////////////////
  //////////////////////////////////////////////////////////////////////////////
  static void arithmetic_ptc_run(const oclMat &src1, const oclMat &src2, oclMat &dst1, oclMat &dst2, bool angleInDegrees,
 -                        string kernelName)
 +                        String kernelName)
  {
-     if(!src1.clCxt->supportsFeature(Context::CL_DOUBLE) && src1.type() == CV_64F)
+     if (!src1.clCxt->supportsFeature(Context::CL_DOUBLE) && src1.type() == CV_64F)
      {
-         CV_Error(Error::GpuNotSupported, "Selected device don't support double\r\n");
 -        CV_Error(CV_GpuNotSupported, "Selected device doesn't support double\r\n");
++        CV_Error(Error::GpuNotSupported, "Selected device doesn't support double\r\n");
          return;
      }
  
      int rows = src2.rows;
  
      size_t localThreads[3]  = { 64, 4, 1 };
-     size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
-                                 divUp(rows, localThreads[1]) *localThreads[1],
-                                 1
-                               };
+     size_t globalThreads[3] = { cols, rows, 1 };
  
      int tmp = angleInDegrees ? 1 : 0;
 -    vector<pair<size_t , const void *> > args;
 +    std::vector<std::pair<size_t , const void *> > args;
-     if(src1.data)
+     if (src1.data)
      {
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&src1.data ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&src1.step ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&src1.offset ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.step ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.offset ));
      }
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src2.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src2.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src2.offset ));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&dst1.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst1.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst1.offset ));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&dst2.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst2.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst2.offset ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&rows ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&cols ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&tmp ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.offset ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst1.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst1.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst1.offset ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst2.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst2.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst2.offset ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&rows ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&tmp ));
  
      openCLExecuteKernel(clCxt, &arithm_polarToCart, kernelName, globalThreads, localThreads, args, -1, depth);
  }
@@@ -1417,9 -1085,10 +1084,10 @@@ void cv::ocl::polarToCart(const oclMat 
  //////////////////////////////////////////////////////////////////////////////
  /////////////////////////////////// minMaxLoc ////////////////////////////////
  //////////////////////////////////////////////////////////////////////////////
  static void arithmetic_minMaxLoc_run(const oclMat &src, cl_mem &dst, int vlen , int groupnum)
  {
 -    vector<pair<size_t , const void *> > args;
 +    std::vector<std::pair<size_t , const void *> > args;
      int all_cols = src.step / (vlen * src.elemSize1());
      int pre_cols = (src.offset % src.step) / (vlen * src.elemSize1());
      int sec_cols = all_cols - (src.offset % src.step + src.cols * src.elemSize1() - 1) / (vlen * src.elemSize1()) - 1;
  
  static void arithmetic_minMaxLoc_mask_run(const oclMat &src, const oclMat &mask, cl_mem &dst, int vlen, int groupnum)
  {
 -    vector<pair<size_t , const void *> > args;
 +    std::vector<std::pair<size_t , const void *> > args;
      size_t gt[3] = {groupnum * 256, 1, 1}, lt[3] = {256, 1, 1};
      char build_options[50];
-     if(src.oclchannels() == 1)
+     if (src.oclchannels() == 1)
      {
          int cols = (src.cols - 1) / vlen + 1;
          int invalid_cols = src.step / (vlen * src.elemSize1()) - cols;
          int moffset = mask.offset / mask.elemSize1();
          int elemnum = cols * src.rows;
          sprintf(build_options, "-D DEPTH_%d -D REPEAT_E%d", src.depth(), repeat_me);
 -        args.push_back( make_pair( sizeof(cl_int) , (void *)&cols ));
 -        args.push_back( make_pair( sizeof(cl_int) , (void *)&invalid_cols ));
 -        args.push_back( make_pair( sizeof(cl_int) , (void *)&offset));
 -        args.push_back( make_pair( sizeof(cl_int) , (void *)&elemnum));
 -        args.push_back( make_pair( sizeof(cl_int) , (void *)&groupnum));
 -        args.push_back( make_pair( sizeof(cl_mem) , (void *)&src.data));
 -        args.push_back( make_pair( sizeof(cl_int) , (void *)&minvalid_cols ));
 -        args.push_back( make_pair( sizeof(cl_int) , (void *)&moffset ));
 -        args.push_back( make_pair( sizeof(cl_mem) , (void *)&mask.data ));
 -        args.push_back( make_pair( sizeof(cl_mem) , (void *)&dst ));
 +        args.push_back( std::make_pair( sizeof(cl_int) , (void *)&cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int) , (void *)&invalid_cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int) , (void *)&offset));
 +        args.push_back( std::make_pair( sizeof(cl_int) , (void *)&elemnum));
 +        args.push_back( std::make_pair( sizeof(cl_int) , (void *)&groupnum));
 +        args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src.data));
 +        args.push_back( std::make_pair( sizeof(cl_int) , (void *)&minvalid_cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int) , (void *)&moffset ));
 +        args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&mask.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst ));
-         //    printf("elemnum:%d,cols:%d,invalid_cols:%d,offset:%d,minvalid_cols:%d,moffset:%d,repeat_e:%d\r\n",
-         //           elemnum,cols,invalid_cols,offset,minvalid_cols,moffset,repeat_me);
          openCLExecuteKernel(src.clCxt, &arithm_minMaxLoc_mask, "arithm_op_minMaxLoc_mask", gt, lt, args, -1, -1, build_options);
      }
  }
@@@ -1537,10 -1207,12 +1206,12 @@@ typedef void (*minMaxLocFunc)(const ocl
  void cv::ocl::minMaxLoc(const oclMat &src, double *minVal, double *maxVal,
                          Point *minLoc, Point *maxLoc, const oclMat &mask)
  {
-     if(!src.clCxt->supportsFeature(Context::CL_DOUBLE) && src.depth() == CV_64F)
+     if (!src.clCxt->supportsFeature(Context::CL_DOUBLE) && src.depth() == CV_64F)
      {
-         CV_Error(Error::GpuNotSupported, "select device don't support double");
 -        CV_Error(CV_GpuNotSupported, "Selected device doesn't support double");
++        CV_Error(Error::GpuNotSupported, "Selected device doesn't support double");
+         return;
      }
      static minMaxLocFunc functab[2] =
      {
          arithmetic_minMaxLoc<float>,
  //////////////////////////////////////////////////////////////////////////////
  ///////////////////////////// countNonZero ///////////////////////////////////
  //////////////////////////////////////////////////////////////////////////////
 -static void arithmetic_countNonZero_run(const oclMat &src, cl_mem &dst, int vlen , int groupnum, string kernelName)
 +static void arithmetic_countNonZero_run(const oclMat &src, cl_mem &dst, int vlen , int groupnum, String kernelName)
  {
 -    vector<pair<size_t , const void *> > args;
 +    std::vector<std::pair<size_t , const void *> > args;
      int all_cols = src.step / (vlen * src.elemSize1());
      int pre_cols = (src.offset % src.step) / (vlen * src.elemSize1());
      int sec_cols = all_cols - (src.offset % src.step + src.cols * src.elemSize() - 1) / (vlen * src.elemSize1()) - 1;
  int cv::ocl::countNonZero(const oclMat &src)
  {
      size_t groupnum = src.clCxt->computeUnits();
-     if(!src.clCxt->supportsFeature(Context::CL_DOUBLE) && src.depth() == CV_64F)
+     if (!src.clCxt->supportsFeature(Context::CL_DOUBLE) && src.depth() == CV_64F)
      {
-         CV_Error(Error::GpuNotSupported, "select device don't support double");
 -        CV_Error(CV_GpuNotSupported, "selected device doesn't support double");
++        CV_Error(Error::GpuNotSupported, "selected device doesn't support double");
      }
      CV_Assert(groupnum != 0);
-     groupnum = groupnum * 2;
      int vlen = 8 , dbsize = groupnum * vlen;
-     //cl_ulong start, end;
      Context *clCxt = src.clCxt;
 -    string kernelName = "arithm_op_nonzero";
 +    String kernelName = "arithm_op_nonzero";
-     int *p = new int[dbsize], nonzero = 0;
+     AutoBuffer<int> _buf(dbsize);
+     int *p = (int*)_buf, nonzero = 0;
      cl_mem dstBuffer = openCLCreateBuffer(clCxt, CL_MEM_WRITE_ONLY, dbsize * sizeof(int));
      arithmetic_countNonZero_run(src, dstBuffer, vlen, groupnum, kernelName);
  
  //////////////////////////////////////////////////////////////////////////////
  ////////////////////////////////bitwise_op////////////////////////////////////
  //////////////////////////////////////////////////////////////////////////////
 -static void bitwise_unary_run(const oclMat &src1, oclMat &dst, string kernelName, const char **kernelString)
 +static void bitwise_run(const oclMat &src1, oclMat &dst, String kernelName, const char **kernelString)
  {
      dst.create(src1.size(), src1.type());
  
      int cols = divUp(dst.cols * channels + offset_cols, vector_length);
  
      size_t localThreads[3]  = { 64, 4, 1 };
-     size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
-                                 divUp(dst.rows, localThreads[1]) *localThreads[1],
-                                 1
-                               };
+     size_t globalThreads[3] = { cols, dst.rows, 1 };
  
      int dst_step1 = dst.cols * dst.elemSize();
 -    vector<pair<size_t , const void *> > args;
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src1.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1.offset ));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.offset ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1.rows ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&cols ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst_step1 ));
 +    std::vector<std::pair<size_t , const void *> > args;
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.offset ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.rows ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step1 ));
  
      openCLExecuteKernel(clCxt, kernelString, kernelName, globalThreads, localThreads, args, -1, depth);
  }
  
+ enum { AND = 0, OR, XOR };
  
- template<typename T>
- void bitwise_run(const oclMat &src1, const oclMat &src2, oclMat &dst, String kernelName,
-  const char **kernelString, void *_scalar, const char* _opt = NULL)
+ static void bitwise_binary_run(const oclMat &src1, const oclMat &src2, const Scalar& src3, const oclMat &mask,
+                                oclMat &dst, int operationType)
  {
-     dst.create(src1.size(), src1.type());
-     CV_Assert(src1.cols == src2.cols && src2.cols == dst.cols &&
-               src1.rows == src2.rows && src2.rows == dst.rows);
-     CV_Assert(src1.type() == src2.type() && src1.type() == dst.type());
      Context  *clCxt = src1.clCxt;
-     int channels = dst.oclchannels();
-     int depth = dst.depth();
-     int vector_lengths[4][7] = {{4, 4, 4, 4, 1, 1, 1},
-         {4, 4, 4, 4, 1, 1, 1},
-         {4, 4, 4, 4, 1, 1, 1},
-         {4, 4, 4, 4, 1, 1, 1}
-     };
-     size_t vector_length = vector_lengths[channels - 1][depth];
-     int offset_cols = (dst.offset / dst.elemSize1()) & (vector_length - 1);
-     int cols = divUp(dst.cols * channels + offset_cols, vector_length);
-     size_t localThreads[3]  = { 64, 4, 1 };
-     size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
-                                 divUp(dst.rows, localThreads[1]) *localThreads[1],
-                                 1
-                               };
-     int dst_step1 = dst.cols * dst.elemSize();
-     std::vector<std::pair<size_t , const void *> > args;
-     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.offset ));
-     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.offset ));
-     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.rows ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step1 ));
-     T scalar;
-     if(_scalar != NULL)
+     if (!clCxt->supportsFeature(Context::CL_DOUBLE) && src1.depth() == CV_64F)
      {
-         double scalar1 = *((double *)_scalar);
-         scalar = (T)scalar1;
-         args.push_back( std::make_pair( sizeof(T), (void *)&scalar ));
 -        cout << "Selected device does not support double" << endl;
++        std::cout << "Selected device does not support double" << std::endl;
+         return;
      }
  
-     openCLExecuteKernel(clCxt, kernelString, kernelName, globalThreads, localThreads, args, -1, depth, _opt);
- }
- static void bitwise_run(const oclMat &src1, const oclMat &src2, oclMat &dst,
-  String kernelName, const char **kernelString, const char* _opt = NULL)
- {
-     bitwise_run<char>(src1, src2, dst, kernelName, kernelString, (void *)NULL, _opt);
- }
- static void bitwise_run(const oclMat &src1, const oclMat &src2, oclMat &dst,
-  const oclMat &mask, String kernelName, const char **kernelString, const char* _opt = NULL)
- {
-     dst.create(src1.size(), src1.type());
-     CV_Assert(src1.cols == src2.cols && src2.cols == dst.cols &&
-               src1.rows == src2.rows && src2.rows == dst.rows &&
-               src1.rows == mask.rows && src1.cols == mask.cols);
+     CV_Assert(operationType >= AND && operationType <= XOR);
+     CV_Assert(src2.empty() || (!src2.empty() && src1.type() == src2.type() && src1.size() == src2.size()));
+     CV_Assert(mask.empty() || (!mask.empty() && mask.type() == CV_8UC1 && mask.size() == src1.size()));
  
-     CV_Assert(src1.type() == src2.type() && src1.type() == dst.type());
-     CV_Assert(mask.type() == CV_8U);
-     Context  *clCxt = src1.clCxt;
-     int channels = dst.oclchannels();
-     int depth = dst.depth();
+     dst.create(src1.size(), src1.type());
  
-     int vector_lengths[4][7] = {{4, 4, 2, 2, 1, 1, 1},
-         {2, 2, 1, 1, 1, 1, 1},
-         {4, 4, 2, 2 , 1, 1, 1},
-         {1, 1, 1, 1, 1, 1, 1}
-     };
+     int elemSize = dst.elemSize();
+     int cols1 = dst.cols * elemSize;
+     oclMat m;
  
-     size_t vector_length = vector_lengths[channels - 1][depth];
-     int offset_cols = ((dst.offset % dst.step) / dst.elemSize()) & (vector_length - 1);
-     int cols = divUp(dst.cols + offset_cols, vector_length);
+     const char operationMap[] = { '&', '|', '^' };
+     std::string kernelName("arithm_bitwise_binary");
+     std::string buildOptions = format("-D Operation=%c", operationMap[operationType]);
  
-     size_t localThreads[3]  = { 64, 4, 1 };
-     size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
-                                 divUp(dst.rows, localThreads[1]) *localThreads[1],
-                                 1
-                               };
+     size_t localThreads[3]  = { 16, 16, 1 };
+     size_t globalThreads[3] = { cols1, dst.rows, 1 };
  
-     int dst_step1 = dst.cols * dst.elemSize();
 -    vector<pair<size_t , const void *> > args;
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src1.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1.offset ));
 +    std::vector<std::pair<size_t , const void *> > args;
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.offset ));
-     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.offset ));
-     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mask.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&mask.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&mask.offset ));
-     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.rows ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step1 ));
  
-     openCLExecuteKernel(clCxt, kernelString, kernelName, globalThreads, localThreads, args, channels, depth, _opt);
- }
- template <typename WT , typename CL_WT>
- void bitwise_scalar_run(const oclMat &src1, const Scalar &src2, oclMat &dst,
-  const oclMat &mask, String kernelName, const char **kernelString, int isMatSubScalar, const char* opt = NULL)
- {
-     dst.create(src1.size(), src1.type());
-     CV_Assert(src1.cols == dst.cols && src1.rows == dst.rows &&
-               src1.type() == dst.type());
-     if(mask.data)
+     if (src2.empty())
      {
-         CV_Assert(mask.type() == CV_8U && src1.rows == mask.rows && src1.cols == mask.cols);
-     }
-     Context  *clCxt = src1.clCxt;
-     int channels = dst.oclchannels();
-     int depth = dst.depth();
-     WT s[4] = { saturate_cast<WT>(src2.val[0]), saturate_cast<WT>(src2.val[1]),
-                 saturate_cast<WT>(src2.val[2]), saturate_cast<WT>(src2.val[3])
-               };
-     int vector_lengths[4][7] = {{4, 4, 2, 2, 1, 1, 1},
-         {2, 2, 1, 1, 1, 1, 1},
-         {4, 4, 2, 2 , 1, 1, 1},
-         {1, 1, 1, 1, 1, 1, 1}
-     };
+         m.create(1, 1, dst.type());
+         m.setTo(src3);
  
-     size_t vector_length = vector_lengths[channels - 1][depth];
-     int offset_cols = ((dst.offset % dst.step) / dst.elemSize()) & (vector_length - 1);
-     int cols = divUp(dst.cols + offset_cols, vector_length);
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&m.data ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&elemSize ) );
++        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&m.data ));
++        args.push_back( std::make_pair( sizeof(cl_int), (void *)&elemSize ) );
  
-     size_t localThreads[3]  = { 64, 4, 1 };
-     size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
-                                 divUp(dst.rows, localThreads[1]) *localThreads[1],
-                                 1
-                               };
-     int dst_step1 = dst.cols * dst.elemSize();
-     std::vector<std::pair<size_t , const void *> > args;
-     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src1.data ));
-     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src1.step ));
-     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src1.offset));
-     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst.data ));
-     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst.step ));
-     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst.offset));
-     if(mask.data)
-     {
-         args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&mask.data ));
-         args.push_back( std::make_pair( sizeof(cl_int) , (void *)&mask.step ));
-         args.push_back( std::make_pair( sizeof(cl_int) , (void *)&mask.offset));
+         kernelName += "_scalar";
      }
-     args.push_back( std::make_pair( sizeof(CL_WT) , (void *)&s ));
-     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src1.rows ));
-     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&cols ));
-     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst_step1 ));
-     if(isMatSubScalar != 0)
+     else
      {
-         isMatSubScalar = isMatSubScalar > 0 ? 1 : 0;
-         args.push_back( std::make_pair( sizeof(cl_int) , (void *)&isMatSubScalar));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&src2.data ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&src2.step ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&src2.offset ));
++        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
++        args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.step ));
++        args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.offset ));
      }
  
-     openCLExecuteKernel(clCxt, kernelString, kernelName, globalThreads, localThreads, args, channels, depth, opt);
- }
+     if (!mask.empty())
+     {
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&mask.data ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&mask.step ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&mask.offset ));
++        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mask.data ));
++        args.push_back( std::make_pair( sizeof(cl_int), (void *)&mask.step ));
++        args.push_back( std::make_pair( sizeof(cl_int), (void *)&mask.offset ));
  
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&elemSize ));
+         if (!src2.empty())
++            args.push_back( std::make_pair( sizeof(cl_int), (void *)&elemSize ));
  
- typedef void (*BitwiseFuncS)(const oclMat &src1, const Scalar &src2, oclMat &dst,
-  const oclMat &mask, String kernelName, const char **kernelString, int isMatSubScalar, const char* opt);
+         kernelName += "_mask";
+     }
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.offset ));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
  
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&cols1 ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1.rows ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.rows ));
  
- static void bitwise_scalar(const oclMat &src1, const Scalar &src2, oclMat &dst,
-  const oclMat &mask, String kernelName, const char **kernelString, int isMatSubScalar, const char* opt)
- {
-     static BitwiseFuncS tab[8] =
-     {
- #if 0
-         bitwise_scalar_run<unsigned char>,
-         bitwise_scalar_run<char>,
-         bitwise_scalar_run<unsigned short>,
-         bitwise_scalar_run<short>,
-         bitwise_scalar_run<int>,
-         bitwise_scalar_run<float>,
-         bitwise_scalar_run<double>,
-         0
- #else
-         bitwise_scalar_run<unsigned char, cl_uchar4>,
-         bitwise_scalar_run<char, cl_char4>,
-         bitwise_scalar_run<unsigned short, cl_ushort4>,
-         bitwise_scalar_run<short, cl_short4>,
-         bitwise_scalar_run<int, cl_int4>,
-         bitwise_scalar_run<float, cl_float4>,
-         bitwise_scalar_run<double, cl_double4>,
-         0
- #endif
-     };
-     BitwiseFuncS func = tab[src1.depth()];
-     if(func == 0)
-         cv::error(Error::StsBadArg, "Unsupported arithmetic operation", "", __FILE__, __LINE__);
-     func(src1, src2, dst, mask, kernelName, kernelString, isMatSubScalar, opt);
- }
- static void bitwise_scalar(const oclMat &src1, const Scalar &src2, oclMat &dst,
-  const oclMat &mask, String kernelName, const char **kernelString, const char * opt = NULL)
- {
-     bitwise_scalar(src1, src2, dst, mask, kernelName, kernelString, 0, opt);
+     openCLExecuteKernel(clCxt, mask.empty() ? (!src2.empty() ? &arithm_bitwise_binary : &arithm_bitwise_binary_scalar) :
+                                               (!src2.empty() ? &arithm_bitwise_binary_mask : &arithm_bitwise_binary_scalar_mask),
+                         kernelName, globalThreads, localThreads,
+                         args, -1, -1, buildOptions.c_str());
  }
  
  void cv::ocl::bitwise_not(const oclMat &src, oclMat &dst)
  {
-     if(!src.clCxt->supportsFeature(Context::CL_DOUBLE) && src.type() == CV_64F)
+     if (!src.clCxt->supportsFeature(Context::CL_DOUBLE) && src.type() == CV_64F)
      {
-         std::cout << "Selected device do not support double" << std::endl;
 -        cout << "Selected device does not support double" << endl;
++        std::cout << "Selected device does not support double" << std::endl;
          return;
      }
      dst.create(src.size(), src.type());
 -    string kernelName =  "arithm_bitwise_not";
 -    bitwise_unary_run(src, dst, kernelName, &arithm_bitwise_not);
 +    String kernelName =  "arithm_bitwise_not";
 +    bitwise_run(src, dst, kernelName, &arithm_bitwise_not);
  }
  
  void cv::ocl::bitwise_or(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask)
@@@ -2069,49 -1521,42 +1520,42 @@@ oclMatExpr::operator oclMat() cons
  //////////////////////////////////////////////////////////////////////////////
  /////////////////////////////// transpose ////////////////////////////////////
  //////////////////////////////////////////////////////////////////////////////
  #define TILE_DIM      (32)
  #define BLOCK_ROWS    (256/TILE_DIM)
- static void transpose_run(const oclMat &src, oclMat &dst, String kernelName)
 -static void transpose_run(const oclMat &src, oclMat &dst, string kernelName, bool inplace = false)
++static void transpose_run(const oclMat &src, oclMat &dst, String kernelName, bool inplace = false)
  {
-     if(!src.clCxt->supportsFeature(Context::CL_DOUBLE) && src.type() == CV_64F)
+     Context  *clCxt = src.clCxt;
+     if (!clCxt->supportsFeature(Context::CL_DOUBLE) && src.depth() == CV_64F)
      {
-         CV_Error(Error::GpuNotSupported, "Selected device don't support double\r\n");
 -        CV_Error(CV_GpuNotSupported, "Selected device doesn't support double\r\n");
++        CV_Error(Error::GpuNotSupported, "Selected device doesn't support double\r\n");
          return;
      }
  
-     CV_Assert(src.cols == dst.rows && src.rows == dst.cols);
-     Context  *clCxt = src.clCxt;
-     int channels = src.oclchannels();
-     int depth = src.depth();
-     int vector_lengths[4][7] = {{1, 0, 0, 0, 1, 1, 0},
-         {0, 0, 1, 1, 0, 0, 0},
-         {0, 0, 0, 0 , 0, 0, 0},
-         {1, 1, 0, 0, 0, 0, 0}
-     };
-     size_t vector_length = vector_lengths[channels - 1][depth];
-     int offset_cols = ((dst.offset % dst.step) / dst.elemSize()) & (vector_length - 1);
-     int cols = divUp(src.cols + offset_cols, vector_length);
+     const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
+     const char channelsString[] = { ' ', ' ', '2', '4', '4' };
+     std::string buildOptions = format("-D T=%s%c", typeMap[src.depth()],
+                                       channelsString[src.channels()]);
  
      size_t localThreads[3]  = { TILE_DIM, BLOCK_ROWS, 1 };
-     size_t globalThreads[3] = { divUp(cols, TILE_DIM) *localThreads[0],
-                                 divUp(src.rows, TILE_DIM) *localThreads[1],
-                                 1
-                               };
+     size_t globalThreads[3] = { src.cols, inplace ? src.rows : divUp(src.rows, TILE_DIM) * BLOCK_ROWS, 1 };
+     int srcstep1 = src.step / src.elemSize(), dststep1 = dst.step / dst.elemSize();
+     int srcoffset1 = src.offset / src.elemSize(), dstoffset1 = dst.offset / dst.elemSize();
  
 -    vector<pair<size_t , const void *> > args;
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src.data ));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src.cols ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src.rows ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&srcstep1 ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dststep1 ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&srcoffset1 ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dstoffset1 ));
 +    std::vector<std::pair<size_t , const void *> > args;
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.offset ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.cols ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.rows ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&srcstep1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dststep1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&srcoffset1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dstoffset1 ));
  
-     openCLExecuteKernel(clCxt, &arithm_transpose, kernelName, globalThreads, localThreads, args, channels, depth);
+     openCLExecuteKernel(clCxt, &arithm_transpose, kernelName, globalThreads, localThreads,
+                         args, -1, -1, buildOptions.c_str());
  }
  
  void cv::ocl::transpose(const oclMat &src, oclMat &dst)
@@@ -2140,155 -1593,59 +1592,59 @@@ void cv::ocl::addWeighted(const oclMat 
      int channels = dst.oclchannels();
      int depth = dst.depth();
  
+     int cols1 = src1.cols * channels;
+     int src1step1 = src1.step1(), src1offset1 = src1.offset / src1.elemSize1();
+     int src2step1 = src2.step1(), src2offset1 = src2.offset / src1.elemSize1();
+     int dststep1 = dst.step1(), dstoffset1 = dst.offset / dst.elemSize1();
  
-     int vector_lengths[4][7] = {{4, 0, 4, 4, 4, 4, 4},
-         {4, 0, 4, 4, 4, 4, 4},
-         {4, 0, 4, 4, 4, 4, 4},
-         {4, 0, 4, 4, 4, 4, 4}
-     };
-     size_t vector_length = vector_lengths[channels - 1][depth];
-     int offset_cols = (dst.offset / dst.elemSize1()) & (vector_length - 1);
-     int cols = divUp(dst.cols * channels + offset_cols, vector_length);
+     const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
+     std::string buildOptions = format("-D T=%s -D WT=%s -D convertToT=convert_%s%s",
+                                       typeMap[depth], hasDouble ? "double" : "float", typeMap[depth],
+                                       depth >= CV_32F ? "" : "_sat_rte");
  
      size_t localThreads[3]  = { 256, 1, 1 };
-     size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
-                                 divUp(dst.rows, localThreads[1]) *localThreads[1],
-                                 1
-                               };
+     size_t globalThreads[3] = { cols1, dst.rows, 1};
+     float alpha_f = static_cast<float>(alpha),
+             beta_f = static_cast<float>(beta),
+             gama_f = static_cast<float>(gama);
  
-     int dst_step1 = dst.cols * dst.elemSize();
-     int src1_step = (int) src1.step;
-     int src2_step = (int) src2.step;
-     int dst_step  = (int) dst.step;
-     float alpha_f = alpha, beta_f = beta, gama_f = gama;
 -    vector<pair<size_t , const void *> > args;
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src1.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1step1 ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1offset1));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src2.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src2step1 ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src2offset1));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dststep1 ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dstoffset1));
 +    std::vector<std::pair<size_t , const void *> > args;
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1_step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.offset));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1step1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1offset1));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2_step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.offset));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2step1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2offset1));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dststep1 ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dstoffset1));
  
-     if(src1.clCxt->supportsFeature(Context::CL_DOUBLE))
-     {
-         args.push_back( std::make_pair( sizeof(cl_double), (void *)&alpha ));
-         args.push_back( std::make_pair( sizeof(cl_double), (void *)&beta ));
-         args.push_back( std::make_pair( sizeof(cl_double), (void *)&gama ));
-     }
-     else
+     if (!hasDouble)
      {
 -        args.push_back( make_pair( sizeof(cl_float), (void *)&alpha_f ));
 -        args.push_back( make_pair( sizeof(cl_float), (void *)&beta_f ));
 -        args.push_back( make_pair( sizeof(cl_float), (void *)&gama_f ));
 +        args.push_back( std::make_pair( sizeof(cl_float), (void *)&alpha_f ));
 +        args.push_back( std::make_pair( sizeof(cl_float), (void *)&beta_f ));
 +        args.push_back( std::make_pair( sizeof(cl_float), (void *)&gama_f ));
      }
 -        args.push_back( make_pair( sizeof(cl_double), (void *)&alpha ));
 -        args.push_back( make_pair( sizeof(cl_double), (void *)&beta ));
 -        args.push_back( make_pair( sizeof(cl_double), (void *)&gama ));
+     else
+     {
++        args.push_back( std::make_pair( sizeof(cl_double), (void *)&alpha ));
++        args.push_back( std::make_pair( sizeof(cl_double), (void *)&beta ));
++        args.push_back( std::make_pair( sizeof(cl_double), (void *)&gama ));
+     }
  
-     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.rows ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step1 ));
-     openCLExecuteKernel(clCxt, &arithm_addWeighted, "addWeighted", globalThreads, localThreads, args, -1, depth);
- }
- void cv::ocl::magnitudeSqr(const oclMat &src1, const oclMat &src2, oclMat &dst)
- {
-     CV_Assert(src1.type() == src2.type() && src1.size() == src2.size() &&
-               (src1.depth() == CV_32F ));
-     dst.create(src1.size(), src1.type());
-     Context *clCxt = src1.clCxt;
-     int channels = dst.oclchannels();
-     int depth = dst.depth();
-     int vector_lengths[4][7] = {{4, 0, 4, 4, 4, 4, 4},
-         {4, 0, 4, 4, 4, 4, 4},
-         {4, 0, 4, 4, 4, 4, 4},
-         {4, 0, 4, 4, 4, 4, 4}
-     };
-     size_t vector_length = vector_lengths[channels - 1][depth];
-     int offset_cols = (dst.offset / dst.elemSize1()) & (vector_length - 1);
-     int cols = divUp(dst.cols * channels + offset_cols, vector_length);
-     size_t localThreads[3]  = { 256, 1, 1 };
-     size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
-                                 divUp(dst.rows, localThreads[1]) *localThreads[1],
-                                 1
-                               };
-     int dst_step1 = dst.cols * dst.elemSize();
-     std::vector<std::pair<size_t , const void *> > args;
-     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.offset));
-     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src2.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src2.offset));
-     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&cols1 ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1.rows ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols1 ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.rows ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step1 ));
  
-     openCLExecuteKernel(clCxt, &arithm_magnitudeSqr, "magnitudeSqr", globalThreads, localThreads, args, 1, depth);
+     openCLExecuteKernel(clCxt, &arithm_addWeighted, "addWeighted", globalThreads, localThreads,
+                         args, -1, -1, buildOptions.c_str());
  }
  
- void cv::ocl::magnitudeSqr(const oclMat &src1, oclMat &dst)
- {
-     CV_Assert (src1.depth() == CV_32F );
-     CV_Assert(src1.size() == dst.size());
-     dst.create(src1.size(), CV_32FC1);
-     Context *clCxt = src1.clCxt;
-     int channels = dst.oclchannels();
-     int depth = dst.depth();
-     int vector_lengths[4][7] = {{4, 0, 4, 4, 4, 4, 4},
-         {4, 0, 4, 4, 4, 4, 4},
-         {4, 0, 4, 4, 4, 4, 4},
-         {4, 0, 4, 4, 4, 4, 4}
-     };
-     size_t vector_length = vector_lengths[channels - 1][depth];
-     int offset_cols = (dst.offset / dst.elemSize1()) & (vector_length - 1);
-     int cols = divUp(dst.cols * channels + offset_cols, vector_length);
-     size_t localThreads[3]  = { 256, 1, 1 };
-     size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
-                                 divUp(dst.rows, localThreads[1]) *localThreads[1],
-                                 1
-                               };
-     int dst_step1 = dst.cols * dst.elemSize();
-     std::vector<std::pair<size_t , const void *> > args;
-     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.offset));
-     args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.rows ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
-     args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step1 ));
-     openCLExecuteKernel(clCxt, &arithm_magnitudeSqr, "magnitudeSqr", globalThreads, localThreads, args, 2, depth);
- }
+ //////////////////////////////////////////////////////////////////////////////
+ /////////////////////////////////// Pow //////////////////////////////////////
+ //////////////////////////////////////////////////////////////////////////////
  
 -static void arithmetic_pow_run(const oclMat &src1, double p, oclMat &dst, string kernelName, const char **kernelString)
 +static void arithmetic_pow_run(const oclMat &src1, double p, oclMat &dst, String kernelName, const char **kernelString)
  {
      CV_Assert(src1.cols == dst.cols && src1.rows == dst.rows);
      CV_Assert(src1.type() == dst.type());
      int rows = dst.rows;
  
      size_t localThreads[3]  = { 64, 4, 1 };
-     size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
-                                 divUp(rows, localThreads[1]) *localThreads[1],
-                                 1
-                               };
+     size_t globalThreads[3] = { cols, rows, 1 };
  
      int dst_step1 = dst.cols * dst.elemSize();
 -    vector<pair<size_t , const void *> > args;
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src1.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src1.offset ));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.offset ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.rows ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&cols ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst_step1 ));
 +    std::vector<std::pair<size_t , const void *> > args;
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src1.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src1.offset ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.rows ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst_step1 ));
-     float pf = p;
-     if(!src1.clCxt->supportsFeature(Context::CL_DOUBLE))
-     {
+     float pf = static_cast<float>(p);
+     if (!src1.clCxt->supportsFeature(Context::CL_DOUBLE))
 -        args.push_back( make_pair( sizeof(cl_float), (void *)&pf ));
 +        args.push_back( std::make_pair( sizeof(cl_float), (void *)&pf ));
-     }
      else
 -        args.push_back( make_pair( sizeof(cl_double), (void *)&p ));
 +        args.push_back( std::make_pair( sizeof(cl_double), (void *)&p ));
  
      openCLExecuteKernel(clCxt, kernelString, kernelName, globalThreads, localThreads, args, -1, depth);
  }
  void cv::ocl::pow(const oclMat &x, double p, oclMat &y)
  {
-     if(!x.clCxt->supportsFeature(Context::CL_DOUBLE) && x.type() == CV_64F)
+     if (!x.clCxt->supportsFeature(Context::CL_DOUBLE) && x.type() == CV_64F)
      {
 -        cout << "Selected device do not support double" << endl;
 +        std::cout << "Selected device do not support double" << std::endl;
          return;
      }
  
  
      arithmetic_pow_run(x, p, y, kernelName, &arithm_pow);
  }
 -    string kernelName = "setIdentityKernel";
+ //////////////////////////////////////////////////////////////////////////////
+ /////////////////////////////// setIdentity //////////////////////////////////
+ //////////////////////////////////////////////////////////////////////////////
+ void cv::ocl::setIdentity(oclMat& src, double scalar)
+ {
+     CV_Assert(src.empty() == false && src.rows == src.cols);
+     CV_Assert(src.type() == CV_32SC1 || src.type() == CV_32FC1);
+     int src_step = src.step/src.elemSize();
+     Context  *clCxt = Context::getContext();
+     size_t local_threads[] = {16, 16, 1};
+     size_t global_threads[] = {src.cols, src.rows, 1};
 -        kernelName += "_F1";
++    String kernelName = "setIdentityKernel";
+     if (src.type() == CV_32FC1)
 -        kernelName += "_I1";
++        kernelName = kernelName + "_F1";
+     else if (src.type() == CV_32SC1)
 -        kernelName += "_D1";
++        kernelName = kernelName + "_I1";
+     else
+     {
 -    vector<pair<size_t , const void *> > args;
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src.rows));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src.cols));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src_step ));
++        kernelName = kernelName + "_D1";
+         if (!(clCxt->supportsFeature(Context::CL_DOUBLE)))
+         {
+             oclMat temp;
+             src.convertTo(temp, CV_32FC1);
+             temp.copyTo(src);
+         }
+     }
 -            args.push_back(make_pair(sizeof(cl_int), (void*)&scalar_i));
++    std::vector<std::pair<size_t , const void *> > args;
++    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.rows));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.cols));
++    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src_step ));
+     int scalar_i = 0;
+     float scalar_f = 0.0f;
+     if (clCxt->supportsFeature(Context::CL_DOUBLE))
+     {
+         if (src.type() == CV_32SC1)
+         {
+             scalar_i = (int)scalar;
 -            args.push_back(make_pair(sizeof(cl_double), (void*)&scalar));
++            args.push_back(std::make_pair(sizeof(cl_int), (void*)&scalar_i));
+         }
+         else
 -            args.push_back(make_pair(sizeof(cl_int), (void*)&scalar_i));
++            args.push_back(std::make_pair(sizeof(cl_double), (void*)&scalar));
+     }
+     else
+     {
+         if (src.type() == CV_32SC1)
+         {
+             scalar_i = (int)scalar;
 -            args.push_back(make_pair(sizeof(cl_float), (void*)&scalar_f));
++            args.push_back(std::make_pair(sizeof(cl_int), (void*)&scalar_i));
+         }
+         else
+         {
+             scalar_f = (float)scalar;
++            args.push_back(std::make_pair(sizeof(cl_float), (void*)&scalar_f));
+         }
+     }
+     openCLExecuteKernel(clCxt, &arithm_setidentity, kernelName, global_threads, local_threads, args, -1, -1);
+ }
@@@ -353,27 -356,26 +353,26 @@@ void canny::edgesHysteresisGlobal_gpu(o
      unsigned int count;
      openCLSafeCall(clEnqueueReadBuffer(*(cl_command_queue*)getoclCommandQueue(), (cl_mem)counter, 1, 0, sizeof(float), &count, 0, NULL, NULL));
      Context *clCxt = map.clCxt;
 -    string kernelName = "edgesHysteresisGlobal";
 -    vector< pair<size_t, const void *> > args;
 +    String kernelName = "edgesHysteresisGlobal";
 +    std::vector< std::pair<size_t, const void *> > args;
      size_t localThreads[3]  = {128, 1, 1};
  
- #define DIVUP(a, b) ((a)+(b)-1)/(b)
      int count_i[1] = {0};
      while(count > 0)
      {
          openCLSafeCall(clEnqueueWriteBuffer(*(cl_command_queue*)getoclCommandQueue(), (cl_mem)counter, 1, 0, sizeof(int), &count_i, 0, NULL, NULL));
  
          args.clear();
-         size_t globalThreads[3] = {std::min(count, 65535u) * 128, DIVUP(count, 65535), 1};
+         size_t globalThreads[3] = {std::min(count, 65535u) * 128, divUp(count, 65535), 1};
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&map.data));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&st1.data));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&st2.data));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&counter));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&rows));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&cols));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&count));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&map.step));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&map.offset));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&map.data));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&st1.data));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&st2.data));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&counter));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&rows));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&count));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&map.step));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&map.offset));
  
          openCLExecuteKernel(clCxt, &imgproc_canny, kernelName, globalThreads, localThreads, args, -1, -1);
          openCLSafeCall(clEnqueueReadBuffer(*(cl_command_queue*)getoclCommandQueue(), (cl_mem)counter, 1, 0, sizeof(int), &count, 0, NULL, NULL));
@@@ -1349,21 -1306,17 +1306,17 @@@ void linearColumnFilter_gpu(const oclMa
      dst_pix_per_row = dst.step / dst.elemSize();
      dst_offset_in_pixel = dst.offset / dst.elemSize();
  
 -    vector<pair<size_t , const void *> > args;
 -    args.push_back(make_pair(sizeof(cl_mem), &src.data));
 -    args.push_back(make_pair(sizeof(cl_mem), &dst.data));
 -    args.push_back(make_pair(sizeof(cl_int), (void *)&dst.cols));
 -    args.push_back(make_pair(sizeof(cl_int), (void *)&dst.rows));
 -    args.push_back(make_pair(sizeof(cl_int), (void *)&src.wholecols));
 -    args.push_back(make_pair(sizeof(cl_int), (void *)&src.wholerows));
 -    args.push_back(make_pair(sizeof(cl_int), (void *)&src_pix_per_row));
 -    args.push_back(make_pair(sizeof(cl_int), (void *)&dst_pix_per_row));
 -    args.push_back(make_pair(sizeof(cl_int), (void *)&dst_offset_in_pixel));
 -    args.push_back(make_pair(sizeof(cl_mem), (void *)&mat_kernel.data));
 +    std::vector<std::pair<size_t , const void *> > args;
 +    args.push_back(std::make_pair(sizeof(cl_mem), &src.data));
 +    args.push_back(std::make_pair(sizeof(cl_mem), &dst.data));
 +    args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.cols));
 +    args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst.rows));
 +    args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.wholecols));
 +    args.push_back(std::make_pair(sizeof(cl_int), (void *)&src.wholerows));
 +    args.push_back(std::make_pair(sizeof(cl_int), (void *)&src_pix_per_row));
-     //args.push_back(std::make_pair(sizeof(cl_int),(void*)&src_offset_x));
-     //args.push_back(std::make_pair(sizeof(cl_int),(void*)&src_offset_y));
 +    args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst_pix_per_row));
 +    args.push_back(std::make_pair(sizeof(cl_int), (void *)&dst_offset_in_pixel));
 +    args.push_back(std::make_pair(sizeof(cl_mem), (void *)&mat_kernel.data));
  
      openCLExecuteKernel(clCxt, &filter_sep_col, kernelName, globalThreads, localThreads, args, -1, -1, compile_option);
  }
@@@ -1393,13 -1337,10 +1337,10 @@@ Ptr<BaseColumnFilter_GPU> cv::ocl::getL
      oclMat mat_kernel(temp);
  
      int ksize = temp.cols;
-     //CV_Assert(ksize < 16);
      normalizeAnchor(anchor, ksize);
  
 -    return Ptr<BaseColumnFilter_GPU>(new GpuLinearColumnFilter(ksize, anchor, mat_kernel,
 -                                     gpuFilter1D_callers[CV_MAT_DEPTH(dstType)], bordertype));
 +    return makePtr<GpuLinearColumnFilter>(ksize, anchor, mat_kernel,
 +        gpuFilter1D_callers[CV_MAT_DEPTH(dstType)], bordertype);
  }
  
  Ptr<FilterEngine_GPU> cv::ocl::createSeparableLinearFilter_GPU(int srcType, int dstType,
@@@ -1669,9 -1664,10 +1664,10 @@@ void cv::ocl::device::hog::compute_hist
  
      if(hog_device_cpu)
      {
 -        openCLExecuteKernel(clCxt, &objdetect_hog, kernelName, globalThreads,
 +        openCLExecuteKernel2(clCxt, &objdetect_hog, kernelName, globalThreads,
              localThreads, args, -1, -1, "-D CPU");
-     }else
+     }
+     else
      {
          cl_kernel kernel = openCLGetKernelFromSource(clCxt, &objdetect_hog, kernelName);
          int wave_size = queryDeviceInfo<WAVEFRONT_SIZE, int>(kernel);
@@@ -501,14 -496,7 +498,7 @@@ namespace c
                  openCLExecuteKernel(clCxt, &imgproc_median, kernelName, globalThreads, localThreads, args, src.oclchannels(), src.depth());
              }
              else
-             {
 -                CV_Error(CV_StsUnsupportedFormat, "Non-supported filter length");
 +                CV_Error(Error::StsUnsupportedFormat, "Non-supported filter length");
-                 //String kernelName = "medianFilter";
-                 //args.push_back( std::make_pair( sizeof(cl_int),(void*)&m));
-                 //openCLExecuteKernel(clCxt,&imgproc_median,kernelName,globalThreads,localThreads,args,src.oclchannels(),-1);
-             }
          }
  
          ////////////////////////////////////////////////////////////////////////
  
      }
  }
 +//////////////////////////////////mulSpectrums////////////////////////////////////////////////////
 +void cv::ocl::mulSpectrums(const oclMat &a, const oclMat &b, oclMat &c, int /*flags*/, float scale, bool conjB)
 +{
 +    CV_Assert(a.type() == CV_32FC2);
 +    CV_Assert(b.type() == CV_32FC2);
 +
 +    c.create(a.size(), CV_32FC2);
 +
 +    size_t lt[3]  = { 16, 16, 1 };
 +    size_t gt[3]  = { a.cols, a.rows, 1 };
 +
 +    String kernelName = conjB ? "mulAndScaleSpectrumsKernel_CONJ":"mulAndScaleSpectrumsKernel";
 +
 +    std::vector<std::pair<size_t , const void *> > args;
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&a.data ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&b.data ));
 +    args.push_back( std::make_pair( sizeof(cl_float), (void *)&scale));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&c.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&a.cols ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&a.rows));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&a.step ));
 +
 +    Context *clCxt = Context::getContext();
 +    openCLExecuteKernel(clCxt, &imgproc_mulAndScaleSpectrums, kernelName, gt, lt, args, -1, -1);
 +}
  //////////////////////////////////convolve////////////////////////////////////////////////////
- inline int divUp(int total, int grain)
- {
-     return (total + grain - 1) / grain;
- }
 +// ported from CUDA module
 +void cv::ocl::ConvolveBuf::create(Size image_size, Size templ_size)
 +{
 +    result_size = Size(image_size.width - templ_size.width + 1,
 +                       image_size.height - templ_size.height + 1);
 +
 +    block_size = user_block_size;
 +    if (user_block_size.width == 0 || user_block_size.height == 0)
 +        block_size = estimateBlockSize(result_size, templ_size);
 +
 +    dft_size.width  = 1 << int(ceil(std::log(block_size.width + templ_size.width - 1.) / std::log(2.)));
 +    dft_size.height = 1 << int(ceil(std::log(block_size.height + templ_size.height - 1.) / std::log(2.)));
 +
 +    // CUFFT has hard-coded kernels for power-of-2 sizes (up to 8192),
 +    // see CUDA Toolkit 4.1 CUFFT Library Programming Guide
 +    //if (dft_size.width > 8192)
 +    dft_size.width = getOptimalDFTSize(block_size.width + templ_size.width - 1.);
 +    //if (dft_size.height > 8192)
 +    dft_size.height = getOptimalDFTSize(block_size.height + templ_size.height - 1.);
 +
 +    // To avoid wasting time doing small DFTs
 +    dft_size.width = std::max(dft_size.width, 512);
 +    dft_size.height = std::max(dft_size.height, 512);
 +
 +    image_block.create(dft_size, CV_32F);
 +    templ_block.create(dft_size, CV_32F);
 +    result_data.create(dft_size, CV_32F);
 +
 +    //spect_len = dft_size.height * (dft_size.width / 2 + 1);
 +    image_spect.create(dft_size.height, dft_size.width / 2 + 1, CV_32FC2);
 +    templ_spect.create(dft_size.height, dft_size.width / 2 + 1, CV_32FC2);
 +    result_spect.create(dft_size.height, dft_size.width / 2 + 1, CV_32FC2);
 +
 +    // Use maximum result matrix block size for the estimated DFT block size
 +    block_size.width = std::min(dft_size.width - templ_size.width + 1, result_size.width);
 +    block_size.height = std::min(dft_size.height - templ_size.height + 1, result_size.height);
 +}
 +
 +Size cv::ocl::ConvolveBuf::estimateBlockSize(Size result_size, Size /*templ_size*/)
 +{
 +    int width = (result_size.width + 2) / 3;
 +    int height = (result_size.height + 2) / 3;
 +    width = std::min(width, result_size.width);
 +    height = std::min(height, result_size.height);
 +    return Size(width, height);
 +}
 +
 +static void convolve_run_fft(const oclMat &image, const oclMat &templ, oclMat &result, bool ccorr, ConvolveBuf& buf)
 +{
 +#if defined HAVE_CLAMDFFT
 +    CV_Assert(image.type() == CV_32F);
 +    CV_Assert(templ.type() == CV_32F);
 +
 +    buf.create(image.size(), templ.size());
 +    result.create(buf.result_size, CV_32F);
 +
 +    Size& block_size = buf.block_size;
 +    Size& dft_size = buf.dft_size;
 +
 +    oclMat& image_block = buf.image_block;
 +    oclMat& templ_block = buf.templ_block;
 +    oclMat& result_data = buf.result_data;
 +
 +    oclMat& image_spect = buf.image_spect;
 +    oclMat& templ_spect = buf.templ_spect;
 +    oclMat& result_spect = buf.result_spect;
 +
 +    oclMat templ_roi = templ;
 +    copyMakeBorder(templ_roi, templ_block, 0, templ_block.rows - templ_roi.rows, 0,
 +                   templ_block.cols - templ_roi.cols, 0, Scalar());
 +
 +    cv::ocl::dft(templ_block, templ_spect, dft_size);
  
 -static void convolve_run(const oclMat &src, const oclMat &temp1, oclMat &dst, string kernelName, const char **kernelString)
 +    // Process all blocks of the result matrix
 +    for (int y = 0; y < result.rows; y += block_size.height)
 +    {
 +        for (int x = 0; x < result.cols; x += block_size.width)
 +        {
 +            Size image_roi_size(std::min(x + dft_size.width, image.cols) - x,
 +                                std::min(y + dft_size.height, image.rows) - y);
 +            Rect roi0(x, y, image_roi_size.width, image_roi_size.height);
 +
 +            oclMat image_roi(image, roi0);
 +
 +            copyMakeBorder(image_roi, image_block, 0, image_block.rows - image_roi.rows,
 +                           0, image_block.cols - image_roi.cols, 0, Scalar());
 +
 +            cv::ocl::dft(image_block, image_spect, dft_size);
 +
 +            mulSpectrums(image_spect, templ_spect, result_spect, 0,
 +                                 1.f / dft_size.area(), ccorr);
 +
 +            cv::ocl::dft(result_spect, result_data, dft_size, cv::DFT_INVERSE | cv::DFT_REAL_OUTPUT);
 +
 +            Size result_roi_size(std::min(x + block_size.width, result.cols) - x,
 +                                 std::min(y + block_size.height, result.rows) - y);
 +
 +            Rect roi1(x, y, result_roi_size.width, result_roi_size.height);
 +            Rect roi2(0, 0, result_roi_size.width, result_roi_size.height);
 +
 +            oclMat result_roi(result, roi1);
 +            oclMat result_block(result_data, roi2);
 +
 +            result_block.copyTo(result_roi);
 +        }
 +    }
 +
 +#else
 +    CV_Error(Error::StsNotImplemented, "OpenCL DFT is not implemented");
 +#define UNUSED(x) (void)(x);
 +    UNUSED(image) UNUSED(templ) UNUSED(result) UNUSED(ccorr) UNUSED(buf)
 +#undef UNUSED
 +#endif
 +}
++
 +static void convolve_run(const oclMat &src, const oclMat &temp1, oclMat &dst, String kernelName, const char **kernelString)
  {
      CV_Assert(src.depth() == CV_32FC1);
      CV_Assert(temp1.depth() == CV_32F);
      int rows = dst.rows;
  
      size_t localThreads[3]  = { 16, 16, 1 };
-     size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
-                                 divUp(rows, localThreads[1]) *localThreads[1],
-                                 1
-                               };
+     size_t globalThreads[3] = { cols, rows, 1 };
  
 -    vector<pair<size_t , const void *> > args;
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src.data ));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&temp1.data ));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src.rows ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&cols ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&temp1.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&temp1.rows ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&temp1.cols ));
 +    std::vector<std::pair<size_t , const void *> > args;
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&temp1.data ));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.rows ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&temp1.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&temp1.rows ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&temp1.cols ));
  
      openCLExecuteKernel(clCxt, kernelString, kernelName, globalThreads, localThreads, args, -1, depth);
  }
@@@ -1036,11 -1033,14 +1036,19 @@@ namespace c
              return impl->maxComputeUnits;
          }
  
 +        size_t Context::maxWorkGroupSize()
 +        {
 +            return impl->maxWorkGroupSize;
 +        }
 +
+         unsigned long queryLocalMemInfo()
+         {
+             Info::Impl* impl = Context::getContext()->impl;
+             cl_ulong local_memory_size = 0;
+             clGetDeviceInfo(impl->devices[impl->devnum], CL_DEVICE_LOCAL_MEM_SIZE, sizeof(cl_ulong), (void*)&local_memory_size, 0);
+             return local_memory_size;
+         }
          void* Context::oclContext()
          {
              return impl->oclcontext;
index 0000000,fd9f2fe..a7a1222
mode 000000,100644..100644
--- /dev/null
@@@ -1,0 -1,157 +1,157 @@@
 -    args.push_back(make_pair(sizeof(cl_mem), (void*)&samples.data));
 -    args.push_back(make_pair(sizeof(cl_int), (void*)&samples.rows));
 -    args.push_back(make_pair(sizeof(cl_int), (void*)&samples.cols));
 -    args.push_back(make_pair(sizeof(cl_int), (void*)&samples_step));
 -    args.push_back(make_pair(sizeof(cl_int), (void*)&k));
 -    args.push_back(make_pair(sizeof(cl_mem), (void*)&samples_ocl.data));
 -    args.push_back(make_pair(sizeof(cl_int), (void*)&samples_ocl.rows));
 -    args.push_back(make_pair(sizeof(cl_int), (void*)&samples_ocl_step));
 -    args.push_back(make_pair(sizeof(cl_mem), (void*)&lables.data));
 -    args.push_back(make_pair(sizeof(cl_int), (void*)&lables_step));
 -    args.push_back(make_pair(sizeof(cl_int), (void*)&_regression));
 -    args.push_back(make_pair(sizeof(cl_int), (void*)&k1));
 -    args.push_back(make_pair(sizeof(cl_int), (void*)&samples_ocl.cols));
 -    args.push_back(make_pair(sizeof(cl_int), (void*)&nThreads));
 -    args.push_back(make_pair(smem_size, (void*)NULL));
+ /*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, 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.
+ //
+ // @Authors
+ //    Jin Ma, jin@multicorewareinc.com
+ //
+ // 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*/
+ #include "precomp.hpp"
+ using namespace cv;
+ using namespace cv::ocl;
+ namespace cv
+ {
+     namespace ocl
+     {
+         extern const char* knearest;//knearest
+     }
+ }
+ KNearestNeighbour::KNearestNeighbour()
+ {
+     clear();
+ }
+ KNearestNeighbour::~KNearestNeighbour()
+ {
+     clear();
+     samples_ocl.release();
+ }
+ void KNearestNeighbour::clear()
+ {
+     CvKNearest::clear();
+ }
+ bool KNearestNeighbour::train(const Mat& trainData, Mat& labels, Mat& sampleIdx,
+                               bool isRegression, int _max_k, bool updateBase)
+ {
+     max_k = _max_k;
+     bool cv_knn_train = CvKNearest::train(trainData, labels, sampleIdx, isRegression, max_k, updateBase);
+     CvVectors* s = CvKNearest::samples;
+     cv::Mat samples_mat(s->count, CvKNearest::var_count + 1, s->type);
+     float* s1 = (float*)(s + 1);
+     for(int i = 0; i < s->count; i++)
+     {
+         float* t1 = s->data.fl[i];
+         for(int j = 0; j < CvKNearest::var_count; j++)
+         {
+             Point pos(j, i);
+             samples_mat.at<float>(pos) = t1[j];
+         }
+         Point pos_label(CvKNearest::var_count, i);
+         samples_mat.at<float>(pos_label) = s1[i];
+     }
+     samples_ocl = samples_mat;
+     return cv_knn_train;
+ }
+ void KNearestNeighbour::find_nearest(const oclMat& samples, int k, oclMat& lables)
+ {
+     CV_Assert(!samples_ocl.empty());
+     lables.create(samples.rows, 1, CV_32FC1);
+     CV_Assert(samples.cols == CvKNearest::var_count);
+     CV_Assert(samples.type() == CV_32FC1);
+     CV_Assert(k >= 1 && k <= max_k);
+     int k1 = KNearest::get_sample_count();
+     k1 = MIN( k1, k );
+     String kernel_name = "knn_find_nearest";
+     cl_ulong local_memory_size = queryLocalMemInfo();
+     int nThreads = local_memory_size / (2 * k * 4);
+     if(nThreads >= 256)
+         nThreads = 256;
+     int smem_size = nThreads * k * 4 * 2;
+     size_t local_thread[] = {1, nThreads, 1};
+     size_t global_thread[] = {1, samples.rows, 1};
+     char build_option[50];
+     if(!Context::getContext()->supportsFeature(Context::CL_DOUBLE))
+     {
+         sprintf(build_option, " ");
+     }else
+         sprintf(build_option, "-D DOUBLE_SUPPORT");
+     std::vector< std::pair<size_t, const void*> > args;
+     int samples_ocl_step = samples_ocl.step/samples_ocl.elemSize();
+     int samples_step = samples.step/samples.elemSize();
+     int lables_step = lables.step/lables.elemSize();
+     int _regression = 0;
+     if(CvKNearest::regression)
+         _regression = 1;
++    args.push_back(std::make_pair(sizeof(cl_mem), (void*)&samples.data));
++    args.push_back(std::make_pair(sizeof(cl_int), (void*)&samples.rows));
++    args.push_back(std::make_pair(sizeof(cl_int), (void*)&samples.cols));
++    args.push_back(std::make_pair(sizeof(cl_int), (void*)&samples_step));
++    args.push_back(std::make_pair(sizeof(cl_int), (void*)&k));
++    args.push_back(std::make_pair(sizeof(cl_mem), (void*)&samples_ocl.data));
++    args.push_back(std::make_pair(sizeof(cl_int), (void*)&samples_ocl.rows));
++    args.push_back(std::make_pair(sizeof(cl_int), (void*)&samples_ocl_step));
++    args.push_back(std::make_pair(sizeof(cl_mem), (void*)&lables.data));
++    args.push_back(std::make_pair(sizeof(cl_int), (void*)&lables_step));
++    args.push_back(std::make_pair(sizeof(cl_int), (void*)&_regression));
++    args.push_back(std::make_pair(sizeof(cl_int), (void*)&k1));
++    args.push_back(std::make_pair(sizeof(cl_int), (void*)&samples_ocl.cols));
++    args.push_back(std::make_pair(sizeof(cl_int), (void*)&nThreads));
++    args.push_back(std::make_pair(smem_size, (void*)NULL));
+     openCLExecuteKernel(Context::getContext(), &knearest, kernel_name, global_thread, local_thread, args, -1, -1, build_option);
+ }
@@@ -370,36 -368,41 +356,41 @@@ void cv::ocl::oclMat::copyTo( oclMat &m
  ///////////////////////////////////////////////////////////////////////////
  static void convert_run(const oclMat &src, oclMat &dst, double alpha, double beta)
  {
-     String kernelName = "convert_to_S";
-     std::stringstream idxStr;
-     idxStr << src.depth();
-     kernelName = kernelName + idxStr.str().c_str();
 -    string kernelName = "convert_to";
++    String kernelName = "convert_to";
      float alpha_f = alpha, beta_f = beta;
+     int sdepth = src.depth(), ddepth = dst.depth();
+     int sstep1 = (int)src.step1(), dstep1 = (int)dst.step1();
+     int cols1 = src.cols * src.oclchannels();
+     char buildOptions[150], convertString[50];
+     const char * typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
+     sprintf(convertString, "convert_%s_sat_rte", typeMap[ddepth]);
+     sprintf(buildOptions, "-D srcT=%s -D dstT=%s -D convertToDstType=%s", typeMap[sdepth],
+             typeMap[ddepth], CV_32F == ddepth || ddepth == CV_64F ? "" : convertString);
      CV_DbgAssert(src.rows == dst.rows && src.cols == dst.cols);
 -    vector<pair<size_t , const void *> > args;
 +    std::vector<std::pair<size_t , const void *> > args;
-     size_t localThreads[3] = {16, 16, 1};
-     size_t globalThreads[3];
-     globalThreads[0] = (dst.cols + localThreads[0] - 1) / localThreads[0] * localThreads[0];
-     globalThreads[1] = (dst.rows + localThreads[1] - 1) / localThreads[1] * localThreads[1];
-     globalThreads[2] = 1;
-     int dststep_in_pixel = dst.step / dst.elemSize(), dstoffset_in_pixel = dst.offset / dst.elemSize();
-     int srcstep_in_pixel = src.step / src.elemSize(), srcoffset_in_pixel = src.offset / src.elemSize();
-     if(dst.type() == CV_8UC1)
-     {
-         globalThreads[0] = ((dst.cols + 4) / 4 + localThreads[0]) / localThreads[0] * localThreads[0];
-     }
+     size_t localThreads[3] = { 16, 16, 1 };
+     size_t globalThreads[3] = { divUp(cols1, localThreads[0]) * localThreads[0],
+                                 divUp(dst.rows, localThreads[1]) * localThreads[1], 1 };
+     int doffset1 = dst.offset / dst.elemSize1();
+     int soffset1 = src.offset / src.elemSize1();
 -    args.push_back( make_pair( sizeof(cl_mem) , (void *)&src.data ));
 -    args.push_back( make_pair( sizeof(cl_mem) , (void *)&dst.data ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&cols1 ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&src.rows ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&sstep1 ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&soffset1 ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&dstep1 ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&doffset1 ));
 -    args.push_back( make_pair( sizeof(cl_float) , (void *)&alpha_f ));
 -    args.push_back( make_pair( sizeof(cl_float) , (void *)&beta_f ));
 +    args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src.data ));
 +    args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst.data ));
-     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.cols ));
++    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&cols1 ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.rows ));
-     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&srcstep_in_pixel ));
-     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&srcoffset_in_pixel ));
-     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dststep_in_pixel ));
-     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dstoffset_in_pixel ));
++    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&sstep1 ));
++    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&soffset1 ));
++    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dstep1 ));
++    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&doffset1 ));
 +    args.push_back( std::make_pair( sizeof(cl_float) , (void *)&alpha_f ));
 +    args.push_back( std::make_pair( sizeof(cl_float) , (void *)&beta_f ));
      openCLExecuteKernel(dst.clCxt , &operator_convertTo, kernelName, globalThreads,
-                         localThreads, args, dst.oclchannels(), dst.depth());
+                         localThreads, args, -1, -1, buildOptions);
  }
  void cv::ocl::oclMat::convertTo( oclMat &dst, int rtype, double alpha, double beta ) const
  {
@@@ -438,368 -446,83 +434,83 @@@ oclMat &cv::ocl::oclMat::operator = (co
      setTo(s);
      return *this;
  }
 -static void set_to_withoutmask_run(const oclMat &dst, const Scalar &scalar, string kernelName)
 +static void set_to_withoutmask_run(const oclMat &dst, const Scalar &scalar, String kernelName)
  {
 -    vector<pair<size_t , const void *> > args;
 +    std::vector<std::pair<size_t , const void *> > args;
  
      size_t localThreads[3] = {16, 16, 1};
-     size_t globalThreads[3];
-     globalThreads[0] = (dst.cols + localThreads[0] - 1) / localThreads[0] * localThreads[0];
-     globalThreads[1] = (dst.rows + localThreads[1] - 1) / localThreads[1] * localThreads[1];
-     globalThreads[2] = 1;
+     size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
      int step_in_pixel = dst.step / dst.elemSize(), offset_in_pixel = dst.offset / dst.elemSize();
-     if(dst.type() == CV_8UC1)
-     {
+     if (dst.type() == CV_8UC1)
          globalThreads[0] = ((dst.cols + 4) / 4 + localThreads[0] - 1) / localThreads[0] * localThreads[0];
-     }
-     char compile_option[32];
-     union sc
-     {
-         cl_uchar4 uval;
-         cl_char4  cval;
-         cl_ushort4 usval;
-         cl_short4 shval;
-         cl_int4 ival;
-         cl_float4 fval;
-         cl_double4 dval;
-     } val;
-     switch(dst.depth())
-     {
-     case CV_8U:
-         val.uval.s[0] = saturate_cast<uchar>(scalar.val[0]);
-         val.uval.s[1] = saturate_cast<uchar>(scalar.val[1]);
-         val.uval.s[2] = saturate_cast<uchar>(scalar.val[2]);
-         val.uval.s[3] = saturate_cast<uchar>(scalar.val[3]);
-         switch(dst.oclchannels())
-         {
-         case 1:
-             sprintf(compile_option, "-D GENTYPE=uchar");
-             args.push_back( std::make_pair( sizeof(cl_uchar) , (void *)&val.uval.s[0] ));
-             break;
-         case 4:
-             sprintf(compile_option, "-D GENTYPE=uchar4");
-             args.push_back( std::make_pair( sizeof(cl_uchar4) , (void *)&val.uval ));
-             break;
-         default:
-             CV_Error(Error::StsUnsupportedFormat, "unsupported channels");
-         }
-         break;
-     case CV_8S:
-         val.cval.s[0] = saturate_cast<char>(scalar.val[0]);
-         val.cval.s[1] = saturate_cast<char>(scalar.val[1]);
-         val.cval.s[2] = saturate_cast<char>(scalar.val[2]);
-         val.cval.s[3] = saturate_cast<char>(scalar.val[3]);
-         switch(dst.oclchannels())
-         {
-         case 1:
-             sprintf(compile_option, "-D GENTYPE=char");
-             args.push_back( std::make_pair( sizeof(cl_char) , (void *)&val.cval.s[0] ));
-             break;
-         case 4:
-             sprintf(compile_option, "-D GENTYPE=char4");
-             args.push_back( std::make_pair( sizeof(cl_char4) , (void *)&val.cval ));
-             break;
-         default:
-             CV_Error(Error::StsUnsupportedFormat, "unsupported channels");
-         }
-         break;
-     case CV_16U:
-         val.usval.s[0] = saturate_cast<ushort>(scalar.val[0]);
-         val.usval.s[1] = saturate_cast<ushort>(scalar.val[1]);
-         val.usval.s[2] = saturate_cast<ushort>(scalar.val[2]);
-         val.usval.s[3] = saturate_cast<ushort>(scalar.val[3]);
-         switch(dst.oclchannels())
-         {
-         case 1:
-             sprintf(compile_option, "-D GENTYPE=ushort");
-             args.push_back( std::make_pair( sizeof(cl_ushort) , (void *)&val.usval.s[0] ));
-             break;
-         case 4:
-             sprintf(compile_option, "-D GENTYPE=ushort4");
-             args.push_back( std::make_pair( sizeof(cl_ushort4) , (void *)&val.usval ));
-             break;
-         default:
-             CV_Error(Error::StsUnsupportedFormat, "unsupported channels");
-         }
-         break;
-     case CV_16S:
-         val.shval.s[0] = saturate_cast<short>(scalar.val[0]);
-         val.shval.s[1] = saturate_cast<short>(scalar.val[1]);
-         val.shval.s[2] = saturate_cast<short>(scalar.val[2]);
-         val.shval.s[3] = saturate_cast<short>(scalar.val[3]);
-         switch(dst.oclchannels())
-         {
-         case 1:
-             sprintf(compile_option, "-D GENTYPE=short");
-             args.push_back( std::make_pair( sizeof(cl_short) , (void *)&val.shval.s[0] ));
-             break;
-         case 4:
-             sprintf(compile_option, "-D GENTYPE=short4");
-             args.push_back( std::make_pair( sizeof(cl_short4) , (void *)&val.shval ));
-             break;
-         default:
-             CV_Error(Error::StsUnsupportedFormat, "unsupported channels");
-         }
-         break;
-     case CV_32S:
-         val.ival.s[0] = saturate_cast<int>(scalar.val[0]);
-         val.ival.s[1] = saturate_cast<int>(scalar.val[1]);
-         val.ival.s[2] = saturate_cast<int>(scalar.val[2]);
-         val.ival.s[3] = saturate_cast<int>(scalar.val[3]);
-         switch(dst.oclchannels())
-         {
-         case 1:
-             sprintf(compile_option, "-D GENTYPE=int");
-             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&val.ival.s[0] ));
-             break;
-         case 2:
-             sprintf(compile_option, "-D GENTYPE=int2");
-             cl_int2 i2val;
-             i2val.s[0] = val.ival.s[0];
-             i2val.s[1] = val.ival.s[1];
-             args.push_back( std::make_pair( sizeof(cl_int2) , (void *)&i2val ));
-             break;
-         case 4:
-             sprintf(compile_option, "-D GENTYPE=int4");
-             args.push_back( std::make_pair( sizeof(cl_int4) , (void *)&val.ival ));
-             break;
-         default:
-             CV_Error(Error::StsUnsupportedFormat, "unsupported channels");
-         }
-         break;
-     case CV_32F:
-         val.fval.s[0] = scalar.val[0];
-         val.fval.s[1] = scalar.val[1];
-         val.fval.s[2] = scalar.val[2];
-         val.fval.s[3] = scalar.val[3];
-         switch(dst.oclchannels())
-         {
-         case 1:
-             sprintf(compile_option, "-D GENTYPE=float");
-             args.push_back( std::make_pair( sizeof(cl_float) , (void *)&val.fval.s[0] ));
-             break;
-         case 4:
-             sprintf(compile_option, "-D GENTYPE=float4");
-             args.push_back( std::make_pair( sizeof(cl_float4) , (void *)&val.fval ));
-             break;
-         default:
-             CV_Error(Error::StsUnsupportedFormat, "unsupported channels");
-         }
-         break;
-     case CV_64F:
-         val.dval.s[0] = scalar.val[0];
-         val.dval.s[1] = scalar.val[1];
-         val.dval.s[2] = scalar.val[2];
-         val.dval.s[3] = scalar.val[3];
-         switch(dst.oclchannels())
-         {
-         case 1:
-             sprintf(compile_option, "-D GENTYPE=double");
-             args.push_back( std::make_pair( sizeof(cl_double) , (void *)&val.dval.s[0] ));
-             break;
-         case 4:
-             sprintf(compile_option, "-D GENTYPE=double4");
-             args.push_back( std::make_pair( sizeof(cl_double4) , (void *)&val.dval ));
-             break;
-         default:
-             CV_Error(Error::StsUnsupportedFormat, "unsupported channels");
-         }
-         break;
-     default:
-         CV_Error(Error::StsUnsupportedFormat, "unknown depth");
-     }
+     const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
+     const char channelMap[] = { ' ', ' ', '2', '4', '4' };
+     std::string buildOptions = format("-D GENTYPE=%s%c", typeMap[dst.depth()], channelMap[dst.channels()]);
+     Mat mat(1, 1, dst.type(), scalar);
  #ifdef CL_VERSION_1_2
-     //this enables backwards portability to
-     //run on OpenCL 1.1 platform if library binaries are compiled with OpenCL 1.2 support
-     if(Context::getContext()->supportsFeature(Context::CL_VER_1_2) &&
+     // this enables backwards portability to
+     // run on OpenCL 1.1 platform if library binaries are compiled with OpenCL 1.2 support
+     if (Context::getContext()->supportsFeature(Context::CL_VER_1_2) &&
          dst.offset == 0 && dst.cols == dst.wholecols)
      {
+         const int sizeofMap[][7] =
+             {
+                 { sizeof(cl_uchar) , sizeof(cl_char) , sizeof(cl_ushort) , sizeof(cl_short) , sizeof(cl_int) , sizeof(cl_float) , sizeof(cl_double)  },
+                 { sizeof(cl_uchar2), sizeof(cl_char2), sizeof(cl_ushort2), sizeof(cl_short2), sizeof(cl_int2), sizeof(cl_float2), sizeof(cl_double2) },
+                 { 0                , 0               , 0                 , 0                , 0              , 0                ,  0                 },
+                 { sizeof(cl_uchar4), sizeof(cl_char4), sizeof(cl_ushort4), sizeof(cl_short4), sizeof(cl_int4), sizeof(cl_float4), sizeof(cl_double4) },
+             };
+         int sizeofGeneric = sizeofMap[dst.oclchannels() - 1][dst.depth()];
          clEnqueueFillBuffer((cl_command_queue)dst.clCxt->oclCommandQueue(),
-             (cl_mem)dst.data, args[0].second, args[0].first, 0, dst.step * dst.rows, 0, NULL, NULL);
+                             (cl_mem)dst.data, (void*)mat.data, sizeofGeneric,
+                             0, dst.step * dst.rows, 0, NULL, NULL);
      }
      else
  #endif
      {
 -        args.push_back( make_pair( sizeof(cl_mem) , (void*)&m.data ));
 -        args.push_back( make_pair( sizeof(cl_mem) , (void *)&dst.data ));
 -        args.push_back( make_pair( sizeof(cl_int) , (void *)&dst.cols ));
 -        args.push_back( make_pair( sizeof(cl_int) , (void *)&dst.rows ));
 -        args.push_back( make_pair( sizeof(cl_int) , (void *)&step_in_pixel ));
 -        args.push_back( make_pair( sizeof(cl_int) , (void *)&offset_in_pixel ));
+         oclMat m(mat);
-         args.push_back( std::make_pair( sizeof(cl_int) , (void *)&offset_in_pixel));
++        args.push_back( std::make_pair( sizeof(cl_mem) , (void*)&m.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst.data ));
 +        args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst.cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst.rows ));
 +        args.push_back( std::make_pair( sizeof(cl_int) , (void *)&step_in_pixel ));
++        args.push_back( std::make_pair( sizeof(cl_int) , (void *)&offset_in_pixel ));
          openCLExecuteKernel(dst.clCxt , &operator_setTo, kernelName, globalThreads,
-             localThreads, args, -1, -1, compile_option);
+             localThreads, args, -1, -1, buildOptions.c_str());
      }
  }
  
 -static void set_to_withmask_run(const oclMat &dst, const Scalar &scalar, const oclMat &mask, string kernelName)
 +static void set_to_withmask_run(const oclMat &dst, const Scalar &scalar, const oclMat &mask, String kernelName)
  {
      CV_DbgAssert( dst.rows == mask.rows && dst.cols == mask.cols);
 -    vector<pair<size_t , const void *> > args;
 +    std::vector<std::pair<size_t , const void *> > args;
-     size_t localThreads[3] = {16, 16, 1};
-     size_t globalThreads[3];
-     globalThreads[0] = (dst.cols + localThreads[0] - 1) / localThreads[0] * localThreads[0];
-     globalThreads[1] = (dst.rows + localThreads[1] - 1) / localThreads[1] * localThreads[1];
-     globalThreads[2] = 1;
+     size_t localThreads[3] = { 16, 16, 1 };
+     size_t globalThreads[3] = { dst.cols, dst.rows, 1 };
      int step_in_pixel = dst.step / dst.elemSize(), offset_in_pixel = dst.offset / dst.elemSize();
-     char compile_option[32];
-     union sc
-     {
-         cl_uchar4 uval;
-         cl_char4  cval;
-         cl_ushort4 usval;
-         cl_short4 shval;
-         cl_int4 ival;
-         cl_float4 fval;
-         cl_double4 dval;
-     } val;
-     switch(dst.depth())
-     {
-     case CV_8U:
-         val.uval.s[0] = saturate_cast<uchar>(scalar.val[0]);
-         val.uval.s[1] = saturate_cast<uchar>(scalar.val[1]);
-         val.uval.s[2] = saturate_cast<uchar>(scalar.val[2]);
-         val.uval.s[3] = saturate_cast<uchar>(scalar.val[3]);
-         switch(dst.oclchannels())
-         {
-         case 1:
-             sprintf(compile_option, "-D GENTYPE=uchar");
-             args.push_back( std::make_pair( sizeof(cl_uchar) , (void *)&val.uval.s[0] ));
-             break;
-         case 4:
-             sprintf(compile_option, "-D GENTYPE=uchar4");
-             args.push_back( std::make_pair( sizeof(cl_uchar4) , (void *)&val.uval ));
-             break;
-         default:
-             CV_Error(Error::StsUnsupportedFormat, "unsupported channels");
-         }
-         break;
-     case CV_8S:
-         val.cval.s[0] = saturate_cast<char>(scalar.val[0]);
-         val.cval.s[1] = saturate_cast<char>(scalar.val[1]);
-         val.cval.s[2] = saturate_cast<char>(scalar.val[2]);
-         val.cval.s[3] = saturate_cast<char>(scalar.val[3]);
-         switch(dst.oclchannels())
-         {
-         case 1:
-             sprintf(compile_option, "-D GENTYPE=char");
-             args.push_back( std::make_pair( sizeof(cl_char) , (void *)&val.cval.s[0] ));
-             break;
-         case 4:
-             sprintf(compile_option, "-D GENTYPE=char4");
-             args.push_back( std::make_pair( sizeof(cl_char4) , (void *)&val.cval ));
-             break;
-         default:
-             CV_Error(Error::StsUnsupportedFormat, "unsupported channels");
-         }
-         break;
-     case CV_16U:
-         val.usval.s[0] = saturate_cast<ushort>(scalar.val[0]);
-         val.usval.s[1] = saturate_cast<ushort>(scalar.val[1]);
-         val.usval.s[2] = saturate_cast<ushort>(scalar.val[2]);
-         val.usval.s[3] = saturate_cast<ushort>(scalar.val[3]);
-         switch(dst.oclchannels())
-         {
-         case 1:
-             sprintf(compile_option, "-D GENTYPE=ushort");
-             args.push_back( std::make_pair( sizeof(cl_ushort) , (void *)&val.usval.s[0] ));
-             break;
-         case 4:
-             sprintf(compile_option, "-D GENTYPE=ushort4");
-             args.push_back( std::make_pair( sizeof(cl_ushort4) , (void *)&val.usval ));
-             break;
-         default:
-             CV_Error(Error::StsUnsupportedFormat, "unsupported channels");
-         }
-         break;
-     case CV_16S:
-         val.shval.s[0] = saturate_cast<short>(scalar.val[0]);
-         val.shval.s[1] = saturate_cast<short>(scalar.val[1]);
-         val.shval.s[2] = saturate_cast<short>(scalar.val[2]);
-         val.shval.s[3] = saturate_cast<short>(scalar.val[3]);
-         switch(dst.oclchannels())
-         {
-         case 1:
-             sprintf(compile_option, "-D GENTYPE=short");
-             args.push_back( std::make_pair( sizeof(cl_short) , (void *)&val.shval.s[0] ));
-             break;
-         case 4:
-             sprintf(compile_option, "-D GENTYPE=short4");
-             args.push_back( std::make_pair( sizeof(cl_short4) , (void *)&val.shval ));
-             break;
-         default:
-             CV_Error(Error::StsUnsupportedFormat, "unsupported channels");
-         }
-         break;
-     case CV_32S:
-         val.ival.s[0] = saturate_cast<int>(scalar.val[0]);
-         val.ival.s[1] = saturate_cast<int>(scalar.val[1]);
-         val.ival.s[2] = saturate_cast<int>(scalar.val[2]);
-         val.ival.s[3] = saturate_cast<int>(scalar.val[3]);
-         switch(dst.oclchannels())
-         {
-         case 1:
-             sprintf(compile_option, "-D GENTYPE=int");
-             args.push_back( std::make_pair( sizeof(cl_int) , (void *)&val.ival.s[0] ));
-             break;
-         case 4:
-             sprintf(compile_option, "-D GENTYPE=int4");
-             args.push_back( std::make_pair( sizeof(cl_int4) , (void *)&val.ival ));
-             break;
-         default:
-             CV_Error(Error::StsUnsupportedFormat, "unsupported channels");
-         }
-         break;
-     case CV_32F:
-         val.fval.s[0] = scalar.val[0];
-         val.fval.s[1] = scalar.val[1];
-         val.fval.s[2] = scalar.val[2];
-         val.fval.s[3] = scalar.val[3];
-         switch(dst.oclchannels())
-         {
-         case 1:
-             sprintf(compile_option, "-D GENTYPE=float");
-             args.push_back( std::make_pair( sizeof(cl_float) , (void *)&val.fval.s[0] ));
-             break;
-         case 4:
-             sprintf(compile_option, "-D GENTYPE=float4");
-             args.push_back( std::make_pair( sizeof(cl_float4) , (void *)&val.fval ));
-             break;
-         default:
-             CV_Error(Error::StsUnsupportedFormat, "unsupported channels");
-         }
-         break;
-     case CV_64F:
-         val.dval.s[0] = scalar.val[0];
-         val.dval.s[1] = scalar.val[1];
-         val.dval.s[2] = scalar.val[2];
-         val.dval.s[3] = scalar.val[3];
-         switch(dst.oclchannels())
-         {
-         case 1:
-             sprintf(compile_option, "-D GENTYPE=double");
-             args.push_back( std::make_pair( sizeof(cl_double) , (void *)&val.dval.s[0] ));
-             break;
-         case 4:
-             sprintf(compile_option, "-D GENTYPE=double4");
-             args.push_back( std::make_pair( sizeof(cl_double4) , (void *)&val.dval ));
-             break;
-         default:
-             CV_Error(Error::StsUnsupportedFormat, "unsupported channels");
-         }
-         break;
-     default:
-         CV_Error(Error::StsUnsupportedFormat, "unknown depth");
-     }
+     const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float", "double" };
+     const char channelMap[] = { ' ', ' ', '2', '4', '4' };
+     std::string buildOptions = format("-D GENTYPE=%s%c", typeMap[dst.depth()], channelMap[dst.channels()]);
+     oclMat m(Mat(1, 1, dst.type(), scalar));
 -    args.push_back( make_pair( sizeof(cl_mem) , (void *)&m.data ));
 -    args.push_back( make_pair( sizeof(cl_mem) , (void *)&dst.data ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&dst.cols ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&dst.rows ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&step_in_pixel ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&offset_in_pixel ));
 -    args.push_back( make_pair( sizeof(cl_mem) , (void *)&mask.data ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&mask.step ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&mask.offset ));
++    args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&m.data ));
 +    args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst.cols ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst.rows ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&step_in_pixel ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&offset_in_pixel ));
 +    args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&mask.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&mask.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&mask.offset ));
      openCLExecuteKernel(dst.clCxt , &operator_setToM, kernelName, globalThreads,
-                         localThreads, args, -1, -1, compile_option);
+                         localThreads, args, -1, -1, buildOptions.c_str());
  }
  
  oclMat &cv::ocl::oclMat::setTo(const Scalar &scalar, const oclMat &mask)
@@@ -845,79 -549,38 +539,38 @@@ oclMat cv::ocl::oclMat::reshape(int new
      oclMat hdr = *this;
  
      int cn = oclchannels();
      if (new_cn == 0)
          new_cn = cn;
  
      int total_width = cols * cn;
      if ((new_cn > total_width || total_width % new_cn != 0) && new_rows == 0)
          new_rows = rows * total_width / new_cn;
  
      if (new_rows != 0 && new_rows != rows)
      {
          int total_size = total_width * rows;
  
          if (!isContinuous())
 -            CV_Error(CV_BadStep, "The matrix is not continuous, thus its number of rows can not be changed");
 +            CV_Error(Error::BadStep, "The matrix is not continuous, thus its number of rows can not be changed");
  
          if ((unsigned)new_rows > (unsigned)total_size)
 -            CV_Error(CV_StsOutOfRange, "Bad new number of rows");
 +            CV_Error(Error::StsOutOfRange, "Bad new number of rows");
  
          total_width = total_size / new_rows;
          if (total_width * new_rows != total_size)
 -            CV_Error(CV_StsBadArg, "The total number of matrix elements is not divisible by the new number of rows");
 +            CV_Error(Error::StsBadArg, "The total number of matrix elements is not divisible by the new number of rows");
  
          hdr.rows = new_rows;
          hdr.step = total_width * elemSize1();
      }
  
      int new_width = total_width / new_cn;
      if (new_width * new_cn != total_width)
 -        CV_Error(CV_BadNumChannels, "The total width is not divisible by the new number of channels");
 +        CV_Error(Error::BadNumChannels, "The total width is not divisible by the new number of channels");
  
      hdr.cols = new_width;
      hdr.wholecols = new_width;
      hdr.flags = (hdr.flags & ~CV_MAT_CN_MASK) | ((new_cn - 1) << CV_CN_SHIFT);
      return hdr;
  
  }
@@@ -71,16 -71,10 +71,10 @@@ namespace c
  {
      namespace ocl
      {
-         inline int divUp(int total, int grain)
-         {
-             return (total + grain - 1) / grain;
-         }
          // provide additional methods for the user to interact with the command queue after a task is fired
 -        static void openCLExecuteKernel_2(Context *clCxt , const char **source, string kernelName, size_t globalThreads[3],
 -                                   size_t localThreads[3],  vector< pair<size_t, const void *> > &args, int channels,
 -                                   int depth, char *build_options, FLUSH_MODE finish_mode)
 +        static void openCLExecuteKernel_2(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, FLUSH_MODE finish_mode)
          {
              //construct kernel name
              //The rule is functionName_Cn_Dn, C represent Channels, D Represent DataType Depth, n represent an integer number
@@@ -86,9 -81,9 +81,9 @@@ inline void setGaussianBlurKernel(cons
  
  static void gaussianBlurOcl(const oclMat &src, int ksizeHalf, oclMat &dst)
  {
--    string kernelName("gaussianBlur");
++    String kernelName("gaussianBlur");
      size_t localThreads[3] = { 256, 1, 1 };
-     size_t globalThreads[3] = { divUp(src.cols, localThreads[0]) * localThreads[0], src.rows, 1 };
+     size_t globalThreads[3] = { src.cols, src.rows, 1 };
      int smem_size = (localThreads[0] + 2*ksizeHalf) * sizeof(float);
  
      CV_Assert(dst.size() == src.size());
  
  static void polynomialExpansionOcl(const oclMat &src, int polyN, oclMat &dst)
  {
--    string kernelName("polynomialExpansion");
++    String kernelName("polynomialExpansion");
      size_t localThreads[3] = { 256, 1, 1 };
      size_t globalThreads[3] = { divUp(src.cols, localThreads[0] - 2*polyN) * localThreads[0], src.rows, 1 };
      int smem_size = 3 * localThreads[0] * sizeof(float);
  
  static void updateMatricesOcl(const oclMat &flowx, const oclMat &flowy, const oclMat &R0, const oclMat &R1, oclMat &M)
  {
--    string kernelName("updateMatrices");
++    String kernelName("updateMatrices");
      size_t localThreads[3] = { 32, 8, 1 };
-     size_t globalThreads[3] = { divUp(flowx.cols, localThreads[0]) * localThreads[0],
-                                 divUp(flowx.rows, localThreads[1]) * localThreads[1],
-                                 1
-                               };
+     size_t globalThreads[3] = { flowx.cols, flowx.rows, 1 };
  
      std::vector< std::pair<size_t, const void *> > args;
      args.push_back(std::make_pair(sizeof(cl_mem), (void *)&M.data));
  
  static void boxFilter5Ocl(const oclMat &src, int ksizeHalf, oclMat &dst)
  {
--    string kernelName("boxFilter5");
++    String kernelName("boxFilter5");
      int height = src.rows / 5;
      size_t localThreads[3] = { 256, 1, 1 };
-     size_t globalThreads[3] = { divUp(src.cols, localThreads[0]) * localThreads[0], height, 1 };
+     size_t globalThreads[3] = { src.cols, height, 1 };
      int smem_size = (localThreads[0] + 2*ksizeHalf) * 5 * sizeof(float);
  
      std::vector< std::pair<size_t, const void *> > args;
  
  static void updateFlowOcl(const oclMat &M, oclMat &flowx, oclMat &flowy)
  {
--    string kernelName("updateFlow");
++    String kernelName("updateFlow");
      int cols = divUp(flowx.cols, 4);
      size_t localThreads[3] = { 32, 8, 1 };
-     size_t globalThreads[3] = { divUp(cols, localThreads[0]) * localThreads[0],
-                                 divUp(flowx.rows, localThreads[1]) * localThreads[0],
-                                 1
-                               };
+     size_t globalThreads[3] = { cols, flowx.rows, 1 };
  
      std::vector< std::pair<size_t, const void *> > args;
      args.push_back(std::make_pair(sizeof(cl_mem), (void *)&flowx.data));
  
  static void gaussianBlur5Ocl(const oclMat &src, int ksizeHalf, oclMat &dst)
  {
--    string kernelName("gaussianBlur5");
++    String kernelName("gaussianBlur5");
      int height = src.rows / 5;
-     int width = src.cols;
      size_t localThreads[3] = { 256, 1, 1 };
-     size_t globalThreads[3] = { divUp(width, localThreads[0]) * localThreads[0], height, 1 };
+     size_t globalThreads[3] = { src.cols, height, 1 };
      int smem_size = (localThreads[0] + 2*ksizeHalf) * 5 * sizeof(float);
  
      std::vector< std::pair<size_t, const void *> > args;
@@@ -324,7 -312,7 +312,7 @@@ void cv::ocl::FarnebackOpticalFlow::pre
  
  void cv::ocl::FarnebackOpticalFlow::setPolynomialExpansionConsts(int n, double sigma)
  {
--    vector<float> buf(n*6 + 3);
++    std::vector<float> buf(n*6 + 3);
      float* g = &buf[0] + n;
      float* xg = g + n*2 + 1;
      float* xxg = xg + n*2 + 1;
@@@ -69,32 -73,19 +69,19 @@@ static void pyrdown_run(const oclMat &s
      CV_Assert(src.depth() != CV_8S);
  
      Context  *clCxt = src.clCxt;
-     //int channels = dst.channels();
-     //int depth = dst.depth();
 -    string kernelName = "pyrDown";
 +    String kernelName = "pyrDown";
  
-     //int vector_lengths[4][7] = {{4, 0, 4, 4, 1, 1, 1},
-     //    {4, 0, 4, 4, 1, 1, 1},
-     //    {4, 0, 4, 4, 1, 1, 1},
-     //    {4, 0, 4, 4, 1, 1, 1}
-     //};
-     //size_t vector_length = vector_lengths[channels-1][depth];
-     //int offset_cols = (dst.offset / dst.elemSize1()) & (vector_length - 1);
      size_t localThreads[3]  = { 256, 1, 1 };
      size_t globalThreads[3] = { src.cols, dst.rows, 1};
  
-     //int dst_step1 = dst.cols * dst.elemSize();
 -    vector<pair<size_t , const void *> > args;
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&src.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src.rows));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&src.cols));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.step ));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&dst.cols));
 +    std::vector<std::pair<size_t , const void *> > args;
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.rows));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.cols));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.cols));
  
      openCLExecuteKernel(clCxt, &pyr_down, kernelName, globalThreads, localThreads, args, src.oclchannels(), src.depth());
  }
@@@ -64,19 -71,29 +70,29 @@@ namespace c
  
              Context *clCxt = src.clCxt;
  
 -            const std::string kernelName = "pyrUp";
+             const char * const typeMap[] = { "uchar", "char", "ushort", "short", "int", "float" };
+             char buildOptions[250], convertString[50];
+             const char * const channelsString = oclChannels == 1 ? "" : "4";
+             sprintf(convertString, "convert_%s%s_sat_rte", typeMap[depth], channelsString);
+             sprintf(buildOptions, "-D Type=%s%s -D floatType=float%s -D convertToType=%s -D convertToFloat=%s",
+                     typeMap[depth], channelsString, channelsString,
+                     depth == CV_32F ? "" : convertString,
+                     oclChannels == 4 ? "convert_float4" : "(float)");
 +            const String kernelName = "pyrUp";
+             int dststep = dst.step / dst.elemSize(), srcstep = src.step / src.elemSize();
  
 -            std::vector< pair<size_t, const void *> > args;
 -            args.push_back( make_pair( sizeof(cl_mem), (void *)&src.data));
 -            args.push_back( make_pair( sizeof(cl_mem), (void *)&dst.data));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&src.rows));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&dst.rows));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&src.cols));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&dst.cols));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&src.offset));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&dst.offset));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&srcstep));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&dststep));
 +            std::vector< std::pair<size_t, const void *> > args;
 +            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&src.data));
 +            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&dst.data));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.rows));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.rows));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.cols));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.cols));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.offset));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.offset));
-             args.push_back( std::make_pair( sizeof(cl_int), (void *)&src.step));
-             args.push_back( std::make_pair( sizeof(cl_int), (void *)&dst.step));
++            args.push_back( std::make_pair( sizeof(cl_int), (void *)&srcstep));
++            args.push_back( std::make_pair( sizeof(cl_int), (void *)&dststep));
  
              size_t globalThreads[3] = {dst.cols, dst.rows, 1};
              size_t localThreads[3]  = {16, 16, 1};
@@@ -148,38 -98,31 +93,31 @@@ namespace c
                  int cols = divUp(mat_dst.cols + offset_cols, vector_length);
  
                  size_t localThreads[3]  = { 64, 4, 1 };
-                 size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
-                                             divUp(mat_dst.rows, localThreads[1]) *localThreads[1],
-                                             1
-                                           };
+                 size_t globalThreads[3] = { cols, mat_dst.rows, 1 };
  
                  int dst_step1 = mat_dst.cols * mat_dst.elemSize();
 -                vector<pair<size_t , const void *> > args;
 -                args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_dst.data));
 -                args.push_back( make_pair( sizeof(cl_int), (void *)&mat_dst.step));
 -                args.push_back( make_pair( sizeof(cl_int), (void *)&mat_dst.offset));
 -                args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_src[0].data));
 -                args.push_back( make_pair( sizeof(cl_int), (void *)&mat_src[0].step));
 -                args.push_back( make_pair( sizeof(cl_int), (void *)&mat_src[0].offset));
 -                args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_src[1].data));
 -                args.push_back( make_pair( sizeof(cl_int), (void *)&mat_src[1].step));
 -                args.push_back( make_pair( sizeof(cl_int), (void *)&mat_src[1].offset));
 +                std::vector<std::pair<size_t , const void *> > args;
 +                args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mat_dst.data));
 +                args.push_back( std::make_pair( sizeof(cl_int), (void *)&mat_dst.step));
 +                args.push_back( std::make_pair( sizeof(cl_int), (void *)&mat_dst.offset));
 +                args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mat_src[0].data));
 +                args.push_back( std::make_pair( sizeof(cl_int), (void *)&mat_src[0].step));
 +                args.push_back( std::make_pair( sizeof(cl_int), (void *)&mat_src[0].offset));
 +                args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mat_src[1].data));
 +                args.push_back( std::make_pair( sizeof(cl_int), (void *)&mat_src[1].step));
 +                args.push_back( std::make_pair( sizeof(cl_int), (void *)&mat_src[1].offset));
  
                  if(channels == 4)
                  {
 -                    args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_src[2].data));
 -                    args.push_back( make_pair( sizeof(cl_int), (void *)&mat_src[2].step));
 -                    args.push_back( make_pair( sizeof(cl_int), (void *)&mat_src[2].offset));
 +                    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mat_src[2].data));
 +                    args.push_back( std::make_pair( sizeof(cl_int), (void *)&mat_src[2].step));
 +                    args.push_back( std::make_pair( sizeof(cl_int), (void *)&mat_src[2].offset));
  
-                     // if channel == 3, then the matrix will convert to channel =4
-                     //if(n == 3)
-                     //   args.push_back( std::make_pair( sizeof(cl_int), (void *)&offset_cols));
                      if(n == 3)
                      {
 -                        args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_src[2].data));
 -                        args.push_back( make_pair( sizeof(cl_int), (void *)&mat_src[2].step));
 -                        args.push_back( make_pair( sizeof(cl_int), (void *)&mat_src[2].offset));
 +                        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mat_src[2].data));
 +                        args.push_back( std::make_pair( sizeof(cl_int), (void *)&mat_src[2].step));
 +                        args.push_back( std::make_pair( sizeof(cl_int), (void *)&mat_src[2].offset));
                      }
                      else if( n == 4)
                      {
                              : divUp(mat_src.cols + max_offset_cols, vector_length);
  
                  size_t localThreads[3]  = { 64, 4, 1 };
-                 size_t globalThreads[3] = { divUp(cols, localThreads[0]) *localThreads[0],
-                                             divUp(mat_src.rows, localThreads[1]) *localThreads[1], 1
-                                           };
+                 size_t globalThreads[3] = { cols, mat_src.rows, 1 };
  
                  int dst_step1 = mat_dst[0].cols * mat_dst[0].elemSize();
 -                vector<pair<size_t , const void *> > args;
 -                args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_src.data));
 -                args.push_back( make_pair( sizeof(cl_int), (void *)&mat_src.step));
 -                args.push_back( make_pair( sizeof(cl_int), (void *)&mat_src.offset));
 -                args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_dst[0].data));
 -                args.push_back( make_pair( sizeof(cl_int), (void *)&mat_dst[0].step));
 -                args.push_back( make_pair( sizeof(cl_int), (void *)&mat_dst[0].offset));
 -                args.push_back( make_pair( sizeof(cl_mem), (void *)&mat_dst[1].data));
 -                args.push_back( make_pair( sizeof(cl_int), (void *)&mat_dst[1].step));
 -                args.push_back( make_pair( sizeof(cl_int), (void *)&mat_dst[1].offset));
 +                std::vector<std::pair<size_t , const void *> > args;
 +                args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mat_src.data));
 +                args.push_back( std::make_pair( sizeof(cl_int), (void *)&mat_src.step));
 +                args.push_back( std::make_pair( sizeof(cl_int), (void *)&mat_src.offset));
 +                args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mat_dst[0].data));
 +                args.push_back( std::make_pair( sizeof(cl_int), (void *)&mat_dst[0].step));
 +                args.push_back( std::make_pair( sizeof(cl_int), (void *)&mat_dst[0].offset));
 +                args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mat_dst[1].data));
 +                args.push_back( std::make_pair( sizeof(cl_int), (void *)&mat_dst[1].step));
 +                args.push_back( std::make_pair( sizeof(cl_int), (void *)&mat_dst[1].offset));
                  if(channels >= 3)
                  {
  
Simple merge
Simple merge
Simple merge
index 0000000,c3df581..70aaa7a
mode 000000,100644..100644
--- /dev/null
@@@ -1,0 -1,1201 +1,1201 @@@
 -    __BEGIN__;
+ /*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-2013, Institute Of Software Chinese Academy Of Science, all rights reserved.
+ // Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved.
+ // Third party copyrights are property of their respective owners.
+ //
+ // @Authors
+ //    Erping Pang, erping@multicorewareinc.com
+ //
+ // 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*/
+ #include "precomp.hpp"
+ using namespace cv;
+ using namespace ocl;
+ #if 1
+ typedef float Qfloat;
+ #define QFLOAT_TYPE CV_32F
+ #else
+ typedef double Qfloat;
+ #define QFLOAT_TYPE CV_64F
+ #endif
+ namespace cv
+ {
+ namespace ocl
+ {
+ ///////////////////////////OpenCL kernel strings///////////////////////////
+ extern const char *svm;
+ }
+ }
+ class CvSVMKernel_ocl: public CvSVMKernel
+ {
+ public:
+     typedef void (CvSVMKernel_ocl::*Calc_ocl)( int vec_count, const int row_idx, Qfloat* results, Mat& src);
+     CvSVMKernel_ocl(const CvSVMParams* params, Calc_ocl _calc_func , Calc _calc_func1);
+     Calc_ocl calc_func_ocl;
+     bool create( const CvSVMParams* params, Calc_ocl _calc_func, Calc _calc_func1);
+     void calc( int vcount, const int row_idx, Qfloat* results, Mat& src);
+     void calc_linear( int vec_count, const int row_idx, Qfloat* results, Mat& src);
+     void calc_poly( int vec_count, const int row_idx, Qfloat* results, Mat& src);
+     void calc_sigmoid( int vec_count, const int row_idx, Qfloat* results, Mat& src);
+     void calc_non_rbf_base( int vec_count, const int row_idx, Qfloat* results, Mat& src);
+     void calc_rbf( int vec_count, const int row_idx, Qfloat* results, Mat& src);
+ };
+ class CvSVMSolver_ocl: public CvSVMSolver
+ {
+ public:
+     CvSVMSolver_ocl();
+     CvSVMSolver_ocl(const CvSVMParams *);
+     float* get_row_base( int i, bool* _existed, Mat& src);
+     bool solve_generic( CvSVMSolutionInfo& si );
+     float* get_row( int i, float* dst, Mat& src);
+ };
+ typedef struct CvSparseVecElem32f
+ {
+     int idx;
+     float val;
+ } CvSparseVecElem32f;
+ static int icvCmpSparseVecElems( const void* a, const void* b )
+ {
+     return ((CvSparseVecElem32f*)a)->idx - ((CvSparseVecElem32f*)b)->idx;
+ }
+ void cvPreparePredictData( const CvArr* sample, int dims_all, const CvMat* comp_idx,
+                            int class_count, const CvMat* prob, float** row_sample,
+                            int as_sparse CV_DEFAULT(0) );
+ void  cvPreparePredictData( const CvArr* _sample, int dims_all,
+                             const CvMat* comp_idx, int class_count,
+                             const CvMat* prob, float** _row_sample,
+                             int as_sparse )
+ {
+     float* row_sample = 0;
+     int* inverse_comp_idx = 0;
+     CV_FUNCNAME( "cvPreparePredictData" );
 -    __END__;
++    __CV_BEGIN__;
+     const CvMat* sample = (const CvMat*)_sample;
+     float* sample_data;
+     int sample_step;
+     int is_sparse = CV_IS_SPARSE_MAT(sample);
+     int d, sizes[CV_MAX_DIM];
+     int i, dims_selected;
+     int vec_size;
+     if( !is_sparse && !CV_IS_MAT(sample) )
+     {
+         CV_ERROR( !sample ? CV_StsNullPtr : CV_StsBadArg, "The sample is not a valid vector" );
+     }
+     if( cvGetElemType( sample ) != CV_32FC1 )
+     {
+         CV_ERROR( CV_StsUnsupportedFormat, "Input sample must have 32fC1 type" );
+     }
+     CV_CALL( d = cvGetDims( sample, sizes ));
+     if( !((is_sparse && d == 1) || (!is_sparse && d == 2 && (sample->rows == 1 || sample->cols == 1))) )
+     {
+         CV_ERROR( CV_StsBadSize, "Input sample must be 1-dimensional vector" );
+     }
+     if( d == 1 )
+     {
+         sizes[1] = 1;
+     }
+     if( sizes[0] + sizes[1] - 1 != dims_all )
+         CV_ERROR( CV_StsUnmatchedSizes,
+                   "The sample size is different from what has been used for training" );
+     if( !_row_sample )
+     {
+         CV_ERROR( CV_StsNullPtr, "INTERNAL ERROR: The row_sample pointer is NULL" );
+     }
+     if( comp_idx && (!CV_IS_MAT(comp_idx) || comp_idx->rows != 1 ||
+                      CV_MAT_TYPE(comp_idx->type) != CV_32SC1) )
+     {
+         CV_ERROR( CV_StsBadArg, "INTERNAL ERROR: invalid comp_idx" );
+     }
+     dims_selected = comp_idx ? comp_idx->cols : dims_all;
+     if( prob )
+     {
+         if( !CV_IS_MAT(prob) )
+         {
+             CV_ERROR( CV_StsBadArg, "The output matrix of probabilities is invalid" );
+         }
+         if( (prob->rows != 1 && prob->cols != 1) ||
+                 (CV_MAT_TYPE(prob->type) != CV_32FC1 &&
+                  CV_MAT_TYPE(prob->type) != CV_64FC1) )
+             CV_ERROR( CV_StsBadSize,
+                       "The matrix of probabilities must be 1-dimensional vector of 32fC1 type" );
+         if( prob->rows + prob->cols - 1 != class_count )
+             CV_ERROR( CV_StsUnmatchedSizes,
+                       "The vector of probabilities must contain as many elements as "
+                       "the number of classes in the training set" );
+     }
+     vec_size = !as_sparse ? dims_selected * sizeof(row_sample[0]) :
+                (dims_selected + 1) * sizeof(CvSparseVecElem32f);
+     if( CV_IS_MAT(sample) )
+     {
+         sample_data = sample->data.fl;
+         sample_step = CV_IS_MAT_CONT(sample->type) ? 1 : sample->step / sizeof(row_sample[0]);
+         if( !comp_idx && CV_IS_MAT_CONT(sample->type) && !as_sparse )
+         {
+             *_row_sample = sample_data;
+         }
+         else
+         {
+             CV_CALL( row_sample = (float*)cvAlloc( vec_size ));
+             if( !comp_idx )
+                 for( i = 0; i < dims_selected; i++ )
+                 {
+                     row_sample[i] = sample_data[sample_step * i];
+                 }
+             else
+             {
+                 int* comp = comp_idx->data.i;
+                 for( i = 0; i < dims_selected; i++ )
+                 {
+                     row_sample[i] = sample_data[sample_step * comp[i]];
+                 }
+             }
+             *_row_sample = row_sample;
+         }
+         if( as_sparse )
+         {
+             const float* src = (const float*)row_sample;
+             CvSparseVecElem32f* dst = (CvSparseVecElem32f*)row_sample;
+             dst[dims_selected].idx = -1;
+             for( i = dims_selected - 1; i >= 0; i-- )
+             {
+                 dst[i].idx = i;
+                 dst[i].val = src[i];
+             }
+         }
+     }
+     else
+     {
+         CvSparseNode* node;
+         CvSparseMatIterator mat_iterator;
+         const CvSparseMat* sparse = (const CvSparseMat*)sample;
+         assert( is_sparse );
+         node = cvInitSparseMatIterator( sparse, &mat_iterator );
+         CV_CALL( row_sample = (float*)cvAlloc( vec_size ));
+         if( comp_idx )
+         {
+             CV_CALL( inverse_comp_idx = (int*)cvAlloc( dims_all * sizeof(int) ));
+             memset( inverse_comp_idx, -1, dims_all * sizeof(int) );
+             for( i = 0; i < dims_selected; i++ )
+             {
+                 inverse_comp_idx[comp_idx->data.i[i]] = i;
+             }
+         }
+         if( !as_sparse )
+         {
+             memset( row_sample, 0, vec_size );
+             for( ; node != 0; node = cvGetNextSparseNode(&mat_iterator) )
+             {
+                 int idx = *CV_NODE_IDX( sparse, node );
+                 if( inverse_comp_idx )
+                 {
+                     idx = inverse_comp_idx[idx];
+                     if( idx < 0 )
+                     {
+                         continue;
+                     }
+                 }
+                 row_sample[idx] = *(float*)CV_NODE_VAL( sparse, node );
+             }
+         }
+         else
+         {
+             CvSparseVecElem32f* ptr = (CvSparseVecElem32f*)row_sample;
+             for( ; node != 0; node = cvGetNextSparseNode(&mat_iterator) )
+             {
+                 int idx = *CV_NODE_IDX( sparse, node );
+                 if( inverse_comp_idx )
+                 {
+                     idx = inverse_comp_idx[idx];
+                     if( idx < 0 )
+                     {
+                         continue;
+                     }
+                 }
+                 ptr->idx = idx;
+                 ptr->val = *(float*)CV_NODE_VAL( sparse, node );
+                 ptr++;
+             }
+             qsort( row_sample, ptr - (CvSparseVecElem32f*)row_sample,
+                    sizeof(ptr[0]), icvCmpSparseVecElems );
+             ptr->idx = -1;
+         }
+         *_row_sample = row_sample;
+     }
 -    string kernelName = "svm_sigmod";
++    __CV_END__;
+     if( inverse_comp_idx )
+     {
+         cvFree( &inverse_comp_idx );
+     }
+     if( cvGetErrStatus() < 0 && _row_sample )
+     {
+         cvFree( &row_sample );
+         *_row_sample = 0;
+     }
+ }
+ float CvSVM_OCL::predict( const int row_index, int row_len, Mat& src, bool returnDFVal ) const
+ {
+     assert( kernel );
+     (void)row_len;
+     int class_count = class_labels ? class_labels->cols :
+                       params.svm_type == ONE_CLASS ? 1 : 0;
+     float result = 0;
+     cv::AutoBuffer<float> _buffer(sv_total + (class_count + 1) * 2);
+     float* buffer = _buffer;
+     if( params.svm_type == EPS_SVR ||
+             params.svm_type == NU_SVR ||
+             params.svm_type == ONE_CLASS )
+     {
+         CvSVMDecisionFunc* df = (CvSVMDecisionFunc*)decision_func;
+         int i, sv_count = df->sv_count;
+         double sum = -df->rho;
+         ((CvSVMKernel_ocl*)kernel)->calc( sv_count, row_index, buffer, src);
+         for( i = 0; i < sv_count; i++ )
+         {
+             sum += buffer[i] * df->alpha[i];
+         }
+         result = params.svm_type == ONE_CLASS ? (float)(sum > 0) : (float)sum;
+     }
+     else if( params.svm_type == C_SVC ||
+              params.svm_type == NU_SVC )
+     {
+         CvSVMDecisionFunc* df = (CvSVMDecisionFunc*)decision_func;
+         int* vote = (int*)(buffer + sv_total);
+         int i, j, k;
+         memset( vote, 0, class_count * sizeof(vote[0]));
+         ((CvSVMKernel_ocl*)kernel)->calc( sv_total, row_index, buffer, src);
+         double sum = 0.;
+         for( i = 0; i < class_count; i++ )
+         {
+             for( j = i + 1; j < class_count; j++, df++ )
+             {
+                 sum = -df->rho;
+                 int sv_count = df->sv_count;
+                 for( k = 0; k < sv_count; k++ )
+                 {
+                     sum += df->alpha[k] * buffer[df->sv_index[k]];
+                 }
+                 vote[sum > 0 ? i : j]++;
+             }
+         }
+         for( i = 1, k = 0; i < class_count; i++ )
+         {
+             if( vote[i] > vote[k] )
+             {
+                 k = i;
+             }
+         }
+         result = returnDFVal && class_count == 2 ? (float)sum : (float)(class_labels->data.i[k]);
+     }
+     else
+         CV_Error( CV_StsBadArg, "INTERNAL ERROR: Unknown SVM type, "
+                   "the SVM structure is probably corrupted" );
+     return result;
+ }
+ float CvSVM_OCL::predict( const Mat& _sample, bool returnDFVal ) const
+ {
+     CvMat sample = _sample;
+     return CvSVM::predict(&sample, returnDFVal);
+ }
+ float CvSVM_OCL::predict( const int row_index, Mat& src, bool returnDFVal) const
+ {
+     float result = 0;
+     result = predict( row_index, get_var_count(), src, returnDFVal);
+     return result;
+ }
+ #undef get_C
+ #define get_C(i) (C[y[i]>0])
+ #undef is_upper_bound
+ #define is_upper_bound(i) (alpha_status[i] > 0)
+ #undef is_lower_bound
+ #define is_lower_bound(i) (alpha_status[i] < 0)
+ #undef update_alpha_status
+ #define update_alpha_status(i) \
+     alpha_status[i] = (schar)(alpha[i] >= get_C(i) ? 1 : alpha[i] <= 0 ? -1 : 0)
+ CvSVMSolver_ocl::CvSVMSolver_ocl(const CvSVMParams* _params)
+ {
+     params = _params;
+ }
+ float* CvSVMSolver_ocl::get_row( int i, float* dst, Mat& src )
+ {
+     bool existed = false;
+     float* row = get_row_base( i, &existed, src);
+     return (this->*get_row_func)( i, row, dst, existed );
+ }
+ float* CvSVMSolver_ocl::get_row_base( int i, bool* _existed, Mat& src )
+ {
+     int i1 = i < sample_count ? i : i - sample_count;
+     CvSVMKernelRow* row = rows + i1;
+     bool existed = row->data != 0;
+     Qfloat* data;
+     if( existed || cache_size <= 0 )
+     {
+         CvSVMKernelRow* del_row = existed ? row : lru_list.prev;
+         data = del_row->data;
+         assert( data != 0 );
+         // delete row from the LRU list
+         del_row->data = 0;
+         del_row->prev->next = del_row->next;
+         del_row->next->prev = del_row->prev;
+     }
+     else
+     {
+         data = (Qfloat*)cvMemStorageAlloc( storage, cache_line_size );
+         cache_size -= cache_line_size;
+     }
+     // insert row into the LRU list
+     row->data = data;
+     row->prev = &lru_list;
+     row->next = lru_list.next;
+     row->prev->next = row->next->prev = row;
+     if( !existed )
+     {
+         ((CvSVMKernel_ocl*)kernel)->calc( sample_count, i1, row->data, src);
+     }
+     if( _existed )
+     {
+         *_existed = existed;
+     }
+     return row->data;
+ }
+ #ifndef HAVE_CLAMDBLAS
+ static void matmul_sigmod(oclMat & src, oclMat & src2, oclMat & dst, int src_rows, int src2_cols, int var_count, double alpha1, double beta1)
+ {
+     Context *clCxt = Context::getContext();
 -    vector< pair<size_t, const void *> > args;
 -    args.push_back(make_pair(sizeof(cl_mem), (void* )&src.data));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&src_step));
 -    args.push_back(make_pair(sizeof(cl_mem), (void* )&src2.data));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&src2_step));
 -    args.push_back(make_pair(sizeof(cl_mem), (void* )&dst.data));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&dst_step));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&src_rows));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&src2_cols));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&width));
++    String kernelName = "svm_sigmod";
+     int src_step = (int)src.step / src.elemSize();
+     int src2_step = (int)src2.step / src2.elemSize();
+     int dst_step = (int)dst.step / dst.elemSize();
+     int x = MIN(16, src_rows);
+     int y = MIN(16, src2_cols);
+     size_t localThreads[] = {x, y, 1};
+     size_t globalThreads[] = {src2_cols, src_rows, 1};
+     int width = var_count;
 -        args.push_back(make_pair(sizeof(cl_float), (void* )&alpha));
 -        args.push_back(make_pair(sizeof(cl_float), (void* )&beta));
++    std::vector< std::pair<size_t, const void *> > args;
++    args.push_back(std::make_pair(sizeof(cl_mem), (void* )&src.data));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&src_step));
++    args.push_back(std::make_pair(sizeof(cl_mem), (void* )&src2.data));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&src2_step));
++    args.push_back(std::make_pair(sizeof(cl_mem), (void* )&dst.data));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&dst_step));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&src_rows));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&src2_cols));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&width));
+     float alpha = 0.0f, beta = 0.0f;
+     if(!Context::getContext()->supportsFeature(Context::CL_DOUBLE))
+     {
+         alpha = (float)alpha1;
+         beta = (float)beta1;
 -        args.push_back(make_pair(sizeof(cl_double), (void* )&alpha1));
 -        args.push_back(make_pair(sizeof(cl_double), (void* )&beta1));
++        args.push_back(std::make_pair(sizeof(cl_float), (void* )&alpha));
++        args.push_back(std::make_pair(sizeof(cl_float), (void* )&beta));
+     }
+     else
+     {
 -    string kernelName = "svm_poly";
++        args.push_back(std::make_pair(sizeof(cl_double), (void* )&alpha1));
++        args.push_back(std::make_pair(sizeof(cl_double), (void* )&beta1));
+     }
+     openCLExecuteKernel(clCxt, &svm, kernelName, globalThreads, localThreads, args, -1, -1);
+ }
+ static void matmul_poly(oclMat & src, oclMat & src2, oclMat & dst, int src_rows, int src2_cols, int var_count, double alpha1, double beta1, double degree1, bool flag)
+ {
+     Context *clCxt = Context::getContext();
 -    vector< pair<size_t, const void *> > args;
 -    args.push_back(make_pair(sizeof(cl_mem), (void* )&src.data));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&src_step));
 -    args.push_back(make_pair(sizeof(cl_mem), (void* )&src2.data));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&src2_step));
 -    args.push_back(make_pair(sizeof(cl_mem), (void* )&dst.data));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&dst_step));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&src_rows));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&src2_cols));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&width));
++    String kernelName = "svm_poly";
+     int src_step = (int)src.step / src.elemSize();
+     int src2_step = (int)src2.step / src2.elemSize();
+     int dst_step = (int)dst.step / dst.elemSize();
+     int x = MIN(16, src_rows);
+     int y = MIN(16, src2_cols);
+     size_t localThreads[] = {x, y, 1};
+     size_t globalThreads[] = {src2_cols, src_rows, 1};
+     int width = var_count;
+     char build_options[50];
+     if(flag)
+     {
+         sprintf(build_options, "-D ADDPOW");
+     }
 -        args.push_back(make_pair(sizeof(cl_float), (void* )&alpha));
 -        args.push_back(make_pair(sizeof(cl_float), (void* )&beta));
 -        args.push_back(make_pair(sizeof(cl_float), (void* )&degree));
++    std::vector< std::pair<size_t, const void *> > args;
++    args.push_back(std::make_pair(sizeof(cl_mem), (void* )&src.data));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&src_step));
++    args.push_back(std::make_pair(sizeof(cl_mem), (void* )&src2.data));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&src2_step));
++    args.push_back(std::make_pair(sizeof(cl_mem), (void* )&dst.data));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&dst_step));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&src_rows));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&src2_cols));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&width));
+     float alpha = 0.0f, beta = 0.0f, degree = 0.0f;
+     if(!Context::getContext()->supportsFeature(Context::CL_DOUBLE))
+     {
+         alpha = (float)alpha1;
+         beta = (float)beta1;
+         degree = (float)degree1;
 -        args.push_back(make_pair(sizeof(cl_double), (void* )&alpha1));
 -        args.push_back(make_pair(sizeof(cl_double), (void* )&beta1));
 -        args.push_back(make_pair(sizeof(cl_double), (void* )&degree1));
++        args.push_back(std::make_pair(sizeof(cl_float), (void* )&alpha));
++        args.push_back(std::make_pair(sizeof(cl_float), (void* )&beta));
++        args.push_back(std::make_pair(sizeof(cl_float), (void* )&degree));
+     }
+     else
+     {
 -    string kernelName = "svm_linear";
++        args.push_back(std::make_pair(sizeof(cl_double), (void* )&alpha1));
++        args.push_back(std::make_pair(sizeof(cl_double), (void* )&beta1));
++        args.push_back(std::make_pair(sizeof(cl_double), (void* )&degree1));
+     }
+     openCLExecuteKernel(clCxt, &svm, kernelName, globalThreads, localThreads, args, -1, -1, build_options);
+ }
+ static void matmul_linear(oclMat & src, oclMat & src2, oclMat & dst, int src_rows, int src2_cols, int var_count, double alpha1, double beta1)
+ {
+     Context *clCxt = Context::getContext();
 -    vector< pair<size_t, const void *> > args;
 -    args.push_back(make_pair(sizeof(cl_mem), (void* )&src.data));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&src_step));
 -    args.push_back(make_pair(sizeof(cl_mem), (void* )&src2.data));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&src2_step));
 -    args.push_back(make_pair(sizeof(cl_mem), (void* )&dst.data));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&dst_step));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&src_rows));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&src2_cols));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&width));
++    String kernelName = "svm_linear";
+     int src_step = (int)src.step / src.elemSize();
+     int src2_step = (int)src2.step / src2.elemSize();
+     int dst_step = (int)dst.step / dst.elemSize();
+     int x = MIN(16, src_rows);
+     int y = MIN(16, src2_cols);
+     size_t localThreads[] = {x, y, 1};
+     size_t globalThreads[] = {src2_cols, src_rows, 1};
+     int width = var_count;
 -        args.push_back(make_pair(sizeof(cl_float), (void* )&alpha));
 -        args.push_back(make_pair(sizeof(cl_float), (void* )&beta));
++    std::vector< std::pair<size_t, const void *> > args;
++    args.push_back(std::make_pair(sizeof(cl_mem), (void* )&src.data));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&src_step));
++    args.push_back(std::make_pair(sizeof(cl_mem), (void* )&src2.data));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&src2_step));
++    args.push_back(std::make_pair(sizeof(cl_mem), (void* )&dst.data));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&dst_step));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&src_rows));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&src2_cols));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&width));
+     float alpha = 0.0f, beta = 0.0f;
+     if(!Context::getContext()->supportsFeature(Context::CL_DOUBLE))
+     {
+         alpha = (float)alpha1;
+         beta = (float)beta1;
 -        args.push_back(make_pair(sizeof(cl_double), (void* )&alpha1));
 -        args.push_back(make_pair(sizeof(cl_double), (void* )&beta1));
++        args.push_back(std::make_pair(sizeof(cl_float), (void* )&alpha));
++        args.push_back(std::make_pair(sizeof(cl_float), (void* )&beta));
+     }
+     else
+     {
 -    string kernelName = "svm_rbf";
++        args.push_back(std::make_pair(sizeof(cl_double), (void* )&alpha1));
++        args.push_back(std::make_pair(sizeof(cl_double), (void* )&beta1));
+     }
+     openCLExecuteKernel(clCxt, &svm, kernelName, globalThreads, localThreads, args, -1, -1);
+ }
+ #endif // #ifndef HAVE_CLAMDBLAS
+ static void matmul_rbf(oclMat& src, oclMat& src_e, oclMat& dst, int src_rows, int src2_cols, int var_count, double gamma1, bool flag)
+ {
+     Context *clCxt = Context::getContext();
 -    vector< pair<size_t, const void *> > args;
 -    args.push_back(make_pair(sizeof(cl_mem), (void* )&src.data));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&src_step));
 -    args.push_back(make_pair(sizeof(cl_mem), (void* )&src_e.data));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&src_e_step));
 -    args.push_back(make_pair(sizeof(cl_mem), (void* )&dst.data));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&dst_step));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&src_rows));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&src2_cols));
 -    args.push_back(make_pair(sizeof(cl_int), (void* )&width));
++    String kernelName = "svm_rbf";
+     int width = var_count;
+     int src_step = (int)src.step / src.elemSize();
+     int src_e_step = (int)src_e.step / src_e.elemSize();
+     int dst_step = (int)dst.step / dst.elemSize();
+     int x = MIN(16, src_rows);
+     int y = MIN(16, src2_cols);
+     size_t localThreads[] = {x, y, 1};
+     size_t globalThreads[] = {src2_cols,  src_rows, 1};
+     char build_options[50];
+     if(flag)
+     {
+         sprintf(build_options, "-D ADDEXP");
+     }
 -        args.push_back(make_pair(sizeof(cl_float), (void* )&gamma));
++    std::vector< std::pair<size_t, const void *> > args;
++    args.push_back(std::make_pair(sizeof(cl_mem), (void* )&src.data));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&src_step));
++    args.push_back(std::make_pair(sizeof(cl_mem), (void* )&src_e.data));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&src_e_step));
++    args.push_back(std::make_pair(sizeof(cl_mem), (void* )&dst.data));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&dst_step));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&src_rows));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&src2_cols));
++    args.push_back(std::make_pair(sizeof(cl_int), (void* )&width));
+     float gamma = 0.0f;
+     if(!Context::getContext()->supportsFeature(Context::CL_DOUBLE))
+     {
+         gamma = (float)gamma1;
 -        args.push_back(make_pair(sizeof(cl_double), (void* )&gamma1));
++        args.push_back(std::make_pair(sizeof(cl_float), (void* )&gamma));
+     }
+     else
+     {
 -        __BEGIN__;
++        args.push_back(std::make_pair(sizeof(cl_double), (void* )&gamma1));
+     }
+     openCLExecuteKernel(clCxt, &svm, kernelName, globalThreads, localThreads, args, -1, -1, build_options);
+ }
+ float CvSVM_OCL::predict(const CvMat* samples, CV_OUT CvMat* results) const
+ {
+     int var_count = get_var_count();
+     int sample_count = samples->rows;
+     //float* row_sample = 0;
+     Mat src_temp = Mat(sample_count, var_count, CV_32FC1);
+     CV_FUNCNAME( "CvSVM::predict" );
+     for(int i = 0; i < samples->rows; i++)
+     {
 -        __END__;
++        __CV_BEGIN__;
+         CvMat sample;
+         float* row_sample = 0;
+         cvGetRow( samples, &sample, i );
+         int class_count;
+         if( !kernel )
+         {
+             CV_ERROR( CV_StsBadArg, "The SVM should be trained first" );
+         }
+         class_count = class_labels ? class_labels->cols :
+                       params.svm_type == ONE_CLASS ? 1 : 0;
+         CV_CALL( cvPreparePredictData(&sample, var_all, var_idx,
+                                       class_count, 0, &row_sample ));
+         for(int j = 0; j < var_count; ++j)
+         {
+             src_temp.at<float>(i, j) = row_sample[j];
+         }
++        __CV_END__;
+     }
+     Mat dst1;
+     double alpha1 = 0.0, beta1 = 0.0, gamma1 = 0.0, degree1 = 0.0;
+     if(params.kernel_type == CvSVM::LINEAR)
+     {
+         alpha1 = 1;
+         beta1 = 0;
+     }
+     if(params.kernel_type == CvSVM::POLY)
+     {
+         alpha1 = params.gamma;
+         beta1 = params.coef0;
+         degree1 = params.degree;
+     }
+     if(params.kernel_type == CvSVM::SIGMOID)
+     {
+         alpha1 = - 2 * params.gamma;
+         beta1 = - 2 * params.coef0;
+     }
+     if(params.kernel_type == CvSVM::RBF)
+     {
+         gamma1 = - params.gamma;
+     }
+     Mat sv_temp = Mat(sv_total, var_count, CV_32FC1, Scalar::all(0));
+     for(int i = 0; i < sv_total; ++i)
+     {
+         for(int j = 0; j < var_count; ++j)
+         {
+             sv_temp.at<float>(i, j) = sv[i][j];
+         }
+     }
+     oclMat src(sample_count, var_count, CV_32FC1, Scalar::all(0));
+     oclMat sv_;
+     src.upload(src_temp);
+     oclMat dst;
+ #if defined HAVE_CLAMDBLAS
+     dst = oclMat(sample_count, sv_total, CV_32FC1);
+     oclMat src3(sample_count, sv_total, CV_32FC1, Scalar::all(1));
+     if(params.kernel_type != CvSVM::RBF)
+     {
+         Mat sv_temp1;
+         transpose(sv_temp, sv_temp1);
+         sv_.upload(sv_temp1);
+         gemm(src, sv_, alpha1, src3, beta1, dst);
+     }
+ #else
+     if(!Context::getContext()->supportsFeature(Context::CL_DOUBLE))
+     {
+         dst = oclMat(sample_count, sv_total, CV_32FC1);
+     }
+     else
+     {
+         dst = oclMat(sample_count, sv_total, CV_64FC1);
+     }
+     if(params.kernel_type == CvSVM::LINEAR)
+     {
+         sv_.upload(sv_temp);
+         matmul_linear(src, sv_, dst, sample_count, sv_total, var_count, alpha1, beta1);
+     }
+     if( params.kernel_type == CvSVM::SIGMOID)
+     {
+         sv_.upload(sv_temp);
+         matmul_sigmod(src, sv_, dst, sample_count, sv_total, var_count, alpha1, beta1);
+     }
+     if(params.kernel_type == CvSVM::POLY)
+     {
+         sv_.upload(sv_temp);
+         if(sample_count > 0)
+         {
+             matmul_poly(src, sv_, dst, sample_count, sv_total, var_count, alpha1, beta1, degree1, true);
+         }
+         else
+         {
+             matmul_poly(src, sv_, dst, sample_count, sv_total, var_count, alpha1, beta1, degree1, false);
+         }
+     }
+ #endif
+     if(params.kernel_type == CvSVM::RBF)
+     {
+         sv_.upload(sv_temp);
+         if(!Context::getContext()->supportsFeature(Context::CL_DOUBLE))
+         {
+             dst = oclMat(sample_count, sv_total, CV_32FC1);
+         }
+         else
+         {
+             dst = oclMat(sample_count, sv_total, CV_64FC1);
+         }
+         if(sample_count > 0)
+         {
+             matmul_rbf(src, sv_, dst, sample_count, sv_total, var_count, gamma1, true);
+         }
+         else
+         {
+             matmul_rbf(src, sv_, dst, sample_count, sv_total, var_count, gamma1, false);
+         }
+     }
+     dst.download(dst1);
+     float result = 0;
+     for(int i = 0; i < samples->rows; i++ )
+     {
+         int r = (int)this->predict(i, dst1);
+         if (results)
+         {
+             results->data.fl[i] = (float)r;
+         }
+         if (i == 0)
+         {
+             result = (float)r;
+         }
+     }
+     return result;
+ }
+ void CvSVM_OCL::predict( cv::InputArray _samples, cv::OutputArray _results ) const
+ {
+     _results.create(_samples.size().height, 1, CV_32F);
+     CvMat samples = _samples.getMat(), results = _results.getMat();
+     predict(&samples, &results);
+ }
+ bool CvSVMSolver_ocl::solve_generic( CvSVMSolutionInfo& si )
+ {
+     int iter = 0;
+     int i, j, k;
+     // 1. initialize gradient and alpha status
+     for( i = 0; i < alpha_count; i++ )
+     {
+         update_alpha_status(i);
+         G[i] = b[i];
+         if( fabs(G[i]) > 1e200 )
+         {
+             return false;
+         }
+     }
+     Mat dst1;
+     double alpha1 = 0.0, beta1 = 0.0, gamma1 = 0.0, degree1 = 0.0;
+     if(params->kernel_type == CvSVM::LINEAR)
+     {
+         alpha1 = 1;
+         beta1 = 0;
+     }
+     if(params->kernel_type == CvSVM::POLY)
+     {
+         alpha1 = params->gamma;
+         beta1 = params->coef0;
+         degree1 = params->degree;
+     }
+     if(params->kernel_type == CvSVM::SIGMOID)
+     {
+         alpha1 = -2 * params->gamma;
+         beta1 = -2 * params->coef0;
+     }
+     if(params->kernel_type == CvSVM::RBF)
+     {
+         gamma1 = -params->gamma;
+     }
+     Mat src1 = Mat(sample_count, var_count, CV_32FC1);
+     for(int i = 0; i < sample_count; ++i)
+     {
+         for(int j = 0; j < var_count; ++j)
+         {
+             src1.at<float>(i, j) = samples[i][j];
+         }
+     }
+     oclMat src, src_e;
+     src.upload(src1);
+     oclMat dst;
+ #if defined HAVE_CLAMDBLAS
+     dst = oclMat(sample_count, sample_count, CV_32FC1);
+     oclMat src3(sample_count, sample_count, CV_32FC1, Scalar::all(1));
+     if(params->kernel_type != CvSVM::RBF)
+     {
+         ocl::transpose(src, src_e);
+         gemm(src, src_e, alpha1, src3, beta1, dst);
+     }
+ #else
+     if(!Context::getContext()->supportsFeature(Context::CL_DOUBLE))
+     {
+         dst = oclMat(sample_count, sample_count, CV_32FC1);
+     }
+     else
+     {
+         dst = oclMat(sample_count, sample_count, CV_64FC1);
+     }
+     if(params->kernel_type == CvSVM::LINEAR )
+     {
+         src_e = src;
+         matmul_linear(src, src_e, dst, sample_count, sample_count, var_count, alpha1, beta1);
+     }
+     if( params->kernel_type == CvSVM::SIGMOID)
+     {
+         src_e = src;
+         matmul_sigmod(src, src_e, dst, sample_count, sample_count, var_count, alpha1, beta1);
+     }
+     if(params->kernel_type == CvSVM::POLY)
+     {
+         src_e = src;
+         if(sample_count > 0)
+         {
+             matmul_poly(src, src_e, dst, sample_count, sample_count, var_count, alpha1, beta1, degree1, true);
+         }
+         else
+         {
+             matmul_poly(src, src_e, dst, sample_count, sample_count, var_count, alpha1, beta1, degree1, false);
+         }
+     }
+ #endif
+     if(params->kernel_type == CvSVM::RBF)
+     {
+         src_e = src;
+         if(!Context::getContext()->supportsFeature(Context::CL_DOUBLE))
+         {
+             dst = oclMat(sample_count, sample_count, CV_32FC1);
+         }
+         else
+         {
+             dst = oclMat(sample_count, sample_count, CV_64FC1);
+         }
+         if(sample_count > 0)
+         {
+             matmul_rbf(src, src_e, dst, sample_count, sample_count, var_count, gamma1, true);
+         }
+         else
+         {
+             matmul_rbf(src, src_e, dst, sample_count, sample_count, var_count, gamma1, false);
+         }
+     }
+     dst.download(dst1);
+     for( i = 0; i < alpha_count; i++ )
+     {
+         if( !is_lower_bound(i) )
+         {
+             const Qfloat *Q_i = CvSVMSolver::get_row( i, buf[0]);
+             double alpha_i = alpha[i];
+             for( j = 0; j < alpha_count; j++ )
+             {
+                 G[j] += alpha_i * Q_i[j];
+             }
+         }
+     }
+     // 2. optimization loop
+     for(;;)
+     {
+         const Qfloat *Q_i, *Q_j;
+         double C_i, C_j;
+         double old_alpha_i, old_alpha_j, alpha_i, alpha_j;
+         double delta_alpha_i, delta_alpha_j;
+ #ifdef _DEBUG
+         for( i = 0; i < alpha_count; i++ )
+         {
+             if( fabs(G[i]) > 1e+300 )
+             {
+                 return false;
+             }
+             if( fabs(alpha[i]) > 1e16 )
+             {
+                 return false;
+             }
+         }
+ #endif
+         if( (this->*select_working_set_func)( i, j ) != 0 || iter++ >= max_iter )
+         {
+             break;
+         }
+         Q_i = get_row( i, buf[0], dst1);
+         Q_j = get_row( j, buf[1], dst1);
+         C_i = get_C(i);
+         C_j = get_C(j);
+         alpha_i = old_alpha_i = alpha[i];
+         alpha_j = old_alpha_j = alpha[j];
+         if( y[i] != y[j] )
+         {
+             double denom = Q_i[i] + Q_j[j] + 2 * Q_i[j];
+             double delta = (-G[i] - G[j]) / MAX(fabs(denom), FLT_EPSILON);
+             double diff = alpha_i - alpha_j;
+             alpha_i += delta;
+             alpha_j += delta;
+             if( diff > 0 && alpha_j < 0 )
+             {
+                 alpha_j = 0;
+                 alpha_i = diff;
+             }
+             else if( diff <= 0 && alpha_i < 0 )
+             {
+                 alpha_i = 0;
+                 alpha_j = -diff;
+             }
+             if( diff > C_i - C_j && alpha_i > C_i )
+             {
+                 alpha_i = C_i;
+                 alpha_j = C_i - diff;
+             }
+             else if( diff <= C_i - C_j && alpha_j > C_j )
+             {
+                 alpha_j = C_j;
+                 alpha_i = C_j + diff;
+             }
+         }
+         else
+         {
+             double denom = Q_i[i] + Q_j[j] - 2 * Q_i[j];
+             double delta = (G[i] - G[j]) / MAX(fabs(denom), FLT_EPSILON);
+             double sum = alpha_i + alpha_j;
+             alpha_i -= delta;
+             alpha_j += delta;
+             if( sum > C_i && alpha_i > C_i )
+             {
+                 alpha_i = C_i;
+                 alpha_j = sum - C_i;
+             }
+             else if( sum <= C_i && alpha_j < 0)
+             {
+                 alpha_j = 0;
+                 alpha_i = sum;
+             }
+             if( sum > C_j && alpha_j > C_j )
+             {
+                 alpha_j = C_j;
+                 alpha_i = sum - C_j;
+             }
+             else if( sum <= C_j && alpha_i < 0 )
+             {
+                 alpha_i = 0;
+                 alpha_j = sum;
+             }
+         }
+         // update alpha
+         alpha[i] = alpha_i;
+         alpha[j] = alpha_j;
+         update_alpha_status(i);
+         update_alpha_status(j);
+         // update G
+         delta_alpha_i = alpha_i - old_alpha_i;
+         delta_alpha_j = alpha_j - old_alpha_j;
+         for( k = 0; k < alpha_count; k++ )
+         {
+             G[k] += Q_i[k] * delta_alpha_i + Q_j[k] * delta_alpha_j;
+         }
+     }
+     // calculate rho
+     (this->*calc_rho_func)( si.rho, si.r );
+     // calculate objective value
+     for( i = 0, si.obj = 0; i < alpha_count; i++ )
+     {
+         si.obj += alpha[i] * (G[i] + b[i]);
+     }
+     si.obj *= 0.5;
+     si.upper_bound_p = C[1];
+     si.upper_bound_n = C[0];
+     return true;
+ }
+ void CvSVMKernel_ocl::calc( int vcount, const int row_idx, Qfloat* results, Mat& src)
+ {
+     //const Qfloat max_val = (Qfloat)(FLT_MAX*1e-3);
+     //int j;
+     (this->*calc_func_ocl)( vcount, row_idx, results, src);
+ #if defined HAVE_CLAMDBLAS
+     const Qfloat max_val = (Qfloat)(FLT_MAX * 1e-3);
+     int j;
+     for( j = 0; j < vcount; j++ )
+     {
+         if( results[j] > max_val )
+         {
+             results[j] = max_val;
+         }
+     }
+ #endif
+ }
+ bool CvSVMKernel_ocl::create( const CvSVMParams* _params, Calc_ocl _calc_func, Calc _calc_func1 )
+ {
+     clear();
+     params = _params;
+     calc_func_ocl = _calc_func;
+     calc_func = _calc_func1;
+     if( !calc_func_ocl )
+         calc_func_ocl = params->kernel_type == CvSVM::RBF ? &CvSVMKernel_ocl::calc_rbf :
+                         params->kernel_type == CvSVM::POLY ? &CvSVMKernel_ocl::calc_poly :
+                         params->kernel_type == CvSVM::SIGMOID ? &CvSVMKernel_ocl::calc_sigmoid :
+                         &CvSVMKernel_ocl::calc_linear;
+     if( !calc_func)
+         calc_func = params->kernel_type == CvSVM::RBF ? &CvSVMKernel::calc_rbf :
+                     params->kernel_type == CvSVM::POLY ? &CvSVMKernel::calc_poly :
+                     params->kernel_type == CvSVM::SIGMOID ? &CvSVMKernel::calc_sigmoid :
+                     &CvSVMKernel::calc_linear;
+     return true;
+ }
+ CvSVMKernel_ocl::CvSVMKernel_ocl(const CvSVMParams* params, CvSVMKernel_ocl::Calc_ocl _calc_func, CvSVMKernel::Calc _calc_func1)
+ {
+     CvSVMKernel::clear();
+     CvSVMKernel_ocl::create( params, _calc_func, _calc_func1 );
+ }
+ void CvSVMKernel_ocl::calc_non_rbf_base( int vcount, const int row_idx, Qfloat* results, Mat& src)
+ {
+ #if defined HAVE_CLAMDBLAS
+     for(int i = 0; i < vcount; i++)
+     {
+         results[i] = (Qfloat) * src.ptr<float>(row_idx, i);
+     }
+ #else
+     if(!Context::getContext()->supportsFeature(Context::CL_DOUBLE))
+     {
+         for(int i = 0; i < vcount; i++)
+         {
+             results[i] = (Qfloat) * src.ptr<float>(row_idx, i);
+         }
+     }
+     else
+     {
+         for(int i = 0; i < vcount; i++)
+         {
+             results[i] = (Qfloat) * src.ptr<double>(row_idx, i);
+         }
+     }
+ #endif
+ }
+ void CvSVMKernel_ocl::calc_rbf( int vcount, const int row_idx, Qfloat* results, Mat& src)
+ {
+     if(!Context::getContext()->supportsFeature(Context::CL_DOUBLE))
+     {
+         for(int m = 0; m < vcount; m++)
+         {
+             results[m] = (Qfloat) * src.ptr<float>(row_idx, m);
+         }
+     }
+     else
+     {
+         for(int m = 0; m < vcount; m++)
+         {
+             results[m] = (Qfloat) * src.ptr<double>(row_idx, m);
+         }
+     }
+ }
+ void CvSVMKernel_ocl::calc_linear( int vcount, const int row_idx, Qfloat* results, Mat& src )
+ {
+     calc_non_rbf_base( vcount, row_idx, results, src);
+ }
+ void CvSVMKernel_ocl::calc_poly( int vcount, const int row_idx, Qfloat* results, Mat& src)
+ {
+     calc_non_rbf_base( vcount, row_idx, results, src);
+ #if defined HAVE_CLAMDBLAS
+     CvMat R = cvMat( 1, vcount, QFLOAT_TYPE, results );
+     if( vcount > 0 )
+     {
+         cvPow( &R, &R, params->degree );
+     }
+ #endif
+ }
+ void CvSVMKernel_ocl::calc_sigmoid( int vcount, const int row_idx, Qfloat* results, Mat& src)
+ {
+     calc_non_rbf_base( vcount, row_idx, results, src);
+     // TODO: speedup this
+ #if defined HAVE_CLAMDBLAS
+     for(int j = 0; j < vcount; j++ )
+     {
+         Qfloat t = results[j];
+         double e = exp(-fabs(t));
+         if( t > 0 )
+         {
+             results[j] = (Qfloat)((1. - e) / (1. + e));
+         }
+         else
+         {
+             results[j] = (Qfloat)((e - 1.) / (e + 1.));
+         }
+     }
+ #endif
+ }
+ CvSVM_OCL::CvSVM_OCL()
+ {
+     CvSVM();
+ }
+ CvSVM_OCL::CvSVM_OCL( const Mat& _train_data, const Mat& _responses,
+                       const Mat& _var_idx, const Mat& _sample_idx, CvSVMParams _params )
+ {
+     decision_func = 0;
+     class_labels = 0;
+     class_weights = 0;
+     storage = 0;
+     var_idx = 0;
+     kernel = 0;
+     solver = 0;
+     default_model_name = "my_svm";
+     train( _train_data, _responses, _var_idx, _sample_idx, _params );
+ }
+ void CvSVM_OCL::create_kernel()
+ {
+     kernel = new CvSVMKernel_ocl(&params, 0, 0);
+ }
+ void CvSVM_OCL::create_solver( )
+ {
+     solver = new CvSVMSolver_ocl(&params);
+ }
@@@ -292,15 -292,15 +292,15 @@@ void ocl_tvl1flow::centeredGradient(con
      int dElememntSize = dx.elemSize();
      int dx_step = dx.step/dElememntSize;
  
 -    string kernelName = "centeredGradientKernel";
 -    vector< pair<size_t, const void *> > args;
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&src.data));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&src.cols));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&src.rows));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&src_step));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&dx.data));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&dy.data));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&dx_step));
 +    String kernelName = "centeredGradientKernel";
-     vector< pair<size_t, const void *> > args;
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&src.data));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&src.cols));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&src.rows));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&src_step));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&dx.data));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&dy.data));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&dx_step));
++    std::vector< std::pair<size_t, const void *> > args;
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&src.data));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&src.cols));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&src.rows));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&src_step));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&dx.data));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&dy.data));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&dx_step));
      openCLExecuteKernel(clCxt, &tvl1flow, kernelName, globalThreads, localThreads, args, -1, -1);
  
  }
@@@ -334,24 -334,24 +334,24 @@@ void ocl_tvl1flow::estimateDualVariable
      int u2_offset_x = u2.offset%u2.step;
      u2_offset_x = u2_offset_x/u2.elemSize();
  
 -    string kernelName = "estimateDualVariablesKernel";
 -    vector< pair<size_t, const void *> > args;
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&u1.data));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&u1.cols));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&u1.rows));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&u1_step));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&u2.data));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&p11.data));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&p11_step));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&p12.data));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&p21.data));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&p22.data));
 -    args.push_back( make_pair( sizeof(cl_float), (void*)&taut));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&u2_step));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&u1_offset_x));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&u1_offset_y));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&u2_offset_x));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&u2_offset_y));
 +    String kernelName = "estimateDualVariablesKernel";
-     vector< pair<size_t, const void *> > args;
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&u1.data));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&u1.cols));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&u1.rows));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&u1_step));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&u2.data));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&p11.data));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&p11_step));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&p12.data));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&p21.data));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&p22.data));
-     args.push_back( make_pair( sizeof(cl_float), (void*)&taut));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&u2_step));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&u1_offset_x));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&u1_offset_y));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&u2_offset_x));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&u2_offset_y));
++    std::vector< std::pair<size_t, const void *> > args;
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&u1.data));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&u1.cols));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&u1.rows));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&u1_step));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&u2.data));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&p11.data));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&p11_step));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&p12.data));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&p21.data));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&p22.data));
++    args.push_back( std::make_pair( sizeof(cl_float), (void*)&taut));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&u2_step));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&u1_offset_x));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&u1_offset_y));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&u2_offset_x));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&u2_offset_y));
  
      openCLExecuteKernel(clCxt, &tvl1flow, kernelName, globalThread, localThread, args, -1, -1);
  }
@@@ -388,31 -388,31 +388,31 @@@ void ocl_tvl1flow::estimateU(oclMat &I1
      int u2_offset_x = u2.offset%u2.step;
      u2_offset_x = u2_offset_x/u2.elemSize();
  
 -    string kernelName = "estimateUKernel";
 -    vector< pair<size_t, const void *> > args;
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&I1wx.data));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&I1wx.cols));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&I1wx.rows));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&I1wx_step));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&I1wy.data));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&grad.data));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&rho_c.data));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&p11.data));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&p12.data));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&p21.data));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&p22.data));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&u1.data));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&u1_step));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&u2.data));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&error.data));
 -    args.push_back( make_pair( sizeof(cl_float), (void*)&l_t));
 -    args.push_back( make_pair( sizeof(cl_float), (void*)&theta));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&u2_step));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&u1_offset_x));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&u1_offset_y));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&u2_offset_x));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&u2_offset_y));
 -    args.push_back( make_pair( sizeof(cl_char), (void*)&calc_error));
 +    String kernelName = "estimateUKernel";
-     vector< pair<size_t, const void *> > args;
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&I1wx.data));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&I1wx.cols));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&I1wx.rows));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&I1wx_step));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&I1wy.data));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&grad.data));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&rho_c.data));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&p11.data));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&p12.data));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&p21.data));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&p22.data));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&u1.data));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&u1_step));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&u2.data));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&error.data));
-     args.push_back( make_pair( sizeof(cl_float), (void*)&l_t));
-     args.push_back( make_pair( sizeof(cl_float), (void*)&theta));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&u2_step));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&u1_offset_x));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&u1_offset_y));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&u2_offset_x));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&u2_offset_y));
-     args.push_back( make_pair( sizeof(cl_char), (void*)&calc_error));
++    std::vector< std::pair<size_t, const void *> > args;
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&I1wx.data));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&I1wx.cols));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&I1wx.rows));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&I1wx_step));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&I1wy.data));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&grad.data));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&rho_c.data));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&p11.data));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&p12.data));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&p21.data));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&p22.data));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&u1.data));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&u1_step));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&u2.data));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&error.data));
++    args.push_back( std::make_pair( sizeof(cl_float), (void*)&l_t));
++    args.push_back( std::make_pair( sizeof(cl_float), (void*)&theta));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&u2_step));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&u1_offset_x));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&u1_offset_y));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&u2_offset_x));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&u2_offset_y));
++    args.push_back( std::make_pair( sizeof(cl_char), (void*)&calc_error));
  
      openCLExecuteKernel(clCxt, &tvl1flow, kernelName, globalThread, localThread, args, -1, -1);
  }
@@@ -459,29 -459,29 +459,29 @@@ void ocl_tvl1flow::warpBackward(const o
      I1x_tex = bindTexture(I1x);
      I1y_tex = bindTexture(I1y);
  
 -    string kernelName = "warpBackwardKernel";
 -    vector< pair<size_t, const void *> > args;
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&I0.data));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&I0Step));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&I0.cols));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&I0.rows));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&I1_tex));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&I1x_tex));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&I1y_tex));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&u1.data));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&u1Step));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&u2.data));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&I1w.data));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&I1wx.data));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&I1wy.data));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&grad.data));
 -    args.push_back( make_pair( sizeof(cl_mem), (void*)&rho.data));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&I1w_step));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&u2Step));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&u1_offset_x));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&u1_offset_y));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&u2_offset_x));
 -    args.push_back( make_pair( sizeof(cl_int), (void*)&u2_offset_y));
 +    String kernelName = "warpBackwardKernel";
-     vector< pair<size_t, const void *> > args;
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&I0.data));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&I0Step));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&I0.cols));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&I0.rows));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&I1_tex));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&I1x_tex));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&I1y_tex));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&u1.data));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&u1Step));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&u2.data));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&I1w.data));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&I1wx.data));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&I1wy.data));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&grad.data));
-     args.push_back( make_pair( sizeof(cl_mem), (void*)&rho.data));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&I1w_step));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&u2Step));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&u1_offset_x));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&u1_offset_y));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&u2_offset_x));
-     args.push_back( make_pair( sizeof(cl_int), (void*)&u2_offset_y));
++    std::vector< std::pair<size_t, const void *> > args;
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&I0.data));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&I0Step));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&I0.cols));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&I0.rows));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&I1_tex));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&I1x_tex));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&I1y_tex));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&u1.data));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&u1Step));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&u2.data));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&I1w.data));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&I1wx.data));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&I1wy.data));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&grad.data));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void*)&rho.data));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&I1w_step));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&u2Step));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&u1_offset_x));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&u1_offset_y));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&u2_offset_x));
++    args.push_back( std::make_pair( sizeof(cl_int), (void*)&u2_offset_y));
  
      openCLExecuteKernel(clCxt, &tvl1flow, kernelName, globalThread, localThread, args, -1, -1);
  
Simple merge
Simple merge
  #include <iterator>
  #include <string>
  #include <cstdarg>
 -#include "cvconfig.h"
 -#include "opencv2/core/core.hpp"
 -#include "opencv2/highgui/highgui.hpp"
 -//#include "opencv2/calib3d/calib3d.hpp"
 -#include "opencv2/imgproc/imgproc.hpp"
 -#include "opencv2/video/video.hpp"
 -#include "opencv2/ts/ts.hpp"
 -#include "opencv2/ocl/ocl.hpp"
 +#include "opencv2/ts.hpp"
 +#include "opencv2/highgui.hpp"
 +#include "opencv2/imgproc.hpp"
++#include "opencv2/features2d.hpp"
 +#include "opencv2/video.hpp"
 +#include "opencv2/ocl.hpp"
  
  #include "utility.hpp"
 -//#include "add_test_info.h"
 +
 +#include "opencv2/core/private.hpp"
  
  #endif
  
  #ifndef __OPENCV_TEST_UTILITY_HPP__
  #define __OPENCV_TEST_UTILITY_HPP__
 +#include "opencv2/core.hpp"
 +
  #define LOOP_TIMES 1
  #define MWIDTH 256
  #define MHEIGHT 256
+ #define MIN_VALUE 171
+ #define MAX_VALUE 357
  //#define RANDOMROI
  int randomInt(int minVal, int maxVal);
  double randomDouble(double minVal, double maxVal);
Simple merge