Merge remote-tracking branch 'origin/2.4' into merge-2.4
authorRoman Donchenko <roman.donchenko@itseez.com>
Mon, 13 Jan 2014 15:28:43 +0000 (19:28 +0400)
committerRoman Donchenko <roman.donchenko@itseez.com>
Tue, 14 Jan 2014 07:53:59 +0000 (11:53 +0400)
Conflicts:
modules/contrib/src/retina.cpp
modules/core/include/opencv2/core/mat.hpp
modules/core/src/algorithm.cpp
modules/core/src/arithm.cpp
modules/features2d/src/features2d_init.cpp
modules/gpu/include/opencv2/gpu/gpu.hpp
modules/gpu/perf/perf_imgproc.cpp
modules/imgproc/src/generalized_hough.cpp
modules/ocl/include/opencv2/ocl/ocl.hpp
modules/video/src/tvl1flow.cpp
modules/video/src/video_init.cpp

44 files changed:
1  2 
.gitignore
apps/haartraining/cvclassifier.h
modules/bioinspired/src/retina.cpp
modules/calib3d/test/test_chessboardgenerator.hpp
modules/contrib/src/adaptiveskindetector.cpp
modules/contrib/src/ba.cpp
modules/contrib/src/facerec.cpp
modules/contrib/src/fuzzymeanshifttracker.cpp
modules/contrib/src/spinimages.cpp
modules/core/include/opencv2/core/mat.inl.hpp
modules/core/src/algorithm.cpp
modules/core/src/arithm.cpp
modules/core/src/convert.cpp
modules/core/src/copy.cpp
modules/core/src/precomp.hpp
modules/core/src/system.cpp
modules/core/test/test_arithm.cpp
modules/cudaimgproc/perf/perf_match_template.cpp
modules/features2d/src/features2d_init.cpp
modules/flann/include/opencv2/flann/hierarchical_clustering_index.h
modules/highgui/src/bitstrm.hpp
modules/highgui/src/cap_ffmpeg_impl.hpp
modules/highgui/src/precomp.hpp
modules/highgui/src/window_w32.cpp
modules/imgproc/perf/perf_filter2d.cpp
modules/imgproc/src/gcgraph.hpp
modules/imgproc/src/imgwarp.cpp
modules/legacy/src/vecfacetracking.cpp
modules/ml/src/ml_init.cpp
modules/nonfree/src/nonfree_init.cpp
modules/ocl/include/opencv2/ocl.hpp
modules/ocl/include/opencv2/ocl/private/opencl_utils.hpp
modules/ocl/test/test_objdetect.cpp
modules/ocl/test/utility.hpp
modules/superres/src/btv_l1.cpp
modules/superres/src/btv_l1_ocl.cpp
modules/superres/src/optical_flow.cpp
modules/ts/include/opencv2/ts/ts_perf.hpp
modules/video/perf/perf_optflowpyrlk.cpp
modules/video/src/kalman.cpp
modules/video/src/tvl1flow.cpp
samples/c/adaptiveskindetector.cpp
samples/cpp/calibration_artificial.cpp
samples/cpp/kmeans.cpp

diff --cc .gitignore
Simple merge
Simple merge
index d2193ea,0000000..303a7f3
mode 100644,000000..100644
--- /dev/null
@@@ -1,743 -1,0 +1,743 @@@
- };
 +/*#******************************************************************************
 + ** IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
 + **
 + ** By downloading, copying, installing or using the software you agree to this license.
 + ** If you do not agree to this license, do not download, install,
 + ** copy or use the software.
 + **
 + **
 + ** bioinspired : interfaces allowing OpenCV users to integrate Human Vision System models. Presented models originate from Jeanny Herault's original research and have been reused and adapted by the author&collaborators for computed vision applications since his thesis with Alice Caplier at Gipsa-Lab.
 + ** Use: extract still images & image sequences features, from contours details to motion spatio-temporal features, etc. for high level visual scene analysis. Also contribute to image enhancement/compression such as tone mapping.
 + **
 + ** Maintainers : Listic lab (code author current affiliation & applications) and Gipsa Lab (original research origins & applications)
 + **
 + **  Creation - enhancement process 2007-2011
 + **      Author: Alexandre Benoit (benoit.alexandre.vision@gmail.com), LISTIC lab, Annecy le vieux, France
 + **
 + ** Theses algorithm have been developped by Alexandre BENOIT since his thesis with Alice Caplier at Gipsa-Lab (www.gipsa-lab.inpg.fr) and the research he pursues at LISTIC Lab (www.listic.univ-savoie.fr).
 + ** Refer to the following research paper for more information:
 + ** Benoit A., Caplier A., Durette B., Herault, J., "USING HUMAN VISUAL SYSTEM MODELING FOR BIO-INSPIRED LOW LEVEL IMAGE PROCESSING", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773, DOI: http://dx.doi.org/10.1016/j.cviu.2010.01.011
 + ** This work have been carried out thanks to Jeanny Herault who's research and great discussions are the basis of all this work, please take a look at his book:
 + ** Vision: Images, Signals and Neural Networks: Models of Neural Processing in Visual Perception (Progress in Neural Processing),By: Jeanny Herault, ISBN: 9814273686. WAPI (Tower ID): 113266891.
 + **
 + ** The retina filter 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 color mosaicing/demosaicing and the reference paper:
 + ** ====> 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.
 + **
 + **                          License Agreement
 + **               For Open Source Computer Vision Library
 + **
 + ** Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
 + ** Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved.
 + **
 + **               For Human Visual System tools (bioinspired)
 + ** Copyright (C) 2007-2011, LISTIC Lab, Annecy le Vieux and GIPSA Lab, Grenoble, France, all rights reserved.
 + **
 + ** Third party copyrights are property of their respective owners.
 + **
 + ** Redistribution and use in source and binary forms, with or without modification,
 + ** are permitted provided that the following conditions are met:
 + **
 + ** * Redistributions of source code must retain the above copyright notice,
 + **    this list of conditions and the following disclaimer.
 + **
 + ** * Redistributions in binary form must reproduce the above copyright notice,
 + **    this list of conditions and the following disclaimer in the documentation
 + **    and/or other materials provided with the distribution.
 + **
 + ** * The name of the copyright holders may not be used to endorse or promote products
 + **    derived from this software without specific prior written permission.
 + **
 + ** This software is provided by the copyright holders and contributors "as is" and
 + ** any express or implied warranties, including, but not limited to, the implied
 + ** warranties of merchantability and fitness for a particular purpose are disclaimed.
 + ** In no event shall the Intel Corporation or contributors be liable for any direct,
 + ** indirect, incidental, special, exemplary, or consequential damages
 + ** (including, but not limited to, procurement of substitute goods or services;
 + ** loss of use, data, or profits; or business interruption) however caused
 + ** and on any theory of liability, whether in contract, strict liability,
 + ** or tort (including negligence or otherwise) arising in any way out of
 + ** the use of this software, even if advised of the possibility of such damage.
 + *******************************************************************************/
 +
 +/*
 + * Retina.cpp
 + *
 + *  Created on: Jul 19, 2011
 + *      Author: Alexandre Benoit
 + */
 +#include "precomp.hpp"
 +#include "retinafilter.hpp"
 +#include <cstdio>
 +#include <sstream>
 +#include <valarray>
 +
 +namespace cv
 +{
 +namespace bioinspired
 +{
 +
 +class RetinaImpl : public Retina
 +{
 +public:
 +    /**
 +     * Main constructor with most commun use setup : create an instance of color ready retina model
 +     * @param inputSize : the input frame size
 +     */
 +    RetinaImpl(Size inputSize);
 +
 +    /**
 +     * Complete Retina filter constructor which allows all basic structural parameters definition
 +         * @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
 +     * @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
 +     */
 +    RetinaImpl(Size inputSize, const bool colorMode, int colorSamplingMethod=RETINA_COLOR_BAYER, const bool useRetinaLogSampling=false, const double reductionFactor=1.0, const double samplingStrenght=10.0);
 +
 +    virtual ~RetinaImpl();
 +    /**
 +        * retreive retina input buffer size
 +        */
 +        Size getInputSize();
 +
 +    /**
 +        * retreive retina output buffer size
 +        */
 +        Size getOutputSize();
 +
 +    /**
 +     * 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
 +     */
 +    void setup(String retinaParameterFile="", const bool applyDefaultSetupOnFailure=true);
 +
 +
 +    /**
 +     * 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 fs : the open Filestorage which contains retina parameters
 +         * @param applyDefaultSetupOnFailure : set to true if an error must be thrown on error
 +     */
 +        void setup(cv::FileStorage &fs, const bool applyDefaultSetupOnFailure=true);
 +
 +    /**
 +     * 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 newParameters : a parameters structures updated with the new target configuration
 +         * @param applyDefaultSetupOnFailure : set to true if an error must be thrown on error
 +     */
 +    void setup(Retina::RetinaParameters newParameters);
 +
 +    /**
 +    * @return the current parameters setup
 +    */
 +    struct Retina::RetinaParameters getParameters();
 +
 +    /**
 +     * parameters setup display method
 +     * @return a string which contains formatted parameters information
 +     */
 +    const String printSetup();
 +
 +    /**
 +     * write xml/yml formated parameters information
 +     * @rparam fs : the filename of the xml file that will be open and writen with formatted parameters information
 +     */
 +    virtual void write( String fs ) const;
 +
 +
 +    /**
 +     * write xml/yml formated parameters information
 +     * @param fs : a cv::Filestorage object ready to be filled
 +         */
 +    virtual void write( FileStorage& fs ) const;
 +
 +    /**
 +     * 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 Inner Plexiform layer of the retina, it allows high contours sensitivity in foveal vision.
 +     * for more informations, please have a look at the 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
 +     * @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 160 and 250 for best results, a high value increases more the low value sensitivity... and the output saturates faster, recommended value: 230
 +     */
 +    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);
 +
 +    /**
 +     * set parameters values for the Inner Plexiform Layer (IPL) magnocellular channel
 +     * this channel processes signals outpint from OPL processing stage in peripheral vision, it allows motion information enhancement. It is decorrelated from the details channel. See reference paper 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, tipicall value is 5
 +     * @param V0CompressionParameter: the compression strengh of the ganglion cells local adaptation output, set a value between 160 and 250 for best results, a high value increases more the low value sensitivity... and the output saturates faster, recommended value: 200
 +     * @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
 +     */
 +    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);
 +
 +    /**
 +     * 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 cv::Mat image to be processed, can be gray level or BGR coded in any format (from 8bit to 16bits)
 +     */
 +    void run(InputArray inputImage);
 +
 +    /**
 +     * method that applies a luminance correction (initially High Dynamic Range (HDR) tone mapping) using only the 2 local adaptation stages of the retina parvo channel : photoreceptors level and ganlion cells level. Spatio temporal filtering is applied but limited to temporal smoothing and eventually high frequencies attenuation. This is a lighter method than the one available using the regular run method. It is then faster but it does not include complete temporal filtering nor retina spectral whitening. This is an adptation of the original still image HDR tone mapping algorithm of David Alleyson, Sabine Susstruck and Laurence Meylan's work, please cite:
 +    * -> Meylan L., Alleysson D., and Susstrunk S., A Model of Retinal Local Adaptation for the Tone Mapping of Color Filter Array Images, Journal of Optical Society of America, A, Vol. 24, N 9, September, 1st, 2007, pp. 2807-2816
 +     @param inputImage the input image to process RGB or gray levels
 +     @param outputToneMappedImage the output tone mapped image
 +     */
 +    void applyFastToneMapping(InputArray inputImage, OutputArray outputToneMappedImage);
 +
 +    /**
 +     * accessor of the details channel of the retina (models foveal vision)
 +     * @param retinaOutput_parvo : the output buffer (reallocated if necessary), this output is rescaled for standard 8bits image processing use in OpenCV
 +     */
 +    void getParvo(OutputArray retinaOutput_parvo);
 +
 +    /**
 +     * accessor of the details channel of the retina (models foveal vision)
 +     * @param retinaOutput_parvo : a cv::Mat header filled with the internal parvo buffer of the retina module. This output is the original retina filter model output, without any quantification or rescaling
 +     */
 +    void getParvoRAW(OutputArray retinaOutput_parvo);
 +
 +    /**
 +     * accessor of the motion channel of the retina (models peripheral vision)
 +     * @param retinaOutput_magno : the output buffer (reallocated if necessary), this output is rescaled for standard 8bits image processing use in OpenCV
 +     */
 +    void getMagno(OutputArray retinaOutput_magno);
 +
 +    /**
 +     * accessor of the motion channel of the retina (models peripheral vision)
 +     * @param retinaOutput_magno : a cv::Mat header filled with the internal retina magno buffer of the retina module. This output is the original retina filter model output, without any quantification or rescaling
 +     */
 +    void getMagnoRAW(OutputArray retinaOutput_magno);
 +
 +    // original API level data accessors : get buffers addresses from a Mat header, similar to getParvoRAW and getMagnoRAW...
 +    const Mat getMagnoRAW() const;
 +    const Mat getParvoRAW() const;
 +
 +    /**
 +     * 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
 +     */
 +    void setColorSaturation(const bool saturateColors=true, const float colorSaturationValue=4.0);
 +
 +    /**
 +     * clear all retina buffers (equivalent to opening the eyes after a long period of eye close ;o)
 +     */
 +    void clearBuffers();
 +
 +        /**
 +        * 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
 +        */
 +        void activateMovingContoursProcessing(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
 +        */
 +        void activateContoursProcessing(const bool activate);
 +private:
 +
 +    // Parameteres setup members
 +    RetinaParameters _retinaParameters; // structure of parameters
 +
 +    // Retina model related modules
 +    std::valarray<float> _inputBuffer; //!< buffer used to convert input cv::Mat to internal retina buffers format (valarrays)
 +
 +    // pointer to retina model
 +    RetinaFilter* _retinaFilter; //!< the pointer to the retina module, allocated with instance construction
 +
 +    //! private method called by constructors, gathers their parameters and use them in a unified way
 +    void _init(const Size inputSize, const bool colorMode, int colorSamplingMethod=RETINA_COLOR_BAYER, const bool useRetinaLogSampling=false, const double reductionFactor=1.0, const double samplingStrenght=10.0);
 +
 +    /**
 +     * exports a valarray buffer outing from bioinspired objects to a cv::Mat in CV_8UC1 (gray level picture) or CV_8UC3 (color) format
 +     * @param grayMatrixToConvert the valarray to export to OpenCV
 +     * @param nbRows : the number of rows of the valarray flatten matrix
 +     * @param nbColumns : the number of rows of the valarray flatten matrix
 +     * @param colorMode : a flag which mentions if matrix is color (true) or graylevel (false)
 +     * @param outBuffer : the output matrix which is reallocated to satisfy Retina output buffer dimensions
 +     */
 +    void _convertValarrayBuffer2cvMat(const std::valarray<float> &grayMatrixToConvert, const unsigned int nbRows, const unsigned int nbColumns, const bool colorMode, OutputArray outBuffer);
 +
 +    /**
 +     * convert a cv::Mat to a valarray buffer in float format
 +     * @param inputMatToConvert : the OpenCV cv::Mat that has to be converted to gray or RGB valarray buffer that will be processed by the retina model
 +     * @param outputValarrayMatrix : the output valarray
 +     * @return the input image color mode (color=true, gray levels=false)
 +     */
 +    bool _convertCvMat2ValarrayBuffer(InputArray inputMatToConvert, std::valarray<float> &outputValarrayMatrix);
 +
 +
 +};
 +
 +// smart pointers allocation :
 +Ptr<Retina> createRetina(Size inputSize){ return makePtr<RetinaImpl>(inputSize); }
 +Ptr<Retina> createRetina(Size inputSize, const bool colorMode, int colorSamplingMethod, const bool useRetinaLogSampling, const double reductionFactor, const double samplingStrenght){
 +    return makePtr<RetinaImpl>(inputSize, colorMode, colorSamplingMethod, useRetinaLogSampling, reductionFactor, samplingStrenght);
 +}
 +
 +
 +// RetinaImpl code
 +RetinaImpl::RetinaImpl(const cv::Size inputSz)
 +{
 +    _retinaFilter = 0;
 +    _init(inputSz, true, RETINA_COLOR_BAYER, false);
 +}
 +
 +RetinaImpl::RetinaImpl(const cv::Size inputSz, const bool colorMode, int colorSamplingMethod, const bool useRetinaLogSampling, const double reductionFactor, const double samplingStrenght)
 +{
 +    _retinaFilter = 0;
 +    _init(inputSz, colorMode, colorSamplingMethod, useRetinaLogSampling, reductionFactor, samplingStrenght);
++}
 +
 +RetinaImpl::~RetinaImpl()
 +{
 +    if (_retinaFilter)
 +        delete _retinaFilter;
 +}
 +
 +/**
 +* retreive retina input buffer size
 +*/
 +Size RetinaImpl::getInputSize(){return cv::Size(_retinaFilter->getInputNBcolumns(), _retinaFilter->getInputNBrows());}
 +
 +/**
 +* retreive retina output buffer size
 +*/
 +Size RetinaImpl::getOutputSize(){return cv::Size(_retinaFilter->getOutputNBcolumns(), _retinaFilter->getOutputNBrows());}
 +
 +
 +void RetinaImpl::setColorSaturation(const bool saturateColors, const float colorSaturationValue)
 +{
 +    _retinaFilter->setColorSaturation(saturateColors, colorSaturationValue);
 +}
 +
 +struct Retina::RetinaParameters RetinaImpl::getParameters(){return _retinaParameters;}
 +
 +void RetinaImpl::setup(String retinaParameterFile, const bool applyDefaultSetupOnFailure)
 +{
 +    try
 +    {
 +        // opening retinaParameterFile in read mode
 +        cv::FileStorage fs(retinaParameterFile, cv::FileStorage::READ);
 +        setup(fs, applyDefaultSetupOnFailure);
 +    }
 +    catch(Exception &e)
 +    {
 +        printf("Retina::setup: wrong/unappropriate xml parameter file : error report :`n=>%s\n", e.what());
 +        if (applyDefaultSetupOnFailure)
 +        {
 +            printf("Retina::setup: resetting retina with default parameters\n");
 +            setupOPLandIPLParvoChannel();
 +            setupIPLMagnoChannel();
 +        }
 +        else
 +        {
 +            printf("=> keeping current parameters\n");
 +        }
 +    }
 +}
 +
 +void RetinaImpl::setup(cv::FileStorage &fs, const bool applyDefaultSetupOnFailure)
 +{
 +    try
 +    {
 +        // read parameters file if it exists or apply default setup if asked for
 +        if (!fs.isOpened())
 +        {
 +            printf("Retina::setup: provided parameters file could not be open... skeeping configuration\n");
 +            return;
 +            // implicit else case : retinaParameterFile could be open (it exists at least)
 +        }
 +                // OPL and Parvo init first... update at the same time the parameters structure and the retina core
 +        cv::FileNode rootFn = fs.root(), currFn=rootFn["OPLandIPLparvo"];
 +        currFn["colorMode"]>>_retinaParameters.OPLandIplParvo.colorMode;
 +        currFn["normaliseOutput"]>>_retinaParameters.OPLandIplParvo.normaliseOutput;
 +        currFn["photoreceptorsLocalAdaptationSensitivity"]>>_retinaParameters.OPLandIplParvo.photoreceptorsLocalAdaptationSensitivity;
 +        currFn["photoreceptorsTemporalConstant"]>>_retinaParameters.OPLandIplParvo.photoreceptorsTemporalConstant;
 +        currFn["photoreceptorsSpatialConstant"]>>_retinaParameters.OPLandIplParvo.photoreceptorsSpatialConstant;
 +        currFn["horizontalCellsGain"]>>_retinaParameters.OPLandIplParvo.horizontalCellsGain;
 +        currFn["hcellsTemporalConstant"]>>_retinaParameters.OPLandIplParvo.hcellsTemporalConstant;
 +        currFn["hcellsSpatialConstant"]>>_retinaParameters.OPLandIplParvo.hcellsSpatialConstant;
 +        currFn["ganglionCellsSensitivity"]>>_retinaParameters.OPLandIplParvo.ganglionCellsSensitivity;
 +        setupOPLandIPLParvoChannel(_retinaParameters.OPLandIplParvo.colorMode, _retinaParameters.OPLandIplParvo.normaliseOutput, _retinaParameters.OPLandIplParvo.photoreceptorsLocalAdaptationSensitivity, _retinaParameters.OPLandIplParvo.photoreceptorsTemporalConstant, _retinaParameters.OPLandIplParvo.photoreceptorsSpatialConstant, _retinaParameters.OPLandIplParvo.horizontalCellsGain, _retinaParameters.OPLandIplParvo.hcellsTemporalConstant, _retinaParameters.OPLandIplParvo.hcellsSpatialConstant, _retinaParameters.OPLandIplParvo.ganglionCellsSensitivity);
 +
 +        // init retina IPL magno setup... update at the same time the parameters structure and the retina core
 +        currFn=rootFn["IPLmagno"];
 +        currFn["normaliseOutput"]>>_retinaParameters.IplMagno.normaliseOutput;
 +        currFn["parasolCells_beta"]>>_retinaParameters.IplMagno.parasolCells_beta;
 +        currFn["parasolCells_tau"]>>_retinaParameters.IplMagno.parasolCells_tau;
 +        currFn["parasolCells_k"]>>_retinaParameters.IplMagno.parasolCells_k;
 +        currFn["amacrinCellsTemporalCutFrequency"]>>_retinaParameters.IplMagno.amacrinCellsTemporalCutFrequency;
 +        currFn["V0CompressionParameter"]>>_retinaParameters.IplMagno.V0CompressionParameter;
 +        currFn["localAdaptintegration_tau"]>>_retinaParameters.IplMagno.localAdaptintegration_tau;
 +        currFn["localAdaptintegration_k"]>>_retinaParameters.IplMagno.localAdaptintegration_k;
 +
 +        setupIPLMagnoChannel(_retinaParameters.IplMagno.normaliseOutput, _retinaParameters.IplMagno.parasolCells_beta, _retinaParameters.IplMagno.parasolCells_tau, _retinaParameters.IplMagno.parasolCells_k, _retinaParameters.IplMagno.amacrinCellsTemporalCutFrequency,_retinaParameters.IplMagno.V0CompressionParameter, _retinaParameters.IplMagno.localAdaptintegration_tau, _retinaParameters.IplMagno.localAdaptintegration_k);
 +
 +    }catch(Exception &e)
 +    {
 +        printf("RetinaImpl::setup: resetting retina with default parameters\n");
 +        if (applyDefaultSetupOnFailure)
 +        {
 +            setupOPLandIPLParvoChannel();
 +            setupIPLMagnoChannel();
 +        }
 +        printf("Retina::setup: wrong/unappropriate xml parameter file : error report :`n=>%s\n", e.what());
 +        printf("=> keeping current parameters\n");
 +    }
 +
 +    // report current configuration
 +    printf("%s\n", printSetup().c_str());
 +}
 +
 +void RetinaImpl::setup(Retina::RetinaParameters newConfiguration)
 +{
 +    // simply copy structures
 +    memcpy(&_retinaParameters, &newConfiguration, sizeof(Retina::RetinaParameters));
 +    // apply setup
 +    setupOPLandIPLParvoChannel(_retinaParameters.OPLandIplParvo.colorMode, _retinaParameters.OPLandIplParvo.normaliseOutput, _retinaParameters.OPLandIplParvo.photoreceptorsLocalAdaptationSensitivity, _retinaParameters.OPLandIplParvo.photoreceptorsTemporalConstant, _retinaParameters.OPLandIplParvo.photoreceptorsSpatialConstant, _retinaParameters.OPLandIplParvo.horizontalCellsGain, _retinaParameters.OPLandIplParvo.hcellsTemporalConstant, _retinaParameters.OPLandIplParvo.hcellsSpatialConstant, _retinaParameters.OPLandIplParvo.ganglionCellsSensitivity);
 +    setupIPLMagnoChannel(_retinaParameters.IplMagno.normaliseOutput, _retinaParameters.IplMagno.parasolCells_beta, _retinaParameters.IplMagno.parasolCells_tau, _retinaParameters.IplMagno.parasolCells_k, _retinaParameters.IplMagno.amacrinCellsTemporalCutFrequency,_retinaParameters.IplMagno.V0CompressionParameter, _retinaParameters.IplMagno.localAdaptintegration_tau, _retinaParameters.IplMagno.localAdaptintegration_k);
 +
 +}
 +
 +const String RetinaImpl::printSetup()
 +{
 +    std::stringstream outmessage;
 +
 +    // displaying OPL and IPL parvo setup
 +    outmessage<<"Current Retina instance setup :"
 +            <<"\nOPLandIPLparvo"<<"{"
 +            << "\n\t colorMode : " << _retinaParameters.OPLandIplParvo.colorMode
 +            << "\n\t normalizeParvoOutput :" << _retinaParameters.OPLandIplParvo.normaliseOutput
 +            << "\n\t photoreceptorsLocalAdaptationSensitivity : " << _retinaParameters.OPLandIplParvo.photoreceptorsLocalAdaptationSensitivity
 +            << "\n\t photoreceptorsTemporalConstant : " << _retinaParameters.OPLandIplParvo.photoreceptorsTemporalConstant
 +            << "\n\t photoreceptorsSpatialConstant : " << _retinaParameters.OPLandIplParvo.photoreceptorsSpatialConstant
 +            << "\n\t horizontalCellsGain : " << _retinaParameters.OPLandIplParvo.horizontalCellsGain
 +            << "\n\t hcellsTemporalConstant : " << _retinaParameters.OPLandIplParvo.hcellsTemporalConstant
 +            << "\n\t hcellsSpatialConstant : " << _retinaParameters.OPLandIplParvo.hcellsSpatialConstant
 +            << "\n\t parvoGanglionCellsSensitivity : " << _retinaParameters.OPLandIplParvo.ganglionCellsSensitivity
 +            <<"}\n";
 +
 +    // displaying IPL magno setup
 +    outmessage<<"Current Retina instance setup :"
 +            <<"\nIPLmagno"<<"{"
 +            << "\n\t normaliseOutput : " << _retinaParameters.IplMagno.normaliseOutput
 +            << "\n\t parasolCells_beta : " << _retinaParameters.IplMagno.parasolCells_beta
 +            << "\n\t parasolCells_tau : " << _retinaParameters.IplMagno.parasolCells_tau
 +            << "\n\t parasolCells_k : " << _retinaParameters.IplMagno.parasolCells_k
 +            << "\n\t amacrinCellsTemporalCutFrequency : " << _retinaParameters.IplMagno.amacrinCellsTemporalCutFrequency
 +            << "\n\t V0CompressionParameter : " << _retinaParameters.IplMagno.V0CompressionParameter
 +            << "\n\t localAdaptintegration_tau : " << _retinaParameters.IplMagno.localAdaptintegration_tau
 +            << "\n\t localAdaptintegration_k : " << _retinaParameters.IplMagno.localAdaptintegration_k
 +            <<"}";
 +    return outmessage.str().c_str();
 +}
 +
 +void RetinaImpl::write( String fs ) const
 +{
 +    FileStorage parametersSaveFile(fs, cv::FileStorage::WRITE );
 +    write(parametersSaveFile);
 +}
 +
 +void RetinaImpl::write( FileStorage& fs ) const
 +{
 +    if (!fs.isOpened())
 +        return; // basic error case
 +    fs<<"OPLandIPLparvo"<<"{";
 +    fs << "colorMode" << _retinaParameters.OPLandIplParvo.colorMode;
 +    fs << "normaliseOutput" << _retinaParameters.OPLandIplParvo.normaliseOutput;
 +    fs << "photoreceptorsLocalAdaptationSensitivity" << _retinaParameters.OPLandIplParvo.photoreceptorsLocalAdaptationSensitivity;
 +    fs << "photoreceptorsTemporalConstant" << _retinaParameters.OPLandIplParvo.photoreceptorsTemporalConstant;
 +    fs << "photoreceptorsSpatialConstant" << _retinaParameters.OPLandIplParvo.photoreceptorsSpatialConstant;
 +    fs << "horizontalCellsGain" << _retinaParameters.OPLandIplParvo.horizontalCellsGain;
 +    fs << "hcellsTemporalConstant" << _retinaParameters.OPLandIplParvo.hcellsTemporalConstant;
 +    fs << "hcellsSpatialConstant" << _retinaParameters.OPLandIplParvo.hcellsSpatialConstant;
 +    fs << "ganglionCellsSensitivity" << _retinaParameters.OPLandIplParvo.ganglionCellsSensitivity;
 +    fs << "}";
 +    fs<<"IPLmagno"<<"{";
 +    fs << "normaliseOutput" << _retinaParameters.IplMagno.normaliseOutput;
 +    fs << "parasolCells_beta" << _retinaParameters.IplMagno.parasolCells_beta;
 +    fs << "parasolCells_tau" << _retinaParameters.IplMagno.parasolCells_tau;
 +    fs << "parasolCells_k" << _retinaParameters.IplMagno.parasolCells_k;
 +    fs << "amacrinCellsTemporalCutFrequency" << _retinaParameters.IplMagno.amacrinCellsTemporalCutFrequency;
 +    fs << "V0CompressionParameter" << _retinaParameters.IplMagno.V0CompressionParameter;
 +    fs << "localAdaptintegration_tau" << _retinaParameters.IplMagno.localAdaptintegration_tau;
 +    fs << "localAdaptintegration_k" << _retinaParameters.IplMagno.localAdaptintegration_k;
 +    fs<<"}";
 +}
 +
 +void RetinaImpl::setupOPLandIPLParvoChannel(const bool colorMode, const bool normaliseOutput, const float photoreceptorsLocalAdaptationSensitivity, const float photoreceptorsTemporalConstant, const float photoreceptorsSpatialConstant, const float horizontalCellsGain, const float HcellsTemporalConstant, const float HcellsSpatialConstant, const float ganglionCellsSensitivity)
 +{
 +    // retina core parameters setup
 +    _retinaFilter->setColorMode(colorMode);
 +    _retinaFilter->setPhotoreceptorsLocalAdaptationSensitivity(photoreceptorsLocalAdaptationSensitivity);
 +    _retinaFilter->setOPLandParvoParameters(0, photoreceptorsTemporalConstant, photoreceptorsSpatialConstant, horizontalCellsGain, HcellsTemporalConstant, HcellsSpatialConstant, ganglionCellsSensitivity);
 +    _retinaFilter->setParvoGanglionCellsLocalAdaptationSensitivity(ganglionCellsSensitivity);
 +    _retinaFilter->activateNormalizeParvoOutput_0_maxOutputValue(normaliseOutput);
 +
 +        // update parameters struture
 +
 +    _retinaParameters.OPLandIplParvo.colorMode = colorMode;
 +    _retinaParameters.OPLandIplParvo.normaliseOutput = normaliseOutput;
 +    _retinaParameters.OPLandIplParvo.photoreceptorsLocalAdaptationSensitivity = photoreceptorsLocalAdaptationSensitivity;
 +    _retinaParameters.OPLandIplParvo.photoreceptorsTemporalConstant = photoreceptorsTemporalConstant;
 +    _retinaParameters.OPLandIplParvo.photoreceptorsSpatialConstant = photoreceptorsSpatialConstant;
 +    _retinaParameters.OPLandIplParvo.horizontalCellsGain = horizontalCellsGain;
 +    _retinaParameters.OPLandIplParvo.hcellsTemporalConstant = HcellsTemporalConstant;
 +    _retinaParameters.OPLandIplParvo.hcellsSpatialConstant = HcellsSpatialConstant;
 +    _retinaParameters.OPLandIplParvo.ganglionCellsSensitivity = ganglionCellsSensitivity;
 +
 +}
 +
 +void RetinaImpl::setupIPLMagnoChannel(const bool normaliseOutput, const float parasolCells_beta, const float parasolCells_tau, const float parasolCells_k, const float amacrinCellsTemporalCutFrequency, const float V0CompressionParameter, const float localAdaptintegration_tau, const float localAdaptintegration_k)
 +{
 +
 +    _retinaFilter->setMagnoCoefficientsTable(parasolCells_beta, parasolCells_tau, parasolCells_k, amacrinCellsTemporalCutFrequency, V0CompressionParameter, localAdaptintegration_tau, localAdaptintegration_k);
 +    _retinaFilter->activateNormalizeMagnoOutput_0_maxOutputValue(normaliseOutput);
 +
 +        // update parameters struture
 +    _retinaParameters.IplMagno.normaliseOutput = normaliseOutput;
 +    _retinaParameters.IplMagno.parasolCells_beta = parasolCells_beta;
 +    _retinaParameters.IplMagno.parasolCells_tau = parasolCells_tau;
 +    _retinaParameters.IplMagno.parasolCells_k = parasolCells_k;
 +    _retinaParameters.IplMagno.amacrinCellsTemporalCutFrequency = amacrinCellsTemporalCutFrequency;
 +    _retinaParameters.IplMagno.V0CompressionParameter = V0CompressionParameter;
 +    _retinaParameters.IplMagno.localAdaptintegration_tau = localAdaptintegration_tau;
 +    _retinaParameters.IplMagno.localAdaptintegration_k = localAdaptintegration_k;
 +}
 +
 +void RetinaImpl::run(InputArray inputMatToConvert)
 +{
 +    // first convert input image to the compatible format : std::valarray<float>
 +    const bool colorMode = _convertCvMat2ValarrayBuffer(inputMatToConvert.getMat(), _inputBuffer);
 +    // process the retina
 +    if (!_retinaFilter->runFilter(_inputBuffer, colorMode, false, _retinaParameters.OPLandIplParvo.colorMode && colorMode, false))
 +        throw cv::Exception(-1, "RetinaImpl cannot be applied, wrong input buffer size", "RetinaImpl::run", "RetinaImpl.h", 0);
 +}
 +
 +void RetinaImpl::applyFastToneMapping(InputArray inputImage, OutputArray outputToneMappedImage)
 +{
 +    // first convert input image to the compatible format :
 +    const bool colorMode = _convertCvMat2ValarrayBuffer(inputImage.getMat(), _inputBuffer);
 +    const unsigned int nbPixels=_retinaFilter->getOutputNBrows()*_retinaFilter->getOutputNBcolumns();
 +
 +    // process tone mapping
 +    if (colorMode)
 +    {
 +        std::valarray<float> imageOutput(nbPixels*3);
 +        _retinaFilter->runRGBToneMapping(_inputBuffer, imageOutput, true, _retinaParameters.OPLandIplParvo.photoreceptorsLocalAdaptationSensitivity, _retinaParameters.OPLandIplParvo.ganglionCellsSensitivity);
 +        _convertValarrayBuffer2cvMat(imageOutput, _retinaFilter->getOutputNBrows(), _retinaFilter->getOutputNBcolumns(), true, outputToneMappedImage);
 +    }else
 +    {
 +        std::valarray<float> imageOutput(nbPixels);
 +        _retinaFilter->runGrayToneMapping(_inputBuffer, imageOutput, _retinaParameters.OPLandIplParvo.photoreceptorsLocalAdaptationSensitivity, _retinaParameters.OPLandIplParvo.ganglionCellsSensitivity);
 +        _convertValarrayBuffer2cvMat(imageOutput, _retinaFilter->getOutputNBrows(), _retinaFilter->getOutputNBcolumns(), false, outputToneMappedImage);
 +    }
 +
 +}
 +
 +void RetinaImpl::getParvo(OutputArray retinaOutput_parvo)
 +{
 +    if (_retinaFilter->getColorMode())
 +    {
 +        // reallocate output buffer (if necessary)
 +        _convertValarrayBuffer2cvMat(_retinaFilter->getColorOutput(), _retinaFilter->getOutputNBrows(), _retinaFilter->getOutputNBcolumns(), true, retinaOutput_parvo);
 +    }else
 +    {
 +        // reallocate output buffer (if necessary)
 +        _convertValarrayBuffer2cvMat(_retinaFilter->getContours(), _retinaFilter->getOutputNBrows(), _retinaFilter->getOutputNBcolumns(), false, retinaOutput_parvo);
 +    }
 +    //retinaOutput_parvo/=255.0;
 +}
 +void RetinaImpl::getMagno(OutputArray retinaOutput_magno)
 +{
 +    // reallocate output buffer (if necessary)
 +    _convertValarrayBuffer2cvMat(_retinaFilter->getMovingContours(), _retinaFilter->getOutputNBrows(), _retinaFilter->getOutputNBcolumns(), false, retinaOutput_magno);
 +    //retinaOutput_magno/=255.0;
 +}
 +
 +// original API level data accessors : copy buffers if size matches, reallocate if required
 +void RetinaImpl::getMagnoRAW(OutputArray magnoOutputBufferCopy){
 +    // get magno channel header
 +    const cv::Mat magnoChannel=cv::Mat(getMagnoRAW());
 +    // copy data
 +    magnoChannel.copyTo(magnoOutputBufferCopy);
 +}
 +
 +void RetinaImpl::getParvoRAW(OutputArray parvoOutputBufferCopy){
 +    // get parvo channel header
 +    const cv::Mat parvoChannel=cv::Mat(getMagnoRAW());
 +    // copy data
 +    parvoChannel.copyTo(parvoOutputBufferCopy);
 +}
 +
 +// original API level data accessors : get buffers addresses...
 +const Mat RetinaImpl::getMagnoRAW() const {
 +    // create a cv::Mat header for the valarray
 +    return Mat((int)_retinaFilter->getMovingContours().size(),1, CV_32F, (void*)get_data(_retinaFilter->getMovingContours()));
 +
 +}
 +
 +const Mat RetinaImpl::getParvoRAW() const {
 +    if (_retinaFilter->getColorMode()) // check if color mode is enabled
 +    {
 +        // create a cv::Mat table (for RGB planes as a single vector)
 +        return Mat((int)_retinaFilter->getColorOutput().size(), 1, CV_32F, (void*)get_data(_retinaFilter->getColorOutput()));
 +    }
 +    // otherwise, output is gray level
 +    // create a cv::Mat header for the valarray
 +    return Mat((int)_retinaFilter->getContours().size(), 1, CV_32F, (void*)get_data(_retinaFilter->getContours()));
 +}
 +
 +// private method called by constructirs
 +void RetinaImpl::_init(const cv::Size inputSz, const bool colorMode, int colorSamplingMethod, const bool useRetinaLogSampling, const double reductionFactor, const double samplingStrenght)
 +{
 +    // basic error check
 +    if (inputSz.height*inputSz.width <= 0)
 +        throw cv::Exception(-1, "Bad retina size setup : size height and with must be superior to zero", "RetinaImpl::setup", "Retina.cpp", 0);
 +
 +    unsigned int nbPixels=inputSz.height*inputSz.width;
 +    // resize buffers if size does not match
 +    _inputBuffer.resize(nbPixels*3); // buffer supports gray images but also 3 channels color buffers... (larger is better...)
 +
 +    // allocate the retina model
 +        if (_retinaFilter)
 +           delete _retinaFilter;
 +    _retinaFilter = new RetinaFilter(inputSz.height, inputSz.width, colorMode, colorSamplingMethod, useRetinaLogSampling, reductionFactor, samplingStrenght);
 +
 +    _retinaParameters.OPLandIplParvo.colorMode = colorMode;
 +    // prepare the default parameter XML file with default setup
 +    setup(_retinaParameters);
 +
 +    // init retina
 +    _retinaFilter->clearAllBuffers();
 +
 +    // report current configuration
 +    printf("%s\n", printSetup().c_str());
 +}
 +
 +void RetinaImpl::_convertValarrayBuffer2cvMat(const std::valarray<float> &grayMatrixToConvert, const unsigned int nbRows, const unsigned int nbColumns, const bool colorMode, OutputArray outBuffer)
 +{
 +    // fill output buffer with the valarray buffer
 +    const float *valarrayPTR=get_data(grayMatrixToConvert);
 +    if (!colorMode)
 +    {
 +        outBuffer.create(cv::Size(nbColumns, nbRows), CV_8U);
 +        Mat outMat = outBuffer.getMat();
 +        for (unsigned int i=0;i<nbRows;++i)
 +        {
 +            for (unsigned int j=0;j<nbColumns;++j)
 +            {
 +                cv::Point2d pixel(j,i);
 +                outMat.at<unsigned char>(pixel)=(unsigned char)*(valarrayPTR++);
 +            }
 +        }
 +    }else
 +    {
 +        const unsigned int nbPixels=nbColumns*nbRows;
 +        const unsigned int doubleNBpixels=nbColumns*nbRows*2;
 +        outBuffer.create(cv::Size(nbColumns, nbRows), CV_8UC3);
 +        Mat outMat = outBuffer.getMat();
 +        for (unsigned int i=0;i<nbRows;++i)
 +        {
 +            for (unsigned int j=0;j<nbColumns;++j,++valarrayPTR)
 +            {
 +                cv::Point2d pixel(j,i);
 +                cv::Vec3b pixelValues;
 +                pixelValues[2]=(unsigned char)*(valarrayPTR);
 +                pixelValues[1]=(unsigned char)*(valarrayPTR+nbPixels);
 +                pixelValues[0]=(unsigned char)*(valarrayPTR+doubleNBpixels);
 +
 +                outMat.at<cv::Vec3b>(pixel)=pixelValues;
 +            }
 +        }
 +    }
 +}
 +
 +bool RetinaImpl::_convertCvMat2ValarrayBuffer(InputArray inputMat, std::valarray<float> &outputValarrayMatrix)
 +{
 +    const Mat inputMatToConvert=inputMat.getMat();
 +    // first check input consistency
 +    if (inputMatToConvert.empty())
 +        throw cv::Exception(-1, "RetinaImpl cannot be applied, input buffer is empty", "RetinaImpl::run", "RetinaImpl.h", 0);
 +
 +    // retreive color mode from image input
 +    int imageNumberOfChannels = inputMatToConvert.channels();
 +
 +        // convert to float AND fill the valarray buffer
 +    typedef float T; // define here the target pixel format, here, float
 +    const int dsttype = DataType<T>::depth; // output buffer is float format
 +
 +    const unsigned int nbPixels=inputMat.getMat().rows*inputMat.getMat().cols;
 +    const unsigned int doubleNBpixels=inputMat.getMat().rows*inputMat.getMat().cols*2;
 +
 +    if(imageNumberOfChannels==4)
 +    {
 +    // create a cv::Mat table (for RGBA planes)
 +        cv::Mat planes[4] =
 +        {
 +            cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[doubleNBpixels]),
 +            cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[nbPixels]),
 +            cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[0])
 +        };
 +        planes[3] = cv::Mat(inputMatToConvert.size(), dsttype);     // last channel (alpha) does not point on the valarray (not usefull in our case)
 +        // split color cv::Mat in 4 planes... it fills valarray directely
 +        cv::split(Mat_<Vec<T, 4> >(inputMatToConvert), planes);
 +    }
 +    else if (imageNumberOfChannels==3)
 +    {
 +        // create a cv::Mat table (for RGB planes)
 +        cv::Mat planes[] =
 +        {
 +        cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[doubleNBpixels]),
 +        cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[nbPixels]),
 +        cv::Mat(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[0])
 +        };
 +        // split color cv::Mat in 3 planes... it fills valarray directely
 +        cv::split(cv::Mat_<Vec<T, 3> >(inputMatToConvert), planes);
 +    }
 +    else if(imageNumberOfChannels==1)
 +    {
 +        // create a cv::Mat header for the valarray
 +        cv::Mat dst(inputMatToConvert.size(), dsttype, &outputValarrayMatrix[0]);
 +        inputMatToConvert.convertTo(dst, dsttype);
 +    }
 +        else
 +            CV_Error(Error::StsUnsupportedFormat, "input image must be single channel (gray levels), bgr format (color) or bgra (color with transparency which won't be considered");
 +
 +    return imageNumberOfChannels>1; // return bool : false for gray level image processing, true for color mode
 +}
 +
 +void RetinaImpl::clearBuffers() {_retinaFilter->clearAllBuffers();}
 +
 +void RetinaImpl::activateMovingContoursProcessing(const bool activate){_retinaFilter->activateMovingContoursProcessing(activate);}
 +
 +void RetinaImpl::activateContoursProcessing(const bool activate){_retinaFilter->activateContoursProcessing(activate);}
 +
 +}// end of namespace bioinspired
 +}// end of namespace cv
@@@ -989,15 -987,15 +989,15 @@@ static void fjac_new(int i, int j, Mat
  static void func_new(int i, int j, Mat& point_params, Mat& cam_params, Mat& estim, void* data)  {
    CvMat _point_params = point_params, _cam_params = cam_params, _estim = estim;
    func(i,j,&_point_params,&_cam_params,&_estim,data);
- };
+ }
  
 -void LevMarqSparse::bundleAdjust( vector<Point3d>& points, //positions of points in global coordinate system (input and output)
 -          const vector<vector<Point2d> >& imagePoints, //projections of 3d points for every camera
 -          const vector<vector<int> >& visibility, //visibility of 3d points for every camera
 -          vector<Mat>& cameraMatrix, //intrinsic matrices of all cameras (input and output)
 -          vector<Mat>& R, //rotation matrices of all cameras (input and output)
 -          vector<Mat>& T, //translation vector of all cameras (input and output)
 -          vector<Mat>& distCoeffs, //distortion coefficients of all cameras (input and output)
 +void LevMarqSparse::bundleAdjust( std::vector<Point3d>& points, //positions of points in global coordinate system (input and output)
 +          const std::vector<std::vector<Point2d> >& imagePoints, //projections of 3d points for every camera
 +          const std::vector<std::vector<int> >& visibility, //visibility of 3d points for every camera
 +          std::vector<Mat>& cameraMatrix, //intrinsic matrices of all cameras (input and output)
 +          std::vector<Mat>& R, //rotation matrices of all cameras (input and output)
 +          std::vector<Mat>& T, //translation vector of all cameras (input and output)
 +          std::vector<Mat>& distCoeffs, //distortion coefficients of all cameras (input and output)
            const TermCriteria& criteria,
            BundleAdjustCallback cb, void* user_data) {
    //,enum{MOTION_AND_STRUCTURE,MOTION,STRUCTURE})
Simple merge
Simple merge
index 3079548,0000000..0cefa15
mode 100644,000000..100644
--- /dev/null
@@@ -1,3359 -1,0 +1,3359 @@@
-         m.convertTo(this, DataType<_Tp>::type);
 +/*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 ////////////////////////
 +
 +inline void _InputArray::init(int _flags, const void* _obj)
 +{ flags = _flags; obj = (void*)_obj; }
 +
 +inline void _InputArray::init(int _flags, const void* _obj, Size _sz)
 +{ flags = _flags; obj = (void*)_obj; sz = _sz; }
 +
 +inline void* _InputArray::getObj() const { return obj; }
 +
 +inline _InputArray::_InputArray() { init(NONE, 0); }
 +inline _InputArray::_InputArray(int _flags, void* _obj) { init(_flags, _obj); }
 +inline _InputArray::_InputArray(const Mat& m) { init(MAT+ACCESS_READ, &m); }
 +inline _InputArray::_InputArray(const std::vector<Mat>& vec) { init(STD_VECTOR_MAT+ACCESS_READ, &vec); }
 +inline _InputArray::_InputArray(const UMat& m) { init(UMAT+ACCESS_READ, &m); }
 +inline _InputArray::_InputArray(const std::vector<UMat>& vec) { init(STD_VECTOR_UMAT+ACCESS_READ, &vec); }
 +
 +template<typename _Tp> inline
 +_InputArray::_InputArray(const std::vector<_Tp>& vec)
 +{ init(FIXED_TYPE + STD_VECTOR + DataType<_Tp>::type + ACCESS_READ, &vec); }
 +
 +template<typename _Tp> inline
 +_InputArray::_InputArray(const std::vector<std::vector<_Tp> >& vec)
 +{ init(FIXED_TYPE + STD_VECTOR_VECTOR + DataType<_Tp>::type + ACCESS_READ, &vec); }
 +
 +template<typename _Tp> inline
 +_InputArray::_InputArray(const std::vector<Mat_<_Tp> >& vec)
 +{ init(FIXED_TYPE + STD_VECTOR_MAT + DataType<_Tp>::type + ACCESS_READ, &vec); }
 +
 +template<typename _Tp, int m, int n> inline
 +_InputArray::_InputArray(const Matx<_Tp, m, n>& mtx)
 +{ init(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type + ACCESS_READ, &mtx, Size(n, m)); }
 +
 +template<typename _Tp> inline
 +_InputArray::_InputArray(const _Tp* vec, int n)
 +{ init(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type + ACCESS_READ, vec, Size(n, 1)); }
 +
 +template<typename _Tp> inline
 +_InputArray::_InputArray(const Mat_<_Tp>& m)
 +{ init(FIXED_TYPE + MAT + DataType<_Tp>::type + ACCESS_READ, &m); }
 +
 +inline _InputArray::_InputArray(const double& val)
 +{ init(FIXED_TYPE + FIXED_SIZE + MATX + CV_64F + ACCESS_READ, &val, Size(1,1)); }
 +
 +inline _InputArray::_InputArray(const MatExpr& expr)
 +{ init(FIXED_TYPE + FIXED_SIZE + EXPR + ACCESS_READ, &expr); }
 +
 +inline _InputArray::_InputArray(const cuda::GpuMat& d_mat)
 +{ init(GPU_MAT + ACCESS_READ, &d_mat); }
 +
 +inline _InputArray::_InputArray(const ogl::Buffer& buf)
 +{ init(OPENGL_BUFFER + ACCESS_READ, &buf); }
 +
 +inline _InputArray::_InputArray(const cuda::CudaMem& cuda_mem)
 +{ init(CUDA_MEM + ACCESS_READ, &cuda_mem); }
 +
 +inline _InputArray::~_InputArray() {}
 +
 +inline bool _InputArray::isMat() const { return kind() == _InputArray::MAT; }
 +inline bool _InputArray::isUMat() const  { return kind() == _InputArray::UMAT; }
 +inline bool _InputArray::isMatVectot() const { return kind() == _InputArray::STD_VECTOR_MAT; }
 +inline bool _InputArray::isUMatVector() const  { return kind() == _InputArray::STD_VECTOR_UMAT; }
 +inline bool _InputArray::isMatx()  { return kind() == _InputArray::MATX; }
 +
 +////////////////////////////////////////////////////////////////////////////////////////
 +
 +inline _OutputArray::_OutputArray() { init(ACCESS_WRITE, 0); }
 +inline _OutputArray::_OutputArray(int _flags, void* _obj) { init(_flags|ACCESS_WRITE, _obj); }
 +inline _OutputArray::_OutputArray(Mat& m) { init(MAT+ACCESS_WRITE, &m); }
 +inline _OutputArray::_OutputArray(std::vector<Mat>& vec) { init(STD_VECTOR_MAT+ACCESS_WRITE, &vec); }
 +inline _OutputArray::_OutputArray(UMat& m) { init(UMAT+ACCESS_WRITE, &m); }
 +inline _OutputArray::_OutputArray(std::vector<UMat>& vec) { init(STD_VECTOR_UMAT+ACCESS_WRITE, &vec); }
 +
 +template<typename _Tp> inline
 +_OutputArray::_OutputArray(std::vector<_Tp>& vec)
 +{ init(FIXED_TYPE + STD_VECTOR + DataType<_Tp>::type + ACCESS_WRITE, &vec); }
 +
 +template<typename _Tp> inline
 +_OutputArray::_OutputArray(std::vector<std::vector<_Tp> >& vec)
 +{ init(FIXED_TYPE + STD_VECTOR_VECTOR + DataType<_Tp>::type + ACCESS_WRITE, &vec); }
 +
 +template<typename _Tp> inline
 +_OutputArray::_OutputArray(std::vector<Mat_<_Tp> >& vec)
 +{ init(FIXED_TYPE + STD_VECTOR_MAT + DataType<_Tp>::type + ACCESS_WRITE, &vec); }
 +
 +template<typename _Tp> inline
 +_OutputArray::_OutputArray(Mat_<_Tp>& m)
 +{ init(FIXED_TYPE + MAT + DataType<_Tp>::type + ACCESS_WRITE, &m); }
 +
 +template<typename _Tp, int m, int n> inline
 +_OutputArray::_OutputArray(Matx<_Tp, m, n>& mtx)
 +{ init(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type + ACCESS_WRITE, &mtx, Size(n, m)); }
 +
 +template<typename _Tp> inline
 +_OutputArray::_OutputArray(_Tp* vec, int n)
 +{ init(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type + ACCESS_WRITE, vec, Size(n, 1)); }
 +
 +template<typename _Tp> inline
 +_OutputArray::_OutputArray(const std::vector<_Tp>& vec)
 +{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR + DataType<_Tp>::type + ACCESS_WRITE, &vec); }
 +
 +template<typename _Tp> inline
 +_OutputArray::_OutputArray(const std::vector<std::vector<_Tp> >& vec)
 +{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_VECTOR + DataType<_Tp>::type + ACCESS_WRITE, &vec); }
 +
 +template<typename _Tp> inline
 +_OutputArray::_OutputArray(const std::vector<Mat_<_Tp> >& vec)
 +{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_MAT + DataType<_Tp>::type + ACCESS_WRITE, &vec); }
 +
 +template<typename _Tp> inline
 +_OutputArray::_OutputArray(const Mat_<_Tp>& m)
 +{ init(FIXED_TYPE + FIXED_SIZE + MAT + DataType<_Tp>::type + ACCESS_WRITE, &m); }
 +
 +template<typename _Tp, int m, int n> inline
 +_OutputArray::_OutputArray(const Matx<_Tp, m, n>& mtx)
 +{ init(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type + ACCESS_WRITE, &mtx, Size(n, m)); }
 +
 +template<typename _Tp> inline
 +_OutputArray::_OutputArray(const _Tp* vec, int n)
 +{ init(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type + ACCESS_WRITE, vec, Size(n, 1)); }
 +
 +inline _OutputArray::_OutputArray(cuda::GpuMat& d_mat)
 +{ init(GPU_MAT + ACCESS_WRITE, &d_mat); }
 +
 +inline _OutputArray::_OutputArray(ogl::Buffer& buf)
 +{ init(OPENGL_BUFFER + ACCESS_WRITE, &buf); }
 +
 +inline _OutputArray::_OutputArray(cuda::CudaMem& cuda_mem)
 +{ init(CUDA_MEM + ACCESS_WRITE, &cuda_mem); }
 +
 +inline _OutputArray::_OutputArray(const Mat& m)
 +{ init(FIXED_TYPE + FIXED_SIZE + MAT + ACCESS_WRITE, &m); }
 +
 +inline _OutputArray::_OutputArray(const std::vector<Mat>& vec)
 +{ init(FIXED_SIZE + STD_VECTOR_MAT + ACCESS_WRITE, &vec); }
 +
 +inline _OutputArray::_OutputArray(const cuda::GpuMat& d_mat)
 +{ init(FIXED_TYPE + FIXED_SIZE + GPU_MAT + ACCESS_WRITE, &d_mat); }
 +
 +inline _OutputArray::_OutputArray(const ogl::Buffer& buf)
 +{ init(FIXED_TYPE + FIXED_SIZE + OPENGL_BUFFER + ACCESS_WRITE, &buf); }
 +
 +inline _OutputArray::_OutputArray(const cuda::CudaMem& cuda_mem)
 +{ init(FIXED_TYPE + FIXED_SIZE + CUDA_MEM + ACCESS_WRITE, &cuda_mem); }
 +
 +///////////////////////////////////////////////////////////////////////////////////////////
 +
 +inline _InputOutputArray::_InputOutputArray() { init(ACCESS_RW, 0); }
 +inline _InputOutputArray::_InputOutputArray(int _flags, void* _obj) { init(_flags|ACCESS_RW, _obj); }
 +inline _InputOutputArray::_InputOutputArray(Mat& m) { init(MAT+ACCESS_RW, &m); }
 +inline _InputOutputArray::_InputOutputArray(std::vector<Mat>& vec) { init(STD_VECTOR_MAT+ACCESS_RW, &vec); }
 +inline _InputOutputArray::_InputOutputArray(UMat& m) { init(UMAT+ACCESS_RW, &m); }
 +inline _InputOutputArray::_InputOutputArray(std::vector<UMat>& vec) { init(STD_VECTOR_UMAT+ACCESS_RW, &vec); }
 +
 +template<typename _Tp> inline
 +_InputOutputArray::_InputOutputArray(std::vector<_Tp>& vec)
 +{ init(FIXED_TYPE + STD_VECTOR + DataType<_Tp>::type + ACCESS_RW, &vec); }
 +
 +template<typename _Tp> inline
 +_InputOutputArray::_InputOutputArray(std::vector<std::vector<_Tp> >& vec)
 +{ init(FIXED_TYPE + STD_VECTOR_VECTOR + DataType<_Tp>::type + ACCESS_RW, &vec); }
 +
 +template<typename _Tp> inline
 +_InputOutputArray::_InputOutputArray(std::vector<Mat_<_Tp> >& vec)
 +{ init(FIXED_TYPE + STD_VECTOR_MAT + DataType<_Tp>::type + ACCESS_RW, &vec); }
 +
 +template<typename _Tp> inline
 +_InputOutputArray::_InputOutputArray(Mat_<_Tp>& m)
 +{ init(FIXED_TYPE + MAT + DataType<_Tp>::type + ACCESS_RW, &m); }
 +
 +template<typename _Tp, int m, int n> inline
 +_InputOutputArray::_InputOutputArray(Matx<_Tp, m, n>& mtx)
 +{ init(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type + ACCESS_RW, &mtx, Size(n, m)); }
 +
 +template<typename _Tp> inline
 +_InputOutputArray::_InputOutputArray(_Tp* vec, int n)
 +{ init(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type + ACCESS_RW, vec, Size(n, 1)); }
 +
 +template<typename _Tp> inline
 +_InputOutputArray::_InputOutputArray(const std::vector<_Tp>& vec)
 +{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR + DataType<_Tp>::type + ACCESS_RW, &vec); }
 +
 +template<typename _Tp> inline
 +_InputOutputArray::_InputOutputArray(const std::vector<std::vector<_Tp> >& vec)
 +{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_VECTOR + DataType<_Tp>::type + ACCESS_RW, &vec); }
 +
 +template<typename _Tp> inline
 +_InputOutputArray::_InputOutputArray(const std::vector<Mat_<_Tp> >& vec)
 +{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_MAT + DataType<_Tp>::type + ACCESS_RW, &vec); }
 +
 +template<typename _Tp> inline
 +_InputOutputArray::_InputOutputArray(const Mat_<_Tp>& m)
 +{ init(FIXED_TYPE + FIXED_SIZE + MAT + DataType<_Tp>::type + ACCESS_RW, &m); }
 +
 +template<typename _Tp, int m, int n> inline
 +_InputOutputArray::_InputOutputArray(const Matx<_Tp, m, n>& mtx)
 +{ init(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type + ACCESS_RW, &mtx, Size(n, m)); }
 +
 +template<typename _Tp> inline
 +_InputOutputArray::_InputOutputArray(const _Tp* vec, int n)
 +{ init(FIXED_TYPE + FIXED_SIZE + MATX + DataType<_Tp>::type + ACCESS_RW, vec, Size(n, 1)); }
 +
 +inline _InputOutputArray::_InputOutputArray(cuda::GpuMat& d_mat)
 +{ init(GPU_MAT + ACCESS_RW, &d_mat); }
 +
 +inline _InputOutputArray::_InputOutputArray(ogl::Buffer& buf)
 +{ init(OPENGL_BUFFER + ACCESS_RW, &buf); }
 +
 +inline _InputOutputArray::_InputOutputArray(cuda::CudaMem& cuda_mem)
 +{ init(CUDA_MEM + ACCESS_RW, &cuda_mem); }
 +
 +inline _InputOutputArray::_InputOutputArray(const Mat& m)
 +{ init(FIXED_TYPE + FIXED_SIZE + MAT + ACCESS_RW, &m); }
 +
 +inline _InputOutputArray::_InputOutputArray(const std::vector<Mat>& vec)
 +{ init(FIXED_SIZE + STD_VECTOR_MAT + ACCESS_RW, &vec); }
 +
 +inline _InputOutputArray::_InputOutputArray(const UMat& m)
 +{ init(FIXED_TYPE + FIXED_SIZE + UMAT + ACCESS_RW, &m); }
 +
 +inline _InputOutputArray::_InputOutputArray(const std::vector<UMat>& vec)
 +{ init(FIXED_SIZE + STD_VECTOR_UMAT + ACCESS_RW, &vec); }
 +
 +inline _InputOutputArray::_InputOutputArray(const cuda::GpuMat& d_mat)
 +{ init(FIXED_TYPE + FIXED_SIZE + GPU_MAT + ACCESS_RW, &d_mat); }
 +
 +inline _InputOutputArray::_InputOutputArray(const ogl::Buffer& buf)
 +{ init(FIXED_TYPE + FIXED_SIZE + OPENGL_BUFFER + ACCESS_RW, &buf); }
 +
 +inline _InputOutputArray::_InputOutputArray(const cuda::CudaMem& cuda_mem)
 +{ init(FIXED_TYPE + FIXED_SIZE + CUDA_MEM + ACCESS_RW, &cuda_mem); }
 +
 +//////////////////////////////////////////// Mat //////////////////////////////////////////
 +
 +inline
 +Mat::Mat()
 +    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
 +      datalimit(0), allocator(0), u(0), size(&rows)
 +{}
 +
 +inline
 +Mat::Mat(int _rows, int _cols, int _type)
 +    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
 +      datalimit(0), allocator(0), u(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), datastart(0), dataend(0),
 +      datalimit(0), allocator(0), u(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), datastart(0), dataend(0),
 +      datalimit(0), allocator(0), u(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), datastart(0), dataend(0),
 +      datalimit(0), allocator(0), u(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), datastart(0), dataend(0),
 +      datalimit(0), allocator(0), u(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), datastart(0), dataend(0),
 +      datalimit(0), allocator(0), u(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),
 +      datastart(m.datastart), dataend(m.dataend), datalimit(m.datalimit), allocator(m.allocator),
 +      u(m.u), size(&rows)
 +{
 +    if( u )
 +        CV_XADD(&u->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), datastart((uchar*)_data), dataend(0), datalimit(0),
 +      allocator(0), u(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), datastart((uchar*)_data), dataend(0), datalimit(0),
 +      allocator(0), u(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), datastart(0), dataend(0), allocator(0), u(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),
 +      datastart(0), dataend(0), allocator(0), u(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),
 +      datastart(0), dataend(0), allocator(0), u(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),
 +      datastart(0), dataend(0), allocator(0), u(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),
 +      datastart(0), dataend(0), allocator(0), u(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),
 +      datastart(0), dataend(0), allocator(0), u(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.u )
 +            CV_XADD(&m.u->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;
 +        allocator = m.allocator;
 +        u = m.u;
 +    }
 +    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( u )
 +        CV_XADD(&u->refcount, 1);
 +}
 +
 +inline void Mat::release()
 +{
 +    if( u && CV_XADD(&u->refcount, -1) == 1 )
 +        deallocate();
 +    u = NULL;
 +    data = datastart = dataend = datalimit = 0;
 +    size.p[0] = 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);
 +}
 +
 +///////////////////////////// MatSize ////////////////////////////
 +
 +inline
 +MatSize::MatSize(int* _p)
 +    : p(_p) {}
 +
 +inline
 +Size MatSize::operator()() const
 +{
 +    CV_DbgAssert(p[-1] <= 2);
 +    return Size(p[1], p[0]);
 +}
 +
 +inline
 +const int& MatSize::operator[](int i) const
 +{
 +    return p[i];
 +}
 +
 +inline
 +int& MatSize::operator[](int i)
 +{
 +    return p[i];
 +}
 +
 +inline
 +MatSize::operator const int*() const
 +{
 +    return p;
 +}
 +
 +inline
 +bool MatSize::operator == (const MatSize& 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 MatSize::operator != (const MatSize& sz) const
 +{
 +    return !(*this == sz);
 +}
 +
 +
 +
 +///////////////////////////// MatStep ////////////////////////////
 +
 +inline
 +MatStep::MatStep()
 +{
 +    p = buf; p[0] = p[1] = 0;
 +}
 +
 +inline
 +MatStep::MatStep(size_t s)
 +{
 +    p = buf; p[0] = s; p[1] = 0;
 +}
 +
 +inline
 +const size_t& MatStep::operator[](int i) const
 +{
 +    return p[i];
 +}
 +
 +inline
 +size_t& MatStep::operator[](int i)
 +{
 +    return p[i];
 +}
 +
 +inline MatStep::operator size_t() const
 +{
 +    CV_DbgAssert( p == buf );
 +    return buf[0];
 +}
 +
 +inline MatStep& MatStep::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);
 +
 +    Matx<typename DataType<_Tp>::channel_type, m, n> res = this->Mat::operator Matx<typename DataType<_Tp>::channel_type, m, n>();
 +    return res;
 +}
 +
 +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>();
 +}
 +
 +
 +///////////////////////////// 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 (Node*)(void*)&hdr->pool[nidx];
 +}
 +
 +inline
 +const SparseMat::Node* SparseMat::node(size_t nidx) const
 +{
 +    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;
 +}
 +
 +
 +//////////////////////////////// UMat ////////////////////////////////
 +
 +inline
 +UMat::UMat()
 +: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), u(0), offset(0), size(&rows)
 +{}
 +
 +inline
 +UMat::UMat(int _rows, int _cols, int _type)
 +: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), u(0), offset(0), size(&rows)
 +{
 +    create(_rows, _cols, _type);
 +}
 +
 +inline
 +UMat::UMat(int _rows, int _cols, int _type, const Scalar& _s)
 +: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), u(0), offset(0), size(&rows)
 +{
 +    create(_rows, _cols, _type);
 +    *this = _s;
 +}
 +
 +inline
 +UMat::UMat(Size _sz, int _type)
 +: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), u(0), offset(0), size(&rows)
 +{
 +    create( _sz.height, _sz.width, _type );
 +}
 +
 +inline
 +UMat::UMat(Size _sz, int _type, const Scalar& _s)
 +: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), u(0), offset(0), size(&rows)
 +{
 +    create(_sz.height, _sz.width, _type);
 +    *this = _s;
 +}
 +
 +inline
 +UMat::UMat(int _dims, const int* _sz, int _type)
 +: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), u(0), offset(0), size(&rows)
 +{
 +    create(_dims, _sz, _type);
 +}
 +
 +inline
 +UMat::UMat(int _dims, const int* _sz, int _type, const Scalar& _s)
 +: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), u(0), offset(0), size(&rows)
 +{
 +    create(_dims, _sz, _type);
 +    *this = _s;
 +}
 +
 +inline
 +UMat::UMat(const UMat& m)
 +: flags(m.flags), dims(m.dims), rows(m.rows), cols(m.cols), allocator(m.allocator),
 +u(m.u), offset(m.offset), size(&rows)
 +{
 +    if( u )
 +        CV_XADD(&(u->urefcount), 1);
 +    if( m.dims <= 2 )
 +    {
 +        step[0] = m.step[0]; step[1] = m.step[1];
 +    }
 +    else
 +    {
 +        dims = 0;
 +        copySize(m);
 +    }
 +}
 +
 +
 +template<typename _Tp> inline
 +UMat::UMat(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), allocator(0), u(0), offset(0), size(&rows)
 +{
 +    if(vec.empty())
 +        return;
 +    if( !copyData )
 +    {
 +        // !!!TODO!!!
 +        CV_Error(Error::StsNotImplemented, "");
 +    }
 +    else
 +        Mat((int)vec.size(), 1, DataType<_Tp>::type, (uchar*)&vec[0]).copyTo(*this);
 +}
 +
 +
 +inline
 +UMat& UMat::operator = (const UMat& m)
 +{
 +    if( this != &m )
 +    {
 +        if( m.u )
 +            CV_XADD(&(m.u->urefcount), 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);
 +        allocator = m.allocator;
 +        u = m.u;
 +        offset = m.offset;
 +    }
 +    return *this;
 +}
 +
 +inline
 +UMat UMat::row(int y) const
 +{
 +    return UMat(*this, Range(y, y + 1), Range::all());
 +}
 +
 +inline
 +UMat UMat::col(int x) const
 +{
 +    return UMat(*this, Range::all(), Range(x, x + 1));
 +}
 +
 +inline
 +UMat UMat::rowRange(int startrow, int endrow) const
 +{
 +    return UMat(*this, Range(startrow, endrow), Range::all());
 +}
 +
 +inline
 +UMat UMat::rowRange(const Range& r) const
 +{
 +    return UMat(*this, r, Range::all());
 +}
 +
 +inline
 +UMat UMat::colRange(int startcol, int endcol) const
 +{
 +    return UMat(*this, Range::all(), Range(startcol, endcol));
 +}
 +
 +inline
 +UMat UMat::colRange(const Range& r) const
 +{
 +    return UMat(*this, Range::all(), r);
 +}
 +
 +inline
 +UMat UMat::clone() const
 +{
 +    UMat m;
 +    copyTo(m);
 +    return m;
 +}
 +
 +inline
 +void UMat::assignTo( UMat& m, int _type ) const
 +{
 +    if( _type < 0 )
 +        m = *this;
 +    else
 +        convertTo(m, _type);
 +}
 +
 +inline
 +void UMat::create(int _rows, int _cols, int _type)
 +{
 +    _type &= TYPE_MASK;
 +    if( dims <= 2 && rows == _rows && cols == _cols && type() == _type && u )
 +        return;
 +    int sz[] = {_rows, _cols};
 +    create(2, sz, _type);
 +}
 +
 +inline
 +void UMat::create(Size _sz, int _type)
 +{
 +    create(_sz.height, _sz.width, _type);
 +}
 +
 +inline
 +void UMat::addref()
 +{
 +    if( u )
 +        CV_XADD(&(u->urefcount), 1);
 +}
 +
 +inline void UMat::release()
 +{
 +    if( u && CV_XADD(&(u->urefcount), -1) == 1 )
 +        deallocate();
 +    size.p[0] = 0;
 +    u = 0;
 +}
 +
 +inline
 +UMat UMat::operator()( Range _rowRange, Range _colRange ) const
 +{
 +    return UMat(*this, _rowRange, _colRange);
 +}
 +
 +inline
 +UMat UMat::operator()( const Rect& roi ) const
 +{
 +    return UMat(*this, roi);
 +}
 +
 +inline
 +UMat UMat::operator()(const Range* ranges) const
 +{
 +    return UMat(*this, ranges);
 +}
 +
 +inline
 +bool UMat::isContinuous() const
 +{
 +    return (flags & CONTINUOUS_FLAG) != 0;
 +}
 +
 +inline
 +bool UMat::isSubmatrix() const
 +{
 +    return (flags & SUBMATRIX_FLAG) != 0;
 +}
 +
 +inline
 +size_t UMat::elemSize() const
 +{
 +    return dims > 0 ? step.p[dims - 1] : 0;
 +}
 +
 +inline
 +size_t UMat::elemSize1() const
 +{
 +    return CV_ELEM_SIZE1(flags);
 +}
 +
 +inline
 +int UMat::type() const
 +{
 +    return CV_MAT_TYPE(flags);
 +}
 +
 +inline
 +int UMat::depth() const
 +{
 +    return CV_MAT_DEPTH(flags);
 +}
 +
 +inline
 +int UMat::channels() const
 +{
 +    return CV_MAT_CN(flags);
 +}
 +
 +inline
 +size_t UMat::step1(int i) const
 +{
 +    return step.p[i] / elemSize1();
 +}
 +
 +inline
 +bool UMat::empty() const
 +{
 +    return u == 0 || total() == 0;
 +}
 +
 +inline
 +size_t UMat::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 bool UMatData::hostCopyObsolete() const { return (flags & HOST_COPY_OBSOLETE) != 0; }
 +inline bool UMatData::deviceCopyObsolete() const { return (flags & DEVICE_COPY_OBSOLETE) != 0; }
 +inline bool UMatData::copyOnMap() const { return (flags & COPY_ON_MAP) != 0; }
 +inline bool UMatData::tempUMat() const { return (flags & TEMP_UMAT) != 0; }
 +inline bool UMatData::tempCopiedUMat() const { return (flags & TEMP_COPIED_UMAT) == TEMP_COPIED_UMAT; }
 +
 +inline void UMatData::markHostCopyObsolete(bool flag)
 +{
 +    if(flag)
 +        flags |= HOST_COPY_OBSOLETE;
 +    else
 +        flags &= ~HOST_COPY_OBSOLETE;
 +}
 +inline void UMatData::markDeviceCopyObsolete(bool flag)
 +{
 +    if(flag)
 +        flags |= DEVICE_COPY_OBSOLETE;
 +    else
 +        flags &= ~DEVICE_COPY_OBSOLETE;
 +}
 +
 +inline UMatDataAutoLock::UMatDataAutoLock(UMatData* _u) : u(_u) { u->lock(); }
 +inline UMatDataAutoLock::~UMatDataAutoLock() { u->unlock(); }
 +
 +} //cv
 +
 +#endif
@@@ -628,9 -647,10 +628,9 @@@ void AlgorithmInfo::set(Algorithm* algo
              || argType == Param::FLOAT || argType == Param::UNSIGNED_INT || argType == Param::UINT64 || argType == Param::UCHAR)
      {
          if ( !( p->type == Param::INT || p->type == Param::REAL || p->type == Param::BOOLEAN
-                 || p->type == Param::UNSIGNED_INT || p->type == Param::UINT64 || p->type == Param::FLOAT || argType == Param::UCHAR) )
 -                || p->type == Param::UNSIGNED_INT || p->type == Param::UINT64 || p->type == Param::FLOAT || p->type == Param::UCHAR
 -                || (p->type == Param::SHORT && argType == Param::INT)) )
++                || p->type == Param::UNSIGNED_INT || p->type == Param::UINT64 || p->type == Param::FLOAT || p->type == Param::UCHAR) )
          {
 -            string message = getErrorMessageForWrongArgumentInSetter(algo->name(), parameter, p->type, argType);
 +            String message = getErrorMessageForWrongArgumentInSetter(algo->name(), parameter, p->type, argType);
              CV_Error(CV_StsBadArg, message);
          }
  
@@@ -1432,33 -1270,23 +1432,33 @@@ static void arithm_op(InputArray _src1
      }
  
      bool haveScalar = false, swapped12 = false;
 -    int depth2 = src2.depth();
 -    if( src1.size != src2.size || src1.channels() != src2.channels() ||
 -        (kind1 == _InputArray::MATX && (src1.size() == Size(1,4) || src1.size() == Size(1,1))) ||
 -        (kind2 == _InputArray::MATX && (src2.size() == Size(1,4) || src2.size() == Size(1,1))) )
 +
 +    if( dims1 != dims2 || sz1 != sz2 || cn != cn2 ||
-         ((kind1 == _InputArray::MATX || kind2 == _InputArray::MATX) &&
-          (sz1 == Size(1,4) || sz2 == Size(1,4))) )
++        (kind1 == _InputArray::MATX && (sz1 == Size(1,4) || sz1 == Size(1,1))) ||
++        (kind2 == _InputArray::MATX && (sz2 == Size(1,4) || sz2 == Size(1,1))) )
      {
 -        if( checkScalar(src1, src2.type(), kind1, kind2) )
 +        if( checkScalar(*psrc1, type2, kind1, kind2) )
          {
              // src1 is a scalar; swap it with src2
 -            swap(src1, src2);
 +            swap(psrc1, psrc2);
 +            swap(sz1, sz2);
 +            swap(type1, type2);
 +            swap(depth1, depth2);
 +            swap(cn, cn2);
 +            swap(dims1, dims2);
              swapped12 = true;
 +            if( oclop == OCL_OP_SUB )
 +                oclop = OCL_OP_RSUB;
 +            if ( oclop == OCL_OP_DIV_SCALE )
 +                oclop = OCL_OP_RDIV_SCALE;
          }
 -        else if( !checkScalar(src2, src1.type(), kind2, kind1) )
 +        else if( !checkScalar(*psrc2, type1, kind2, kind1) )
              CV_Error( CV_StsUnmatchedSizes,
 -                     "The operation is neither 'array op array' (where arrays have the same size and the same number of channels), "
 +                     "The operation is neither 'array op array' "
 +                     "(where arrays have the same size and the same number of channels), "
                       "nor 'array op scalar', nor 'scalar op array'" );
          haveScalar = true;
 -        CV_Assert(src2.type() == CV_64F && (src2.rows == 4 || src2.rows == 1));
 +        CV_Assert(type2 == CV_64F && (sz2.height == 1 || sz2.height == 4));
  
          if (!muldiv)
          {
Simple merge
Simple merge
Simple merge
Simple merge
@@@ -954,10 -954,10 +954,10 @@@ static void log(const Mat& src, Mat& ds
  
  struct ExpOp : public BaseElemWiseOp
  {
-     ExpOp() : BaseElemWiseOp(1, FIX_ALPHA+FIX_BETA+FIX_GAMMA, 1, 1, Scalar::all(0)) {};
+     ExpOp() : BaseElemWiseOp(1, FIX_ALPHA+FIX_BETA+FIX_GAMMA, 1, 1, Scalar::all(0)) {}
      int getRandomType(RNG& rng)
      {
 -        return cvtest::randomType(rng, DEPTH_MASK_FLT, 1, ARITHM_MAX_CHANNELS);
 +        return cvtest::randomType(rng, _OutputArray::DEPTH_MASK_FLT, 1, ARITHM_MAX_CHANNELS);
      }
      void getValueRange(int depth, double& minval, double& maxval)
      {
  
  struct LogOp : public BaseElemWiseOp
  {
-     LogOp() : BaseElemWiseOp(1, FIX_ALPHA+FIX_BETA+FIX_GAMMA, 1, 1, Scalar::all(0)) {};
+     LogOp() : BaseElemWiseOp(1, FIX_ALPHA+FIX_BETA+FIX_GAMMA, 1, 1, Scalar::all(0)) {}
      int getRandomType(RNG& rng)
      {
 -        return cvtest::randomType(rng, DEPTH_MASK_FLT, 1, ARITHM_MAX_CHANNELS);
 +        return cvtest::randomType(rng, _OutputArray::DEPTH_MASK_FLT, 1, ARITHM_MAX_CHANNELS);
      }
      void getValueRange(int depth, double& minval, double& maxval)
      {
index c026ec2,0000000..321250c
mode 100644,000000..100644
--- /dev/null
@@@ -1,135 -1,0 +1,135 @@@
- };
 +/*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*/
 +
 +#include "perf_precomp.hpp"
 +
 +using namespace std;
 +using namespace testing;
 +using namespace perf;
 +
 +////////////////////////////////////////////////////////////////////////////////
 +// MatchTemplate8U
 +
 +CV_ENUM(TemplateMethod, TM_SQDIFF, TM_SQDIFF_NORMED, TM_CCORR, TM_CCORR_NORMED, TM_CCOEFF, TM_CCOEFF_NORMED)
 +
 +DEF_PARAM_TEST(Sz_TemplateSz_Cn_Method, cv::Size, cv::Size, MatCn, TemplateMethod);
 +
 +PERF_TEST_P(Sz_TemplateSz_Cn_Method, MatchTemplate8U,
 +            Combine(CUDA_TYPICAL_MAT_SIZES,
 +                    Values(cv::Size(5, 5), cv::Size(16, 16), cv::Size(30, 30)),
 +                    CUDA_CHANNELS_1_3_4,
 +                    TemplateMethod::all()))
 +{
 +    declare.time(300.0);
 +
 +    const cv::Size size = GET_PARAM(0);
 +    const cv::Size templ_size = GET_PARAM(1);
 +    const int cn = GET_PARAM(2);
 +    const int method = GET_PARAM(3);
 +
 +    cv::Mat image(size, CV_MAKE_TYPE(CV_8U, cn));
 +    cv::Mat templ(templ_size, CV_MAKE_TYPE(CV_8U, cn));
 +    declare.in(image, templ, WARMUP_RNG);
 +
 +    if (PERF_RUN_CUDA())
 +    {
 +        const cv::cuda::GpuMat d_image(image);
 +        const cv::cuda::GpuMat d_templ(templ);
 +        cv::cuda::GpuMat dst;
 +
 +        cv::Ptr<cv::cuda::TemplateMatching> alg = cv::cuda::createTemplateMatching(image.type(), method);
 +
 +        TEST_CYCLE() alg->match(d_image, d_templ, dst);
 +
 +        CUDA_SANITY_CHECK(dst, 1e-5, ERROR_RELATIVE);
 +    }
 +    else
 +    {
 +        cv::Mat dst;
 +
 +        TEST_CYCLE() cv::matchTemplate(image, templ, dst, method);
 +
 +        CPU_SANITY_CHECK(dst);
 +    }
++}
 +
 +////////////////////////////////////////////////////////////////////////////////
 +// MatchTemplate32F
 +
 +PERF_TEST_P(Sz_TemplateSz_Cn_Method, MatchTemplate32F,
 +            Combine(CUDA_TYPICAL_MAT_SIZES,
 +                    Values(cv::Size(5, 5), cv::Size(16, 16), cv::Size(30, 30)),
 +                    CUDA_CHANNELS_1_3_4,
 +                    Values(TemplateMethod(cv::TM_SQDIFF), TemplateMethod(cv::TM_CCORR))))
 +{
 +    declare.time(300.0);
 +
 +    const cv::Size size = GET_PARAM(0);
 +    const cv::Size templ_size = GET_PARAM(1);
 +    const int cn = GET_PARAM(2);
 +    int method = GET_PARAM(3);
 +
 +    cv::Mat image(size, CV_MAKE_TYPE(CV_32F, cn));
 +    cv::Mat templ(templ_size, CV_MAKE_TYPE(CV_32F, cn));
 +    declare.in(image, templ, WARMUP_RNG);
 +
 +    if (PERF_RUN_CUDA())
 +    {
 +        const cv::cuda::GpuMat d_image(image);
 +        const cv::cuda::GpuMat d_templ(templ);
 +        cv::cuda::GpuMat dst;
 +
 +        cv::Ptr<cv::cuda::TemplateMatching> alg = cv::cuda::createTemplateMatching(image.type(), method);
 +
 +        TEST_CYCLE() alg->match(d_image, d_templ, dst);
 +
 +        CUDA_SANITY_CHECK(dst, 1e-6, ERROR_RELATIVE);
 +    }
 +    else
 +    {
 +        cv::Mat dst;
 +
 +        TEST_CYCLE() cv::matchTemplate(image, templ, dst, method);
 +
 +        CPU_SANITY_CHECK(dst);
 +    }
 +}
@@@ -69,8 -70,12 +69,8 @@@ CV_INIT_ALGORITHM(BriefDescriptorExtrac
  
  CV_INIT_ALGORITHM(FastFeatureDetector, "Feature2D.FAST",
                    obj.info()->addParam(obj, "threshold", obj.threshold);
 -                  obj.info()->addParam(obj, "nonmaxSuppression", obj.nonmaxSuppression))
 -
 -CV_INIT_ALGORITHM(FastFeatureDetector2, "Feature2D.FASTX",
 -                  obj.info()->addParam(obj, "threshold", obj.threshold);
                    obj.info()->addParam(obj, "nonmaxSuppression", obj.nonmaxSuppression);
-                   obj.info()->addParam(obj, "type", obj.type));
+                   obj.info()->addParam(obj, "type", obj.type))
  
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////
  
Simple merge
Simple merge
Simple merge
@@@ -8,10 -8,10 +8,10 @@@ using std::tr1::make_tuple
  using std::tr1::get;
  
  
- CV_ENUM(BorderMode, BORDER_CONSTANT, BORDER_REPLICATE, BORDER_REFLECT_101);
+ CV_ENUM(BorderMode, BORDER_CONSTANT, BORDER_REPLICATE, BORDER_REFLECT_101)
  
  typedef TestBaseWithParam< tr1::tuple<Size, int, BorderMode> > TestFilter2d;
 -typedef TestBaseWithParam< tr1::tuple<String, int> > Image_KernelSize;
 +typedef TestBaseWithParam< tr1::tuple<string, int> > Image_KernelSize;
  
  PERF_TEST_P( TestFilter2d, Filter2d,
               Combine(
Simple merge
Simple merge
Simple merge
Simple merge
index faf0e96,0000000..d305c33
mode 100644,000000..100644
--- /dev/null
@@@ -1,2210 -1,0 +1,2210 @@@
-             CACHE_ALL     = CACHE_DEBUG | CACHE_RELEASE, // cache opencl binary
 +// This file is part of OpenCV project.
 +// It is subject to the license terms in the LICENSE file found in the top-level directory
 +// of this distribution and at http://opencv.org/license.html.
 +
 +// 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.
 +
 +#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 DeviceType
 +        {
 +            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
 +        };
 +
 +        // these classes contain OpenCL runtime information
 +
 +        struct PlatformInfo;
 +
 +        struct DeviceInfo
 +        {
 +        public:
 +            int _id; // reserved, don't use it
 +
 +            DeviceType deviceType;
 +            std::string deviceProfile;
 +            std::string deviceVersion;
 +            std::string deviceName;
 +            std::string deviceVendor;
 +            int deviceVendorId;
 +            std::string deviceDriverVersion;
 +            std::string deviceExtensions;
 +
 +            size_t maxWorkGroupSize;
 +            std::vector<size_t> maxWorkItemSizes;
 +            int maxComputeUnits;
 +            size_t localMemorySize;
 +            size_t maxMemAllocSize;
 +
 +            int deviceVersionMajor;
 +            int deviceVersionMinor;
 +
 +            bool haveDoubleSupport;
 +            bool isUnifiedMemory; // 1 means integrated GPU, otherwise this value is 0
 +            bool isIntelDevice;
 +
 +            std::string compilationExtraOptions;
 +
 +            const PlatformInfo* platform;
 +
 +            DeviceInfo();
 +            ~DeviceInfo();
 +        };
 +
 +        struct PlatformInfo
 +        {
 +            int _id; // reserved, don't use it
 +
 +            std::string platformProfile;
 +            std::string platformVersion;
 +            std::string platformName;
 +            std::string platformVendor;
 +            std::string platformExtensons;
 +
 +            int platformVersionMajor;
 +            int platformVersionMinor;
 +
 +            std::vector<const DeviceInfo*> devices;
 +
 +            PlatformInfo();
 +            ~PlatformInfo();
 +        };
 +
 +        //////////////////////////////// Initialization & Info ////////////////////////
 +        typedef std::vector<const PlatformInfo*> PlatformsInfo;
 +
 +        CV_EXPORTS int getOpenCLPlatforms(PlatformsInfo& platforms);
 +
 +        typedef std::vector<const DeviceInfo*> DevicesInfo;
 +
 +        CV_EXPORTS int getOpenCLDevices(DevicesInfo& devices, int deviceType = CVCL_DEVICE_TYPE_GPU,
 +                const PlatformInfo* platform = NULL);
 +
 +        // set device you want to use
 +        CV_EXPORTS void setDevice(const DeviceInfo* info);
 +
 +        // Initialize from OpenCL handles directly.
 +        // Argument types is (pointers): cl_platform_id*, cl_context*, cl_device_id*
 +        CV_EXPORTS void initializeContext(void* pClPlatform, void* pClContext, void* pClDevice);
 +
 +        enum FEATURE_TYPE
 +        {
 +            FEATURE_CL_DOUBLE = 1,
 +            FEATURE_CL_UNIFIED_MEM,
 +            FEATURE_CL_VER_1_2,
 +            FEATURE_CL_INTEL_DEVICE
 +        };
 +
 +        // Represents OpenCL context, interface
 +        class CV_EXPORTS Context
 +        {
 +        protected:
 +            Context() { }
 +            ~Context() { }
 +        public:
 +            static Context *getContext();
 +
 +            bool supportsFeature(FEATURE_TYPE featureType) const;
 +            const DeviceInfo& getDeviceInfo() const;
 +
 +            const void* getOpenCLContextPtr() const;
 +            const void* getOpenCLCommandQueuePtr() const;
 +            const void* getOpenCLDeviceIDPtr() const;
 +        };
 +
 +        inline const void *getClContextPtr()
 +        {
 +            return Context::getContext()->getOpenCLContextPtr();
 +        }
 +
 +        inline const void *getClCommandQueuePtr()
 +        {
 +            return Context::getContext()->getOpenCLCommandQueuePtr();
 +        }
 +
 +        CV_EXPORTS bool supportsFeature(FEATURE_TYPE featureType);
 +
 +        CV_EXPORTS void finish();
 +
 +        enum BINARY_CACHE_MODE
 +        {
 +            CACHE_NONE    = 0,        // do not cache OpenCL binary
 +            CACHE_DEBUG   = 0x1 << 0, // cache OpenCL binary when built in debug mode
 +            CACHE_RELEASE = 0x1 << 1, // default behavior, only cache when built in release mode
++            CACHE_ALL     = CACHE_DEBUG | CACHE_RELEASE // cache opencl binary
 +        };
 +        //! 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.
 +        //
 +        // This feature is enabled by default.
 +        CV_EXPORTS void setBinaryDiskCache(int mode = CACHE_RELEASE, cv::String path = "./");
 +
 +        //! set where binary cache to be saved to
 +        CV_EXPORTS void setBinaryPath(const char *path);
 +
 +        struct ProgramSource
 +        {
 +            const char* name;
 +            const char* programStr;
 +            const char* programHash;
 +
 +            // Cache in memory by name (should be unique). Caching on disk disabled.
 +            inline ProgramSource(const char* _name, const char* _programStr)
 +                : name(_name), programStr(_programStr), programHash(NULL)
 +            {
 +            }
 +
 +            // Cache in memory by name (should be unique). Caching on disk uses programHash mark.
 +            inline ProgramSource(const char* _name, const char* _programStr, const char* _programHash)
 +                : name(_name), programStr(_programStr), programHash(_programHash)
 +            {
 +            }
 +        };
 +
 +        //! Calls OpenCL kernel. Pass globalThreads = NULL, and cleanUp = true, to finally clean-up without executing.
 +        //! Deprecated, will be replaced
 +        CV_EXPORTS void openCLExecuteKernelInterop(Context *clCxt,
 +                const cv::ocl::ProgramSource& 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);
 +
 +        class CV_EXPORTS oclMatExpr;
 +        //////////////////////////////// oclMat ////////////////////////////////
 +        class CV_EXPORTS oclMat
 +        {
 +        public:
 +            //! default constructor
 +            oclMat();
 +            //! constructs oclMatrix of the specified size and type (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
 +            oclMat(int rows, int cols, int type);
 +            oclMat(Size size, int type);
 +            //! constucts oclMatrix and fills it with the specified value _s.
 +            oclMat(int rows, int cols, int type, const Scalar &s);
 +            oclMat(Size size, int type, const Scalar &s);
 +            //! copy constructor
 +            oclMat(const oclMat &m);
 +
 +            //! constructor for oclMatrix headers pointing to user-allocated data
 +            oclMat(int rows, int cols, int type, void *data, size_t step = Mat::AUTO_STEP);
 +            oclMat(Size size, int type, void *data, size_t step = Mat::AUTO_STEP);
 +
 +            //! creates a matrix header for a part of the bigger matrix
 +            oclMat(const oclMat &m, const Range &rowRange, const Range &colRange);
 +            oclMat(const oclMat &m, const Rect &roi);
 +
 +            //! builds oclMat from Mat. Perfom blocking upload to device.
 +            explicit oclMat (const Mat &m);
 +
 +            //! destructor - calls release()
 +            ~oclMat();
 +
 +            //! assignment operators
 +            oclMat &operator = (const oclMat &m);
 +            //! assignment operator. Perfom blocking upload to device.
 +            oclMat &operator = (const Mat &m);
 +            oclMat &operator = (const oclMatExpr& expr);
 +
 +            //! pefroms blocking upload data to oclMat.
 +            void upload(const cv::Mat &m);
 +
 +
 +            //! downloads data from device to host memory. Blocking calls.
 +            operator Mat() const;
 +            void download(cv::Mat &m) const;
 +
 +            //! convert to _InputArray
 +            operator _InputArray();
 +
 +            //! convert to _OutputArray
 +            operator _OutputArray();
 +
 +            //! returns a new oclMatrix header for the specified row
 +            oclMat row(int y) const;
 +            //! returns a new oclMatrix header for the specified column
 +            oclMat col(int x) const;
 +            //! ... for the specified row span
 +            oclMat rowRange(int startrow, int endrow) const;
 +            oclMat rowRange(const Range &r) const;
 +            //! ... for the specified column span
 +            oclMat colRange(int startcol, int endcol) const;
 +            oclMat colRange(const Range &r) const;
 +
 +            //! returns deep copy of the oclMatrix, i.e. the data is copied
 +            oclMat clone() const;
 +
 +            //! copies 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
 +            void copyTo( oclMat &m, const oclMat &mask = oclMat()) const;
 +
 +            //! converts oclMatrix to another datatype with optional scalng. See cvConvertScale.
 +            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
 +            oclMat& operator = (const Scalar &s);
 +            //! sets some of the oclMatrix elements to s, according to the mask
 +            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 createEx(Size size, int type, DevMemRW rw_type,
 +                          DevMemType mem_type);
 +
 +            //! 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;
 +
 +            //! 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; // TODO clCtx
 +            //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 ///////////////////////////////////
 +
 +        //! adds one matrix to another with scale (dst = src1 * alpha + src2 * beta + gama)
 +        // supports all data types
 +        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)
 +        // supports all data types
 +        CV_EXPORTS void multiply(double scalar, const oclMat &src, oclMat &dst);
 +
 +        //! 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);
 +
 +        //! computes element-wise minimum of the two arrays (dst = min(src1, src2))
 +        // supports all data types
 +        CV_EXPORTS void min(const oclMat &src1, const oclMat &src2, oclMat &dst);
 +
 +        //! computes element-wise maximum of the two arrays (dst = max(src1, src2))
 +        // supports all data types
 +        CV_EXPORTS void max(const oclMat &src1, const oclMat &src2, 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
 +        // supports all data types
 +        CV_EXPORTS void transpose(const oclMat &src, oclMat &dst);
 +
 +        //! computes element-wise absolute values of an array (dst = abs(src))
 +        // supports all data types
 +        CV_EXPORTS void abs(const oclMat &src, oclMat &dst);
 +
 +        //! 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 all data types
 +        CV_EXPORTS void meanStdDev(const oclMat &mtx, Scalar &mean, Scalar &stddev);
 +
 +        //! computes norm of array
 +        // supports NORM_INF, NORM_L1, NORM_L2
 +        // supports all data types
 +        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 all data types
 +        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
 +        // 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());
 +
 +        //! finds global minimum and maximum array elements and returns their values with locations
 +        // support all C1 types
 +        CV_EXPORTS void minMaxLoc(const oclMat &src, double *minVal, double *maxVal = 0, Point *minLoc = 0, Point *maxLoc = 0,
 +                                  const oclMat &mask = oclMat());
 +
 +        //! counts non-zero array elements
 +        // support all types
 +        CV_EXPORTS int countNonZero(const oclMat &src);
 +
 +        //! transforms 8-bit unsigned integers using lookup table: dst(i)=lut(src(i))
 +        // destination array will have the depth type as lut and the same channels number as source
 +        //It supports 8UC1 8UC4 only
 +        CV_EXPORTS void LUT(const oclMat &src, const oclMat &lut, oclMat &dst);
 +
 +        //! only 8UC1 and 256 bins is supported now
 +        CV_EXPORTS void calcHist(const oclMat &mat_src, oclMat &mat_hist);
 +        //! only 8UC1 and 256 bins is supported now
 +        CV_EXPORTS void equalizeHist(const oclMat &mat_src, oclMat &mat_dst);
 +
 +        //! only 8UC1 is supported now
 +        CV_EXPORTS Ptr<cv::CLAHE> createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8));
 +
 +        //! bilateralFilter
 +        // supports 8UC1 8UC4
 +        CV_EXPORTS void bilateralFilter(const oclMat& src, oclMat& dst, int d, double sigmaColor, double sigmaSpace, int borderType=BORDER_DEFAULT);
 +
 +        //! Applies an adaptive bilateral filter to the input image
 +        //  Unlike the usual bilateral filter that uses fixed value for sigmaColor,
 +        //  the adaptive version calculates the local variance in he ksize neighborhood
 +        //  and use this as sigmaColor, for the value filtering. However, the local standard deviation is
 +        //  clamped to the maxSigmaColor.
 +        //  supports 8UC1, 8UC3
 +        CV_EXPORTS void adaptiveBilateralFilter(const oclMat& src, oclMat& dst, Size ksize, double sigmaSpace, double maxSigmaColor=20.0, Point anchor = Point(-1, -1), int borderType=BORDER_DEFAULT);
 +
 +        //! 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);
 +
 +        //! 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 square root of each matrix element
 +        // supports only CV_32FC1, CV_64FC1 type
 +        CV_EXPORTS void sqrt(const oclMat &src, oclMat &dst);
 +
 +        //! computes magnitude of each (x(i), y(i)) vector
 +        // supports only CV_32F, CV_64F type
 +        CV_EXPORTS void magnitude(const oclMat &x, const oclMat &y, oclMat &magnitude);
 +
 +        //! computes angle (angle(i)) of each (x(i), y(i)) vector
 +        // supports only CV_32F, CV_64F type
 +        CV_EXPORTS void phase(const oclMat &x, const oclMat &y, oclMat &angle, bool angleInDegrees = false);
 +
 +        //! the function raises every element of tne input array to p
 +        // support only CV_32F, CV_64F type
 +        CV_EXPORTS void pow(const oclMat &x, double p, oclMat &y);
 +
 +        //! converts Cartesian coordinates to polar
 +        // supports only CV_32F CV_64F type
 +        CV_EXPORTS void cartToPolar(const oclMat &x, const oclMat &y, oclMat &magnitude, oclMat &angle, bool angleInDegrees = false);
 +
 +        //! converts polar coordinates to Cartesian
 +        // supports only CV_32F CV_64F type
 +        CV_EXPORTS void polarToCart(const oclMat &magnitude, const oclMat &angle, oclMat &x, oclMat &y, bool angleInDegrees = false);
 +
 +        //! perfroms per-elements bit-wise inversion
 +        // supports all types
 +        CV_EXPORTS void bitwise_not(const oclMat &src, oclMat &dst);
 +
 +        //! calculates per-element bit-wise disjunction of two arrays
 +        // supports all types
 +        CV_EXPORTS void bitwise_or(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask = oclMat());
 +        CV_EXPORTS void bitwise_or(const oclMat &src1, const Scalar &s, oclMat &dst, const oclMat &mask = oclMat());
 +
 +        //! calculates per-element bit-wise conjunction of two arrays
 +        // supports all types
 +        CV_EXPORTS void bitwise_and(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask = oclMat());
 +        CV_EXPORTS void bitwise_and(const oclMat &src1, const Scalar &s, oclMat &dst, const oclMat &mask = oclMat());
 +
 +        //! calculates per-element bit-wise "exclusive or" operation
 +        // supports all types
 +        CV_EXPORTS void bitwise_xor(const oclMat &src1, const oclMat &src2, oclMat &dst, const oclMat &mask = oclMat());
 +        CV_EXPORTS void bitwise_xor(const oclMat &src1, const Scalar &s, oclMat &dst, const oclMat &mask = oclMat());
 +
 +        //! Logical operators
 +        CV_EXPORTS oclMat operator ~ (const oclMat &);
 +        CV_EXPORTS oclMat operator | (const oclMat &, const oclMat &);
 +        CV_EXPORTS oclMat operator & (const oclMat &, const oclMat &);
 +        CV_EXPORTS oclMat operator ^ (const oclMat &, const oclMat &);
 +
 +
 +        //! Mathematics operators
 +        CV_EXPORTS oclMatExpr operator + (const oclMat &src1, const oclMat &src2);
 +        CV_EXPORTS oclMatExpr operator - (const oclMat &src1, const oclMat &src2);
 +        CV_EXPORTS oclMatExpr operator * (const oclMat &src1, const oclMat &src2);
 +        CV_EXPORTS oclMatExpr operator / (const oclMat &src1, const oclMat &src2);
 +
 +        struct CV_EXPORTS ConvolveBuf
 +        {
 +            Size result_size;
 +            Size block_size;
 +            Size user_block_size;
 +            Size dft_size;
 +
 +            oclMat image_spect, templ_spect, result_spect;
 +            oclMat image_block, templ_block, result_data;
 +
 +            void create(Size image_size, Size templ_size);
 +            static Size estimateBlockSize(Size result_size, Size templ_size);
 +        };
 +
 +        //! computes convolution of two images, may use discrete Fourier transform
 +        // support only CV_32FC1 type
 +        CV_EXPORTS void convolve(const oclMat &image, const oclMat &temp1, oclMat &result, bool ccorr = false);
 +        CV_EXPORTS void convolve(const oclMat &image, const oclMat &temp1, oclMat &result, bool ccorr, ConvolveBuf& buf);
 +
 +        //! Performs a per-element multiplication of two Fourier spectrums.
 +        //! Only full (not packed) CV_32FC2 complex spectrums in the interleaved format are supported for now.
 +        //! support only CV_32FC2 type
 +        CV_EXPORTS void mulSpectrums(const oclMat &a, const oclMat &b, oclMat &c, int flags, float scale, bool conjB = false);
 +
 +        CV_EXPORTS void cvtColor(const oclMat &src, oclMat &dst, int code, int dcn = 0);
 +
 +        //! initializes a scaled identity matrix
 +        CV_EXPORTS void setIdentity(oclMat& src, const Scalar & val = Scalar(1));
 +
 +        //! fills the output array with repeated copies of the input array
 +        CV_EXPORTS void repeat(const oclMat & src, int ny, int nx, oclMat & dst);
 +
 +        //////////////////////////////// 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, Size imgSize = Size(-1,-1));
 +
 +        //! 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, Size imgSize = Size(-1,-1));
 +
 +        //! 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, Size imgSize = Size(-1,-1) );
 +
 +        //! applies Laplacian operator to the image
 +        // supports only ksize = 1 and ksize = 3
 +        CV_EXPORTS void Laplacian(const oclMat &src, oclMat &dst, int ddepth, int ksize = 1, double scale = 1,
 +                double delta=0, int borderType=BORDER_DEFAULT);
 +
 +        //! returns 2D box filter
 +        // 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: dst type must be the same as source type
 +        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
 +        // supports: dst type must be the same as source type
 +        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
 +        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
 +        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
 +        CV_EXPORTS void filter2D(const oclMat &src, oclMat &dst, int ddepth, const Mat &kernel,
 +                                 Point anchor = Point(-1, -1), double delta = 0.0, 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. m should be 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 support CV_32S, CV_32F, sqsum - support CV32F, CV_64F
 +        // supports only CV_8UC1 source type
 +        CV_EXPORTS void integral(const oclMat &src, oclMat &sum, oclMat &sqsum, int sdepth=-1 );
 +        CV_EXPORTS void integral(const oclMat &src, oclMat &sum, int sdepth=-1 );
 +        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
 +        // supports NORM_L1 and NORM_L2 distType
 +        // if indices is provided, only the indexed rows will be calculated and their results are in the same
 +        // order of indices
 +        CV_EXPORTS void distanceToCenters(const oclMat &src, const oclMat &centers, Mat &dists, Mat &labels, int distType = NORM_L2SQR);
 +
 +        //!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(1, 1, CV_32S) { }
 +            ~CannyBuf()
 +            {
 +                release();
 +            }
 +            explicit CannyBuf(const Size &image_size, int apperture_size = 3) : counter(1, 1, CV_32S)
 +            {
 +                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;
 +            oclMat 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 eig_minmax_;
 +            oclMat minMaxbuf_;
 +            oclMat tmpCorners_;
 +            oclMat counter_;
 +        };
 +
 +        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_;
 +        }
 +
 +        ////////////////////////////////// FAST Feature Detector //////////////////////////////////
 +        class CV_EXPORTS FAST_OCL
 +        {
 +        public:
 +            enum
 +            {
 +                X_ROW = 0,
 +                Y_ROW,
 +                RESPONSE_ROW,
 +                ROWS_COUNT
 +            };
 +
 +            // all features have same size
 +            static const int FEATURE_SIZE = 7;
 +
 +            explicit FAST_OCL(int threshold, bool nonmaxSupression = true, double keypointsRatio = 0.05);
 +
 +            //! finds the keypoints using FAST detector
 +            //! supports only CV_8UC1 images
 +            void operator ()(const oclMat& image, const oclMat& mask, oclMat& keypoints);
 +            void operator ()(const oclMat& image, const oclMat& mask, std::vector<KeyPoint>& keypoints);
 +
 +            //! download keypoints from device to host memory
 +            static void downloadKeypoints(const oclMat& d_keypoints, std::vector<KeyPoint>& keypoints);
 +
 +            //! convert keypoints to KeyPoint vector
 +            static void convertKeypoints(const Mat& h_keypoints, std::vector<KeyPoint>& keypoints);
 +
 +            //! release temporary buffer's memory
 +            void release();
 +
 +            bool nonmaxSupression;
 +
 +            int threshold;
 +
 +            //! max keypoints = keypointsRatio * img.size().area()
 +            double keypointsRatio;
 +
 +            //! find keypoints and compute it's response if nonmaxSupression is true
 +            //! return count of detected keypoints
 +            int calcKeyPointsLocation(const oclMat& image, const oclMat& mask);
 +
 +            //! get final array of keypoints
 +            //! performs nonmax supression if needed
 +            //! return final count of keypoints
 +            int getKeyPoints(oclMat& keypoints);
 +
 +        private:
 +            oclMat kpLoc_;
 +            int count_;
 +
 +            oclMat score_;
 +
 +            oclMat d_keypoints_;
 +
 +            int calcKeypointsOCL(const oclMat& img, const oclMat& mask, int maxKeypoints);
 +            int nonmaxSupressionOCL(oclMat& keypoints);
 +        };
 +
 +        ////////////////////////////////// ORB Descriptor Extractor //////////////////////////////////
 +        class CV_EXPORTS ORB_OCL
 +        {
 +        public:
 +            enum
 +            {
 +                X_ROW = 0,
 +                Y_ROW,
 +                RESPONSE_ROW,
 +                ANGLE_ROW,
 +                OCTAVE_ROW,
 +                SIZE_ROW,
 +                ROWS_COUNT
 +            };
 +
 +            enum
 +            {
 +                DEFAULT_FAST_THRESHOLD = 20
 +            };
 +
 +            //! Constructor
 +            explicit ORB_OCL(int nFeatures = 500, float scaleFactor = 1.2f, int nLevels = 8, int edgeThreshold = 31,
 +                             int firstLevel = 0, int WTA_K = 2, int scoreType = 0, int patchSize = 31);
 +
 +            //! Compute the ORB features on an image
 +            //! image - the image to compute the features (supports only CV_8UC1 images)
 +            //! mask - the mask to apply
 +            //! keypoints - the resulting keypoints
 +            void operator ()(const oclMat& image, const oclMat& mask, std::vector<KeyPoint>& keypoints);
 +            void operator ()(const oclMat& image, const oclMat& mask, oclMat& keypoints);
 +
 +            //! Compute the ORB features and descriptors on an image
 +            //! image - the image to compute the features (supports only CV_8UC1 images)
 +            //! mask - the mask to apply
 +            //! keypoints - the resulting keypoints
 +            //! descriptors - descriptors array
 +            void operator ()(const oclMat& image, const oclMat& mask, std::vector<KeyPoint>& keypoints, oclMat& descriptors);
 +            void operator ()(const oclMat& image, const oclMat& mask, oclMat& keypoints, oclMat& descriptors);
 +
 +            //! download keypoints from device to host memory
 +            static void downloadKeyPoints(const oclMat& d_keypoints, std::vector<KeyPoint>& keypoints);
 +            //! convert keypoints to KeyPoint vector
 +            static void convertKeyPoints(const Mat& d_keypoints, std::vector<KeyPoint>& keypoints);
 +
 +            //! returns the descriptor size in bytes
 +            inline int descriptorSize() const { return kBytes; }
 +            inline int descriptorType() const { return CV_8U; }
 +            inline int defaultNorm() const { return NORM_HAMMING; }
 +
 +            inline void setFastParams(int threshold, bool nonmaxSupression = true)
 +            {
 +                fastDetector_.threshold = threshold;
 +                fastDetector_.nonmaxSupression = nonmaxSupression;
 +            }
 +
 +            //! release temporary buffer's memory
 +            void release();
 +
 +            //! if true, image will be blurred before descriptors calculation
 +            bool blurForDescriptor;
 +
 +        private:
 +            enum { kBytes = 32 };
 +
 +            void buildScalePyramids(const oclMat& image, const oclMat& mask);
 +
 +            void computeKeyPointsPyramid();
 +
 +            void computeDescriptors(oclMat& descriptors);
 +
 +            void mergeKeyPoints(oclMat& keypoints);
 +
 +            int nFeatures_;
 +            float scaleFactor_;
 +            int nLevels_;
 +            int edgeThreshold_;
 +            int firstLevel_;
 +            int WTA_K_;
 +            int scoreType_;
 +            int patchSize_;
 +
 +            // The number of desired features per scale
 +            std::vector<size_t> n_features_per_level_;
 +
 +            // Points to compute BRIEF descriptors from
 +            oclMat pattern_;
 +
 +            std::vector<oclMat> imagePyr_;
 +            std::vector<oclMat> maskPyr_;
 +
 +            oclMat buf_;
 +
 +            std::vector<oclMat> keyPointsPyr_;
 +            std::vector<int> keyPointsCount_;
 +
 +            FAST_OCL fastDetector_;
 +
 +            Ptr<ocl::FilterEngine_GPU> blurFilter;
 +
 +            oclMat d_keypoints_;
 +
 +            oclMat uMax_;
 +        };
 +
 +        /////////////////////////////// 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
 +        //! _array should be a vector a points standing for the contour
 +        CV_EXPORTS Moments ocl_moments(InputArray contour);
 +        //! src should be a general image uploaded to the GPU.
 +        //! the supported oclMat type are CV_8UC1, CV_16UC1, CV_16SC1, CV_32FC1 and CV_64FC1
 +        //! to use type of CV_64FC1, the GPU should support CV_64FC1
 +        CV_EXPORTS Moments ocl_moments(oclMat& src, bool binary);
 +
 +        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)
 +        CV_EXPORTS void 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;
 +        };
 +
 +        /*!***************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__ */
@@@ -178,11 -180,17 +178,11 @@@ INSTANTIATE_TEST_CASE_P(OCL_ObjDetect, 
                              testing::Values(Size(64, 128), Size(48, 96)),
                              testing::Values(MatType(CV_8UC1), MatType(CV_8UC4))));
  
 +
  ///////////////////////////// Haar //////////////////////////////
- IMPLEMENT_PARAM_CLASS(CascadeName, std::string);
+ IMPLEMENT_PARAM_CLASS(CascadeName, std::string)
  CascadeName cascade_frontalface_alt(std::string("haarcascade_frontalface_alt.xml"));
  CascadeName cascade_frontalface_alt2(std::string("haarcascade_frontalface_alt2.xml"));
 -struct getRect
 -{
 -    Rect operator ()(const CvAvgComp &e) const
 -    {
 -        return e.rect;
 -    }
 -};
  
  PARAM_TEST_CASE(Haar, int, CascadeName)
  {
Simple merge
Simple merge
Simple merge
@@@ -472,9 -471,9 +472,9 @@@ namespac
                        obj.info()->addParam(obj, "scaleFactor", obj.scaleFactor_, false, 0, 0, "Pyramid scale factor");
                        obj.info()->addParam(obj, "innerIterations", obj.innerIterations_, false, 0, 0, "Number of lagged non-linearity iterations (inner loop)");
                        obj.info()->addParam(obj, "outerIterations", obj.outerIterations_, false, 0, 0, "Number of warping iterations (number of pyramid levels)");
-                       obj.info()->addParam(obj, "solverIterations", obj.solverIterations_, false, 0, 0, "Number of linear system solver iterations"));
+                       obj.info()->addParam(obj, "solverIterations", obj.solverIterations_, false, 0, 0, "Number of linear system solver iterations"))
  
 -    Brox_GPU::Brox_GPU() : GpuOpticalFlow(CV_32FC1), alg_(0.197f, 50.0f, 0.8f, 10, 77, 10)
 +    Brox_CUDA::Brox_CUDA() : GpuOpticalFlow(CV_32FC1), alg_(0.197f, 50.0f, 0.8f, 10, 77, 10)
      {
          alpha_ = alg_.alpha;
          gamma_ = alg_.gamma;
@@@ -533,12 -532,12 +533,12 @@@ namespac
          PyrLKOpticalFlow alg_;
      };
  
 -    CV_INIT_ALGORITHM(PyrLK_GPU, "DenseOpticalFlowExt.PyrLK_GPU",
 +    CV_INIT_ALGORITHM(PyrLK_CUDA, "DenseOpticalFlowExt.PyrLK_CUDA",
                        obj.info()->addParam(obj, "winSize", obj.winSize_);
                        obj.info()->addParam(obj, "maxLevel", obj.maxLevel_);
-                       obj.info()->addParam(obj, "iterations", obj.iterations_));
+                       obj.info()->addParam(obj, "iterations", obj.iterations_))
  
 -    PyrLK_GPU::PyrLK_GPU() : GpuOpticalFlow(CV_8UC1)
 +    PyrLK_CUDA::PyrLK_CUDA() : GpuOpticalFlow(CV_8UC1)
      {
          winSize_ = alg_.winSize.width;
          maxLevel_ = alg_.maxLevel;
@@@ -603,9 -602,9 +603,9 @@@ namespac
                        obj.info()->addParam(obj, "numIters", obj.numIters_);
                        obj.info()->addParam(obj, "polyN", obj.polyN_);
                        obj.info()->addParam(obj, "polySigma", obj.polySigma_);
-                       obj.info()->addParam(obj, "flags", obj.flags_));
+                       obj.info()->addParam(obj, "flags", obj.flags_))
  
 -    Farneback_GPU::Farneback_GPU() : GpuOpticalFlow(CV_8UC1)
 +    Farneback_CUDA::Farneback_CUDA() : GpuOpticalFlow(CV_8UC1)
      {
          pyrScale_ = alg_.pyrScale;
          numLevels_ = alg_.numLevels;
@@@ -679,9 -678,9 +679,9 @@@ namespac
                        obj.info()->addParam(obj, "warps", obj.warps_);
                        obj.info()->addParam(obj, "epsilon", obj.epsilon_);
                        obj.info()->addParam(obj, "iterations", obj.iterations_);
-                       obj.info()->addParam(obj, "useInitialFlow", obj.useInitialFlow_));
+                       obj.info()->addParam(obj, "useInitialFlow", obj.useInitialFlow_))
  
 -    DualTVL1_GPU::DualTVL1_GPU() : GpuOpticalFlow(CV_8UC1)
 +    DualTVL1_CUDA::DualTVL1_CUDA() : GpuOpticalFlow(CV_8UC1)
      {
          tau_ = alg_.tau;
          lambda_ = alg_.lambda;
@@@ -251,9 -257,8 +251,9 @@@ typedef struct CV_EXPORTS performance_m
  \*****************************************************************************************/
  enum PERF_STRATEGY
  {
 +    PERF_STRATEGY_DEFAULT = -1,
      PERF_STRATEGY_BASE = 0,
-     PERF_STRATEGY_SIMPLE = 1,
+     PERF_STRATEGY_SIMPLE = 1
  };
  
  
Simple merge
@@@ -937,17 -924,11 +937,17 @@@ CV_INIT_ALGORITHM(OpticalFlowDual_TVL1
                                         "Number of scales used to create the pyramid of images");
                    obj.info()->addParam(obj, "warps", obj.warps, false, 0, 0,
                                         "Number of warpings per scale");
 +                  obj.info()->addParam(obj, "medianFiltering", obj.medianFiltering, false, 0, 0,
 +                                       "Median filter kernel size (1 = no filter) (3 or 5)");
 +                  obj.info()->addParam(obj, "scaleStep", obj.scaleStep, false, 0, 0,
 +                                       "Step between scales (<1)");
                    obj.info()->addParam(obj, "epsilon", obj.epsilon, false, 0, 0,
                                         "Stopping criterion threshold used in the numerical scheme, which is a trade-off between precision and running time");
 -                  obj.info()->addParam(obj, "iterations", obj.iterations, false, 0, 0,
 -                                       "Stopping criterion iterations number used in the numerical scheme");
 +                  obj.info()->addParam(obj, "innerIterations", obj.innerIterations, false, 0, 0,
 +                                       "inner iterations (between outlier filtering) used in the numerical scheme");
 +                  obj.info()->addParam(obj, "outerIterations", obj.outerIterations, false, 0, 0,
 +                                       "outer iterations (number of inner loops) used in the numerical scheme");
-                   obj.info()->addParam(obj, "useInitialFlow", obj.useInitialFlow));
+                   obj.info()->addParam(obj, "useInitialFlow", obj.useInitialFlow))
  
  } // namespace
  
Simple merge
Simple merge