Merge branch '2.4'
authorAndrey Kamaev <andrey.kamaev@itseez.com>
Fri, 29 Mar 2013 14:48:06 +0000 (18:48 +0400)
committerAndrey Kamaev <andrey.kamaev@itseez.com>
Fri, 29 Mar 2013 15:38:35 +0000 (19:38 +0400)
103 files changed:
1  2 
CMakeLists.txt
cmake/OpenCVFindLibsGrfmt.cmake
cmake/OpenCVModule.cmake
doc/tutorials/introduction/windows_visual_studio_image_watch/windows_visual_studio_image_watch.rst
modules/core/include/opencv2/core/cuda_devptrs.hpp
modules/core/include/opencv2/core/gpumat.hpp
modules/core/include/opencv2/core/opengl.hpp
modules/core/include/opencv2/core/operations.hpp
modules/core/include/opencv2/core/stream_accessor.hpp
modules/core/src/gl_core_3_1.cpp
modules/core/test/test_io.cpp
modules/gpu/CMakeLists.txt
modules/gpu/include/opencv2/gpu.hpp
modules/gpu/include/opencv2/gpu/gpu.hpp
modules/gpu/perf/perf_calib3d.cpp
modules/gpu/perf/perf_precomp.hpp
modules/gpu/perf/perf_video.cpp
modules/gpu/perf4au/main.cpp
modules/gpu/src/arithm.cpp
modules/gpu/src/bilateral_filter.cpp
modules/gpu/src/blend.cpp
modules/gpu/src/brute_force_matcher.cpp
modules/gpu/src/cascadeclassifier.cpp
modules/gpu/src/cu_safe_call.cpp
modules/gpu/src/cu_safe_call.h
modules/gpu/src/cuda/bilateral_filter.cu
modules/gpu/src/cuda/blend.cu
modules/gpu/src/cuda/integral_image.cu
modules/gpu/src/cuda/lbp.hpp
modules/gpu/src/cuda/split_merge.cu
modules/gpu/src/cuda/stereobp.cu
modules/gpu/src/cuvid_video_source.cpp
modules/gpu/src/cuvid_video_source.h
modules/gpu/src/error.cpp
modules/gpu/src/fast.cpp
modules/gpu/src/ffmpeg_video_source.cpp
modules/gpu/src/ffmpeg_video_source.h
modules/gpu/src/gftt.cpp
modules/gpu/src/global_motion.cpp
modules/gpu/src/hog.cpp
modules/gpu/src/imgproc.cpp
modules/gpu/src/matrix_reductions.cpp
modules/gpu/src/mssegmentation.cpp
modules/gpu/src/nvidia/NCVHaarObjectDetection.cu
modules/gpu/src/nvidia/NCVHaarObjectDetection.hpp
modules/gpu/src/nvidia/core/NCV.cu
modules/gpu/src/nvidia/core/NCV.hpp
modules/gpu/src/optical_flow.cpp
modules/gpu/src/optical_flow_farneback.cpp
modules/gpu/src/orb.cpp
modules/gpu/src/precomp.hpp
modules/gpu/src/pyrlk.cpp
modules/gpu/src/speckle_filtering.cpp
modules/gpu/src/split_merge.cpp
modules/gpu/src/stereobp.cpp
modules/gpu/src/stereocsbp.cpp
modules/gpu/src/tvl1flow.cpp
modules/gpu/src/video_reader.cpp
modules/gpu/test/interpolation.hpp
modules/gpu/test/main.cpp
modules/gpu/test/nvidia/NCVTestSourceProvider.hpp
modules/gpu/test/nvidia/main_nvidia.cpp
modules/gpu/test/test_bgfg.cpp
modules/gpu/test/test_precomp.hpp
modules/gpu/test/test_stream.cpp
modules/imgproc/include/opencv2/imgproc.hpp
modules/imgproc/include/opencv2/imgproc/imgproc.hpp
modules/imgproc/src/histogram.cpp
modules/java/generator/src/cpp/features2d_manual.hpp
modules/ml/src/svm.cpp
modules/ml/test/test_mltests2.cpp
modules/nonfree/include/opencv2/nonfree/gpu.hpp
modules/nonfree/perf/perf_gpu.cpp
modules/nonfree/perf/perf_precomp.hpp
modules/nonfree/src/opencl/surf.cl
modules/nonfree/src/surf.ocl.cpp
modules/nonfree/src/surf_gpu.cpp
modules/ocl/include/opencv2/ocl/private/util.hpp
modules/ocl/src/brute_force_matcher.cpp
modules/ocl/src/canny.cpp
modules/ocl/src/haar.cpp
modules/ocl/src/initialization.cpp
modules/ocl/src/match_template.cpp
modules/ocl/src/moments.cpp
modules/ocl/src/opencl/haarobjectdetect.cl
modules/ocl/src/opencl/moments.cl
modules/superres/include/opencv2/superres.hpp
modules/superres/include/opencv2/superres/optical_flow.hpp
modules/superres/perf/perf_precomp.hpp
modules/superres/src/btv_l1.cpp
modules/superres/src/btv_l1_gpu.cpp
modules/superres/src/frame_source.cpp
modules/superres/src/input_array_utility.cpp
modules/superres/src/input_array_utility.hpp
modules/superres/src/optical_flow.cpp
modules/superres/src/precomp.hpp
modules/superres/src/super_resolution.cpp
modules/superres/test/test_precomp.hpp
modules/ts/include/opencv2/ts/gpu_perf.hpp
modules/ts/include/opencv2/ts/gpu_test.hpp
modules/ts/src/gpu_perf.cpp
modules/world/CMakeLists.txt
samples/cpp/CMakeLists.txt

diff --cc CMakeLists.txt
@@@ -120,12 -120,11 +120,12 @@@ OCV_OPTION(WITH_NVCUVID        "Includ
  OCV_OPTION(WITH_EIGEN          "Include Eigen2/Eigen3 support"               ON)
  OCV_OPTION(WITH_FFMPEG         "Include FFMPEG support"                      ON   IF (NOT ANDROID AND NOT IOS))
  OCV_OPTION(WITH_GSTREAMER      "Include Gstreamer support"                   ON   IF (UNIX AND NOT APPLE AND NOT ANDROID) )
 +OCV_OPTION(WITH_GSTREAMER_1_X  "Include Gstreamer 1.x support"               OFF)
  OCV_OPTION(WITH_GTK            "Include GTK support"                         ON   IF (UNIX AND NOT APPLE AND NOT ANDROID) )
 -OCV_OPTION(WITH_IMAGEIO        "ImageIO support for OS X"                    OFF  IF APPLE)
  OCV_OPTION(WITH_IPP            "Include Intel IPP support"                   OFF  IF (MSVC OR X86 OR X86_64) )
  OCV_OPTION(WITH_JASPER         "Include JPEG2K support"                      ON   IF (NOT IOS) )
- OCV_OPTION(WITH_JPEG           "Include JPEG support"                        ON   IF (NOT IOS) )
+ OCV_OPTION(WITH_JPEG           "Include JPEG support"                        ON)
 +OCV_OPTION(WITH_WEBP           "Include WebP support"                        ON   IF (NOT IOS) )
  OCV_OPTION(WITH_OPENEXR        "Include ILM support via OpenEXR"             ON   IF (NOT IOS) )
  OCV_OPTION(WITH_OPENGL         "Include OpenGL support"                      OFF  IF (NOT ANDROID AND NOT APPLE) )
  OCV_OPTION(WITH_OPENNI         "Include OpenNI support"                      OFF  IF (NOT ANDROID AND NOT IOS) )
@@@ -142,10 -141,9 +142,10 @@@ OCV_OPTION(WITH_V4L            "Includ
  OCV_OPTION(WITH_VIDEOINPUT     "Build HighGUI with DirectShow support"       ON   IF WIN32 )
  OCV_OPTION(WITH_XIMEA          "Include XIMEA cameras support"               OFF  IF (NOT ANDROID AND NOT APPLE) )
  OCV_OPTION(WITH_XINE           "Include Xine support (GPL)"                  OFF  IF (UNIX AND NOT APPLE AND NOT ANDROID) )
 -OCV_OPTION(WITH_OPENCL         "Include OpenCL Runtime support"              ON   IF (NOT ANDROID AND NOT IOS) )
 -OCV_OPTION(WITH_OPENCLAMDFFT   "Include AMD OpenCL FFT library support"      ON   IF (NOT ANDROID AND NOT IOS) )
 -OCV_OPTION(WITH_OPENCLAMDBLAS  "Include AMD OpenCL BLAS library support"     ON   IF (NOT ANDROID AND NOT IOS) )
 +OCV_OPTION(WITH_CLP            "Include Clp support (EPL)"                   OFF)
- OCV_OPTION(WITH_OPENCL         "Include OpenCL Runtime support"              OFF  IF (NOT ANDROID AND NOT IOS) )
- OCV_OPTION(WITH_OPENCLAMDFFT   "Include AMD OpenCL FFT library support"      OFF  IF (NOT ANDROID AND NOT IOS) )
- OCV_OPTION(WITH_OPENCLAMDBLAS  "Include AMD OpenCL BLAS library support"     OFF  IF (NOT ANDROID AND NOT IOS) )
++OCV_OPTION(WITH_OPENCL         "Include OpenCL Runtime support"              ON  IF (NOT ANDROID AND NOT IOS) )
++OCV_OPTION(WITH_OPENCLAMDFFT   "Include AMD OpenCL FFT library support"      ON  IF (NOT ANDROID AND NOT IOS) )
++OCV_OPTION(WITH_OPENCLAMDBLAS  "Include AMD OpenCL BLAS library support"     ON  IF (NOT ANDROID AND NOT IOS) )
  
  
  # OpenCV build components
Simple merge
Simple merge
index 0000000,7b201b9..91b4116
mode 000000,100644..100644
--- /dev/null
@@@ -1,0 -1,144 +1,144 @@@
 -=======
+ .. _Windows_Visual_Studio_Image_Watch:
+ Image Watch: viewing in-memory images in the Visual Studio debugger
+ *******************************************************************
+ Image Watch is a plug-in for Microsoft Visual Studio that lets you to visualize in-memory images (*cv::Mat* or *IplImage\_* objects, for example) while debugging an application. This can be helpful for tracking down bugs, or for simply understanding what a given piece of code is doing.
+ Prerequisites
+ =============
+ This tutorial assumes that you have the following available:
+ #. Visual Studio 2012 Professional (or better) with Update 1 installed. Update 1 can be downloaded `here <http://www.microsoft.com/en-us/download/details.aspx?id=35774>`_.
+ #. An OpenCV installation on your Windows machine (Tutorial: :ref:`Windows_Installation`).
+ #. Ability to create and build OpenCV projects in Visual Studio (Tutorial: :ref:`Windows_Visual_Studio_How_To`).
+ Installation
+ ============
+ `Download <http://go.microsoft.com/fwlink/?LinkId=285460>`_ the Image Watch installer. The installer comes in a single file with extension .vsix (*Visual Studio Extension*). To launch it, simply double-click on the .vsix file in Windows Explorer. When the installer has finished, make sure to restart Visual Studio to complete the installation.
+ Example
 -      :height: 320pt
++========
+ Image Watch works with any existing project that uses OpenCV image objects (for example, *cv::Mat*). In this example, we use a minimal test program that loads an image from a file and runs an edge detector. To build the program, create a console application project in Visual Studio, name it "image-watch-demo", and insert the source code below.
+ .. code-block:: c++
+     // Test application for the Visual Studio Image Watch Debugger extension
+     #include <iostream>                        // std::cout
+     #include <opencv2/core/core.hpp>           // cv::Mat
+     #include <opencv2/highgui/highgui.hpp>     // cv::imread()
+     #include <opencv2/imgproc/imgproc.hpp>     // cv::Canny()
+     using namespace std;
+     using namespace cv;
+     void help()
+     {
+         cout
+             << "----------------------------------------------------" << endl
+             << "This is a test program for the Image Watch Debugger " << endl
+             << "plug-in for Visual Studio. The program loads an     " << endl
+             << "image from a file and runs the Canny edge detector. " << endl
+             << "No output is displayed or written to disk."
+             << endl
+             << "Usage:"                                               << endl
+             << "image-watch-demo inputimage"                          << endl
+             << "----------------------------------------------------" << endl
+             << endl;
+     }
+     int main(int argc, char *argv[])
+     {
+         help();
+         if (argc != 2)
+         {
+             cout << "Wrong number of parameters" << endl;
+             return -1;
+         }
+         cout << "Loading input image: " << argv[1] << endl;
+         Mat input;
+         input = imread(argv[1], CV_LOAD_IMAGE_COLOR);
+         cout << "Detecting edges in input image" << endl;
+         Mat edges;
+         Canny(input, edges, 10, 100);
+         return 0;
+     }
+ Make sure your active solution configuration (:menuselection:`Build --> Configuration Manager`) is set to a debug build (usually called "Debug"). This should disable compiler optimizations so that viewing variables in the debugger can work reliably.
+ Build your solution (:menuselection:`Build --> Build Solution`, or press *F7*).
+ Now set a breakpoint on the source line that says
+ .. code-block:: c++
+     Mat edges;
+ To set the breakpoint, right-click on the source line and select :menuselection:`Breakpoints --> Insert Breakpoint` from the context menu.
+ Launch the program in the debugger (:menuselection:`Debug --> Start Debugging`, or hit *F5*). When the breakpoint is hit, the program is paused and Visual Studio displays a yellow instruction pointer at the breakpoint:
+ .. image:: images/breakpoint.png
+ Now you can inspect the state of you program. For example, you can bring up the *Locals* window (:menuselection:`Debug --> Windows --> Locals`), which will show the names and values of the variables in the current scope:
+ .. image:: images/vs_locals.png
+ Note that the built-in *Locals* window will display text only. This is where the Image Watch plug-in comes in. Image Watch is like another *Locals* window, but with an image viewer built into it. To bring up Image Watch, select :menuselection:`View --> Other Windows --> Image Watch`. Like Visual Studio's *Locals* window, Image Watch can dock to the Visual Studio IDE. Also, Visual Studio will remember whether you had Image Watch open, and where it was located between debugging sessions. This means you only have to do this once--the next time you start debugging, Image Watch will be back where you left it. Here's what the docked Image Watch window looks like at our breakpoint:
+ .. image:: images/toolwindow.jpg
 -      :height: 160pt
++    :height: 320pt
+ The radio button at the top left (*Locals/Watch*) selects what is shown in the *Image List* below: *Locals* lists all OpenCV image objects in the current scope (this list is automatically populated). *Watch* shows image expressions that have been pinned for continuous inspection (not described here, see `Image Watch documentation <http://go.microsoft.com/fwlink/?LinkId=285461>`_ for details). The image list shows basic information such as width, height, number of channels, and, if available, a thumbnail. In our example, the image list contains our two local image variables, *input* and *edges*.
+ If an image has a thumbnail, left-clicking on that image will select it for detailed viewing in the *Image Viewer* on the right. The viewer lets you pan (drag mouse) and zoom (mouse wheel). It also displays the pixel coordinate and value at the current mouse position.
+ .. image:: images/viewer.jpg
 -      :height: 160pt
 -      
++    :height: 160pt
+ Note that the second image in the list, *edges*, is shown as "invalid". This indicates that some data members of this image object have corrupt or invalid values (for example, a negative image width). This is expected at this point in the program, since the C++ constructor for *edges* has not run yet, and so its members have undefined values (in debug mode they are usually filled with "0xCD" bytes).
+ From here you can single-step through your code (:menuselection:`Debug->Step Over`, or press *F10*) and watch the pixels change: if you step once, over the *Mat edges;* statement, the *edges* image will change from "invalid" to "empty", which means that it is now in a valid state (default constructed), even though it has not been initialized yet (using *cv::Mat::create()*, for example). If you make one more step over the *cv::Canny()* call, you will see a thumbnail of the edge image appear in the image list.
+ Now assume you want to do a visual sanity check of the *cv::Canny()* implementation. Bring the *edges* image into the viewer by selecting it in the *Image List* and zoom into a region with a clearly defined edge:
+ .. image:: images/edges_zoom.png
 -      :height: 120pt
++    :height: 160pt
++
+ Right-click on the *Image Viewer* to bring up the view context menu and enable :menuselection:`Link Views` (a check box next to the menu item indicates whether the option is enabled).
+ .. image:: images/viewer_context_menu.png
 -      :height: 160pt
 -      
++    :height: 120pt
+ The :menuselection:`Link Views` feature keeps the view region fixed when flipping between images of the same size. To see how this works, select the input image from the image list--you should now see the corresponding zoomed-in region in the input image:
+ .. image:: images/input_zoom.png
 -      :height: 80pt
++    :height: 160pt
++
+ You may also switch back and forth between viewing input and edges with your up/down cursor keys. That way you can easily  verify that the detected edges line up nicely with the data in the input image.
+ More ...
+ ====================
+ Image watch has a number of more advanced features, such as
+ #. pinning images to a *Watch* list for inspection across scopes or between debugging sessions
+ #. clamping, thresholding, or diff'ing images directly inside the Watch window
+ #. comparing an in-memory image against a reference image from a file
+ Please refer to the online `Image Watch Documentation <http://go.microsoft.com/fwlink/?LinkId=285461>`_ for details--you also can get to the documentation page by clicking on the *Help* link in the Image Watch window:
+ .. image:: images/help_button.jpg
++    :height: 80pt
@@@ -2858,11 -2912,14 +2858,14 @@@ template<typename _Tp> static inline Fi
      return fs;
  }
  
 -CV_EXPORTS FileStorage& operator << (FileStorage& fs, const string& str);
 +CV_EXPORTS FileStorage& operator << (FileStorage& fs, const String& str);
  
  static inline FileStorage& operator << (FileStorage& fs, const char* str)
 -{ return (fs << string(str)); }
 +{ return (fs << String(str)); }
  
 -{ return (fs << string(value)); }
+ static inline FileStorage& operator << (FileStorage& fs, char* value)
++{ return (fs << String(value)); }
  inline FileNode::FileNode() : fs(0), node(0) {}
  inline FileNode::FileNode(const CvFileStorage* _fs, const CvFileNode* _node)
      : fs(_fs), node(_node) {}
@@@ -61,4 -61,4 +61,4 @@@ namespace c
      }
  }
  
- #endif /* __OPENCV_CUDA_STREAM_ACCESSOR_HPP__ */
 -#endif /* __OPENCV_GPU_STREAM_ACCESSOR_HPP__ */
++#endif /* __OPENCV_CUDA_STREAM_ACCESSOR_HPP__ */
@@@ -1,7 -1,49 +1,49 @@@
 -#include <string>
+ /*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 <sstream>
  #include "cvconfig.h"
 -#include "opencv2/core/core.hpp"
 +#include "opencv2/core.hpp"
 +#include "opencv2/core/utility.hpp"
  #include "gl_core_3_1.hpp"
  
  #ifdef HAVE_OPENGL
@@@ -454,19 -454,12 +454,29 @@@ protected
  TEST(Core_InputOutput, huge) { CV_BigMatrixIOTest test; test.safe_run(); }
  */
  
- }
 +TEST(Core_globbing, accurasy)
 +{
 +    std::string patternLena    = cvtest::TS::ptr()->get_data_path() + "lena*.*";
 +    std::string patternLenaPng = cvtest::TS::ptr()->get_data_path() + "lena.png";
 +
 +    std::vector<String> lenas, pngLenas;
 +    cv::glob(patternLena, lenas, true);
 +    cv::glob(patternLenaPng, pngLenas, true);
 +
 +    ASSERT_GT(lenas.size(), pngLenas.size());
 +
 +    for (size_t i = 0; i < pngLenas.size(); ++i)
 +    {
 +        ASSERT_NE(std::find(lenas.begin(), lenas.end(), pngLenas[i]), lenas.end());
 +    }
++}
++
+ TEST(Core_InputOutput, FileStorage)
+ {
+     std::string file = cv::tempfile(".xml");
+     cv::FileStorage f(file, cv::FileStorage::WRITE);
+     char arr[66];
+     sprintf(arr, "sprintf is hell %d", 666);
+     EXPECT_NO_THROW(f << arr);
+ }
Simple merge
index 51e1c5f,0000000..88703fe
mode 100644,000000..100644
--- /dev/null
@@@ -1,2365 -1,0 +1,2373 @@@
- //     and/or other GpuMaterials provided with the distribution.
 +/*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_GPU_HPP__
 +#define __OPENCV_GPU_HPP__
 +
 +#ifndef SKIP_INCLUDES
 +#include <vector>
 +#include <memory>
 +#include <iosfwd>
 +#endif
 +
 +#include "opencv2/core/gpumat.hpp"
 +#include "opencv2/imgproc.hpp"
 +#include "opencv2/objdetect.hpp"
 +#include "opencv2/features2d.hpp"
 +
 +namespace cv { namespace gpu {
 +//////////////////////////////// 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_) : ksize(ksize_), anchor(anchor_) {}
 +    virtual ~BaseRowFilter_GPU() {}
 +    virtual void operator()(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null()) = 0;
 +    int ksize, anchor;
 +};
 +
 +/*!
 +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_) : ksize(ksize_), anchor(anchor_) {}
 +    virtual ~BaseColumnFilter_GPU() {}
 +    virtual void operator()(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null()) = 0;
 +    int ksize, anchor;
 +};
 +
 +/*!
 +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_) : ksize(ksize_), anchor(anchor_) {}
 +    virtual ~BaseFilter_GPU() {}
 +    virtual void operator()(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null()) = 0;
 +    Size ksize;
 +    Point anchor;
 +};
 +
 +/*!
 +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 GpuMat& src, GpuMat& dst, Rect roi = Rect(0,0,-1,-1), Stream& stream = Stream::Null()) = 0;
 +};
 +
 +//! returns the non-separable filter engine with the specified filter
 +CV_EXPORTS Ptr<FilterEngine_GPU> createFilter2D_GPU(const Ptr<BaseFilter_GPU>& filter2D, int srcType, int dstType);
 +
 +//! 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, int srcType, int bufType, int dstType);
 +CV_EXPORTS Ptr<FilterEngine_GPU> createSeparableFilter_GPU(const Ptr<BaseRowFilter_GPU>& rowFilter,
 +    const Ptr<BaseColumnFilter_GPU>& columnFilter, int srcType, int bufType, int dstType, GpuMat& buf);
 +
 +//! returns horizontal 1D box filter
 +//! supports only CV_8UC1 source type and CV_32FC1 sum type
 +CV_EXPORTS Ptr<BaseRowFilter_GPU> getRowSumFilter_GPU(int srcType, int sumType, int ksize, int anchor = -1);
 +
 +//! returns vertical 1D box filter
 +//! supports only CV_8UC1 sum type and CV_32FC1 dst type
 +CV_EXPORTS Ptr<BaseColumnFilter_GPU> getColumnSumFilter_GPU(int sumType, int dstType, int ksize, int anchor = -1);
 +
 +//! returns 2D box filter
 +//! supports CV_8UC1 and CV_8UC4 source type, dst type must be the same as source type
 +CV_EXPORTS Ptr<BaseFilter_GPU> getBoxFilter_GPU(int srcType, int dstType, const Size& ksize, Point anchor = Point(-1, -1));
 +
 +//! returns box filter engine
 +CV_EXPORTS Ptr<FilterEngine_GPU> createBoxFilter_GPU(int srcType, int dstType, const Size& ksize,
 +    const Point& anchor = Point(-1,-1));
 +
 +//! returns 2D morphological filter
 +//! only MORPH_ERODE and MORPH_DILATE are supported
 +//! supports CV_8UC1 and CV_8UC4 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);
 +CV_EXPORTS Ptr<FilterEngine_GPU> createMorphologyFilter_GPU(int op, int type, const Mat& kernel, GpuMat& buf,
 +    const Point& anchor = Point(-1,-1), int iterations = 1);
 +
 +//! returns 2D filter with the specified kernel
 +//! supports CV_8U, CV_16U and CV_32F one and four channel image
 +CV_EXPORTS Ptr<BaseFilter_GPU> getLinearFilter_GPU(int srcType, int dstType, const Mat& kernel, Point anchor = Point(-1, -1), int borderType = BORDER_DEFAULT);
 +
 +//! returns the non-separable linear filter engine
 +CV_EXPORTS Ptr<FilterEngine_GPU> createLinearFilter_GPU(int srcType, int dstType, const Mat& kernel,
 +    Point anchor = Point(-1,-1), int borderType = BORDER_DEFAULT);
 +
 +//! returns the primitive row filter with the specified kernel.
 +//! supports only CV_8UC1, CV_8UC4, CV_16SC1, CV_16SC2, CV_32SC1, CV_32FC1 source type.
 +//! there are two version of algorithm: NPP and OpenCV.
 +//! NPP calls when srcType == CV_8UC1 or srcType == CV_8UC4 and bufType == srcType,
 +//! otherwise calls OpenCV version.
 +//! NPP supports only BORDER_CONSTANT border type.
 +//! OpenCV version supports only CV_32F as buffer depth and
 +//! BORDER_REFLECT101, BORDER_REPLICATE and BORDER_CONSTANT border types.
 +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.
 +//! supports only CV_8UC1, CV_8UC4, CV_16SC1, CV_16SC2, CV_32SC1, CV_32FC1 dst type.
 +//! there are two version of algorithm: NPP and OpenCV.
 +//! NPP calls when dstType == CV_8UC1 or dstType == CV_8UC4 and bufType == dstType,
 +//! otherwise calls OpenCV version.
 +//! NPP supports only BORDER_CONSTANT border type.
 +//! OpenCV version supports only CV_32F as buffer depth and
 +//! BORDER_REFLECT101, BORDER_REPLICATE and BORDER_CONSTANT border types.
 +CV_EXPORTS Ptr<BaseColumnFilter_GPU> getLinearColumnFilter_GPU(int bufType, int dstType, const Mat& columnKernel,
 +    int anchor = -1, int borderType = BORDER_DEFAULT);
 +
 +//! 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), int rowBorderType = BORDER_DEFAULT,
 +    int columnBorderType = -1);
 +CV_EXPORTS Ptr<FilterEngine_GPU> createSeparableLinearFilter_GPU(int srcType, int dstType, const Mat& rowKernel,
 +    const Mat& columnKernel, GpuMat& buf, const Point& anchor = Point(-1,-1), int rowBorderType = BORDER_DEFAULT,
 +    int columnBorderType = -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 rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);
 +CV_EXPORTS Ptr<FilterEngine_GPU> createDerivFilter_GPU(int srcType, int dstType, int dx, int dy, int ksize, GpuMat& buf,
 +                                                       int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);
 +
 +//! returns the Gaussian filter engine
 +CV_EXPORTS Ptr<FilterEngine_GPU> createGaussianFilter_GPU(int type, Size ksize, double sigma1, double sigma2 = 0,
 +                                                          int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);
 +CV_EXPORTS Ptr<FilterEngine_GPU> createGaussianFilter_GPU(int type, Size ksize, GpuMat& buf, double sigma1, double sigma2 = 0,
 +                                                          int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);
 +
 +//! returns maximum filter
 +CV_EXPORTS Ptr<BaseFilter_GPU> getMaxFilter_GPU(int srcType, int dstType, const Size& ksize, Point anchor = Point(-1,-1));
 +
 +//! returns minimum filter
 +CV_EXPORTS Ptr<BaseFilter_GPU> getMinFilter_GPU(int srcType, int dstType, const Size& ksize, Point anchor = Point(-1,-1));
 +
 +//! smooths the image using the normalized box filter
 +//! supports CV_8UC1, CV_8UC4 types
 +CV_EXPORTS void boxFilter(const GpuMat& src, GpuMat& dst, int ddepth, Size ksize, Point anchor = Point(-1,-1), Stream& stream = Stream::Null());
 +
 +//! a synonym for normalized box filter
 +static inline void blur(const GpuMat& src, GpuMat& dst, Size ksize, Point anchor = Point(-1,-1), Stream& stream = Stream::Null())
 +{
 +    boxFilter(src, dst, -1, ksize, anchor, stream);
 +}
 +
 +//! erodes the image (applies the local minimum operator)
 +CV_EXPORTS void erode(const GpuMat& src, GpuMat& dst, const Mat& kernel, Point anchor = Point(-1, -1), int iterations = 1);
 +CV_EXPORTS void erode(const GpuMat& src, GpuMat& dst, const Mat& kernel, GpuMat& buf,
 +                      Point anchor = Point(-1, -1), int iterations = 1,
 +                      Stream& stream = Stream::Null());
 +
 +//! dilates the image (applies the local maximum operator)
 +CV_EXPORTS void dilate(const GpuMat& src, GpuMat& dst, const Mat& kernel, Point anchor = Point(-1, -1), int iterations = 1);
 +CV_EXPORTS void dilate(const GpuMat& src, GpuMat& dst, const Mat& kernel, GpuMat& buf,
 +                       Point anchor = Point(-1, -1), int iterations = 1,
 +                       Stream& stream = Stream::Null());
 +
 +//! applies an advanced morphological operation to the image
 +CV_EXPORTS void morphologyEx(const GpuMat& src, GpuMat& dst, int op, const Mat& kernel, Point anchor = Point(-1, -1), int iterations = 1);
 +CV_EXPORTS void morphologyEx(const GpuMat& src, GpuMat& dst, int op, const Mat& kernel, GpuMat& buf1, GpuMat& buf2,
 +                             Point anchor = Point(-1, -1), int iterations = 1, Stream& stream = Stream::Null());
 +
 +//! applies non-separable 2D linear filter to the image
 +CV_EXPORTS void filter2D(const GpuMat& src, GpuMat& dst, int ddepth, const Mat& kernel, Point anchor=Point(-1,-1), int borderType = BORDER_DEFAULT, Stream& stream = Stream::Null());
 +
 +//! applies separable 2D linear filter to the image
 +CV_EXPORTS void sepFilter2D(const GpuMat& src, GpuMat& dst, int ddepth, const Mat& kernelX, const Mat& kernelY,
 +                            Point anchor = Point(-1,-1), int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);
 +CV_EXPORTS void sepFilter2D(const GpuMat& src, GpuMat& dst, int ddepth, const Mat& kernelX, const Mat& kernelY, GpuMat& buf,
 +                            Point anchor = Point(-1,-1), int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1,
 +                            Stream& stream = Stream::Null());
 +
 +//! applies generalized Sobel operator to the image
 +CV_EXPORTS void Sobel(const GpuMat& src, GpuMat& dst, int ddepth, int dx, int dy, int ksize = 3, double scale = 1,
 +                      int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);
 +CV_EXPORTS void Sobel(const GpuMat& src, GpuMat& dst, int ddepth, int dx, int dy, GpuMat& buf, int ksize = 3, double scale = 1,
 +                      int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1, Stream& stream = Stream::Null());
 +
 +//! applies the vertical or horizontal Scharr operator to the image
 +CV_EXPORTS void Scharr(const GpuMat& src, GpuMat& dst, int ddepth, int dx, int dy, double scale = 1,
 +                       int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);
 +CV_EXPORTS void Scharr(const GpuMat& src, GpuMat& dst, int ddepth, int dx, int dy, GpuMat& buf, double scale = 1,
 +                       int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1, Stream& stream = Stream::Null());
 +
 +//! smooths the image using Gaussian filter.
 +CV_EXPORTS void GaussianBlur(const GpuMat& src, GpuMat& dst, Size ksize, double sigma1, double sigma2 = 0,
 +                             int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);
 +CV_EXPORTS void GaussianBlur(const GpuMat& src, GpuMat& dst, Size ksize, GpuMat& buf, double sigma1, double sigma2 = 0,
 +                             int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1, Stream& stream = Stream::Null());
 +
 +//! applies Laplacian operator to the image
 +//! supports only ksize = 1 and ksize = 3
 +CV_EXPORTS void Laplacian(const GpuMat& src, GpuMat& dst, int ddepth, int ksize = 1, double scale = 1, int borderType = BORDER_DEFAULT, Stream& stream = Stream::Null());
 +
 +
 +////////////////////////////// Arithmetics ///////////////////////////////////
 +
 +//! implements generalized matrix product algorithm GEMM from BLAS
 +CV_EXPORTS void gemm(const GpuMat& src1, const GpuMat& src2, double alpha,
 +    const GpuMat& src3, double beta, GpuMat& dst, int flags = 0, Stream& stream = Stream::Null());
 +
 +//! transposes the matrix
 +//! supports matrix with element size = 1, 4 and 8 bytes (CV_8UC1, CV_8UC4, CV_16UC2, CV_32FC1, etc)
 +CV_EXPORTS void transpose(const GpuMat& src1, GpuMat& dst, Stream& stream = Stream::Null());
 +
 +//! reverses the order of the rows, columns or both in a matrix
 +//! supports 1, 3 and 4 channels images with CV_8U, CV_16U, CV_32S or CV_32F depth
 +CV_EXPORTS void flip(const GpuMat& a, GpuMat& b, int flipCode, Stream& stream = Stream::Null());
 +
 +//! 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
 +//! supports CV_8UC1, CV_8UC3 types
 +CV_EXPORTS void LUT(const GpuMat& src, const Mat& lut, GpuMat& dst, Stream& stream = Stream::Null());
 +
 +//! makes multi-channel array out of several single-channel arrays
 +CV_EXPORTS void merge(const GpuMat* src, size_t n, GpuMat& dst, Stream& stream = Stream::Null());
 +
 +//! makes multi-channel array out of several single-channel arrays
 +CV_EXPORTS void merge(const std::vector<GpuMat>& src, GpuMat& dst, Stream& stream = Stream::Null());
 +
 +//! copies each plane of a multi-channel array to a dedicated array
 +CV_EXPORTS void split(const GpuMat& src, GpuMat* dst, Stream& stream = Stream::Null());
 +
 +//! copies each plane of a multi-channel array to a dedicated array
 +CV_EXPORTS void split(const GpuMat& src, std::vector<GpuMat>& dst, Stream& stream = Stream::Null());
 +
 +//! computes magnitude of complex (x(i).re, x(i).im) vector
 +//! supports only CV_32FC2 type
 +CV_EXPORTS void magnitude(const GpuMat& xy, GpuMat& magnitude, Stream& stream = Stream::Null());
 +
 +//! computes squared magnitude of complex (x(i).re, x(i).im) vector
 +//! supports only CV_32FC2 type
 +CV_EXPORTS void magnitudeSqr(const GpuMat& xy, GpuMat& magnitude, Stream& stream = Stream::Null());
 +
 +//! computes magnitude of each (x(i), y(i)) vector
 +//! supports only floating-point source
 +CV_EXPORTS void magnitude(const GpuMat& x, const GpuMat& y, GpuMat& magnitude, Stream& stream = Stream::Null());
 +
 +//! computes squared magnitude of each (x(i), y(i)) vector
 +//! supports only floating-point source
 +CV_EXPORTS void magnitudeSqr(const GpuMat& x, const GpuMat& y, GpuMat& magnitude, Stream& stream = Stream::Null());
 +
 +//! computes angle (angle(i)) of each (x(i), y(i)) vector
 +//! supports only floating-point source
 +CV_EXPORTS void phase(const GpuMat& x, const GpuMat& y, GpuMat& angle, bool angleInDegrees = false, Stream& stream = Stream::Null());
 +
 +//! converts Cartesian coordinates to polar
 +//! supports only floating-point source
 +CV_EXPORTS void cartToPolar(const GpuMat& x, const GpuMat& y, GpuMat& magnitude, GpuMat& angle, bool angleInDegrees = false, Stream& stream = Stream::Null());
 +
 +//! converts polar coordinates to Cartesian
 +//! supports only floating-point source
 +CV_EXPORTS void polarToCart(const GpuMat& magnitude, const GpuMat& angle, GpuMat& x, GpuMat& y, bool angleInDegrees = false, Stream& stream = Stream::Null());
 +
 +//! scales and shifts array elements so that either the specified norm (alpha) or the minimum (alpha) and maximum (beta) array values get the specified values
 +CV_EXPORTS void normalize(const GpuMat& src, GpuMat& dst, double alpha = 1, double beta = 0,
 +                          int norm_type = NORM_L2, int dtype = -1, const GpuMat& mask = GpuMat());
 +CV_EXPORTS void normalize(const GpuMat& src, GpuMat& dst, double a, double b,
 +                          int norm_type, int dtype, const GpuMat& mask, GpuMat& norm_buf, GpuMat& cvt_buf);
 +
 +
 +//////////////////////////// Per-element operations ////////////////////////////////////
 +
 +//! adds one matrix to another (c = a + b)
 +CV_EXPORTS void add(const GpuMat& a, const GpuMat& b, GpuMat& c, const GpuMat& mask = GpuMat(), int dtype = -1, Stream& stream = Stream::Null());
 +//! adds scalar to a matrix (c = a + s)
 +CV_EXPORTS void add(const GpuMat& a, const Scalar& sc, GpuMat& c, const GpuMat& mask = GpuMat(), int dtype = -1, Stream& stream = Stream::Null());
 +
 +//! subtracts one matrix from another (c = a - b)
 +CV_EXPORTS void subtract(const GpuMat& a, const GpuMat& b, GpuMat& c, const GpuMat& mask = GpuMat(), int dtype = -1, Stream& stream = Stream::Null());
 +//! subtracts scalar from a matrix (c = a - s)
 +CV_EXPORTS void subtract(const GpuMat& a, const Scalar& sc, GpuMat& c, const GpuMat& mask = GpuMat(), int dtype = -1, Stream& stream = Stream::Null());
 +
 +//! computes element-wise weighted product of the two arrays (c = scale * a * b)
 +CV_EXPORTS void multiply(const GpuMat& a, const GpuMat& b, GpuMat& c, double scale = 1, int dtype = -1, Stream& stream = Stream::Null());
 +//! weighted multiplies matrix to a scalar (c = scale * a * s)
 +CV_EXPORTS void multiply(const GpuMat& a, const Scalar& sc, GpuMat& c, double scale = 1, int dtype = -1, Stream& stream = Stream::Null());
 +
 +//! computes element-wise weighted quotient of the two arrays (c = a / b)
 +CV_EXPORTS void divide(const GpuMat& a, const GpuMat& b, GpuMat& c, double scale = 1, int dtype = -1, Stream& stream = Stream::Null());
 +//! computes element-wise weighted quotient of matrix and scalar (c = a / s)
 +CV_EXPORTS void divide(const GpuMat& a, const Scalar& sc, GpuMat& c, double scale = 1, int dtype = -1, Stream& stream = Stream::Null());
 +//! computes element-wise weighted reciprocal of an array (dst = scale/src2)
 +CV_EXPORTS void divide(double scale, const GpuMat& b, GpuMat& c, int dtype = -1, Stream& stream = Stream::Null());
 +
 +//! computes the weighted sum of two arrays (dst = alpha*src1 + beta*src2 + gamma)
 +CV_EXPORTS void addWeighted(const GpuMat& src1, double alpha, const GpuMat& src2, double beta, double gamma, GpuMat& dst,
 +                            int dtype = -1, Stream& stream = Stream::Null());
 +
 +//! adds scaled array to another one (dst = alpha*src1 + src2)
 +static inline void scaleAdd(const GpuMat& src1, double alpha, const GpuMat& src2, GpuMat& dst, Stream& stream = Stream::Null())
 +{
 +    addWeighted(src1, alpha, src2, 1.0, 0.0, dst, -1, stream);
 +}
 +
 +//! computes element-wise absolute difference of two arrays (c = abs(a - b))
 +CV_EXPORTS void absdiff(const GpuMat& a, const GpuMat& b, GpuMat& c, Stream& stream = Stream::Null());
 +//! computes element-wise absolute difference of array and scalar (c = abs(a - s))
 +CV_EXPORTS void absdiff(const GpuMat& a, const Scalar& s, GpuMat& c, Stream& stream = Stream::Null());
 +
 +//! computes absolute value of each matrix element
 +//! supports CV_16S and CV_32F depth
 +CV_EXPORTS void abs(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());
 +
 +//! computes square of each pixel in an image
 +//! supports CV_8U, CV_16U, CV_16S and CV_32F depth
 +CV_EXPORTS void sqr(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());
 +
 +//! computes square root of each pixel in an image
 +//! supports CV_8U, CV_16U, CV_16S and CV_32F depth
 +CV_EXPORTS void sqrt(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());
 +
 +//! computes exponent of each matrix element (b = e**a)
 +//! supports CV_8U, CV_16U, CV_16S and CV_32F depth
 +CV_EXPORTS void exp(const GpuMat& a, GpuMat& b, Stream& stream = Stream::Null());
 +
 +//! computes natural logarithm of absolute value of each matrix element: b = log(abs(a))
 +//! supports CV_8U, CV_16U, CV_16S and CV_32F depth
 +CV_EXPORTS void log(const GpuMat& a, GpuMat& b, Stream& stream = Stream::Null());
 +
 +//! computes power of each matrix element:
 +//    (dst(i,j) = pow(     src(i,j) , power), if src.type() is integer
 +//    (dst(i,j) = pow(fabs(src(i,j)), power), otherwise
 +//! supports all, except depth == CV_64F
 +CV_EXPORTS void pow(const GpuMat& src, double power, GpuMat& dst, Stream& stream = Stream::Null());
 +
 +//! compares elements of two arrays (c = a <cmpop> b)
 +CV_EXPORTS void compare(const GpuMat& a, const GpuMat& b, GpuMat& c, int cmpop, Stream& stream = Stream::Null());
 +CV_EXPORTS void compare(const GpuMat& a, Scalar sc, GpuMat& c, int cmpop, Stream& stream = Stream::Null());
 +
 +//! performs per-elements bit-wise inversion
 +CV_EXPORTS void bitwise_not(const GpuMat& src, GpuMat& dst, const GpuMat& mask=GpuMat(), Stream& stream = Stream::Null());
 +
 +//! calculates per-element bit-wise disjunction of two arrays
 +CV_EXPORTS void bitwise_or(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const GpuMat& mask=GpuMat(), Stream& stream = Stream::Null());
 +//! calculates per-element bit-wise disjunction of array and scalar
 +//! supports 1, 3 and 4 channels images with CV_8U, CV_16U or CV_32S depth
 +CV_EXPORTS void bitwise_or(const GpuMat& src1, const Scalar& sc, GpuMat& dst, Stream& stream = Stream::Null());
 +
 +//! calculates per-element bit-wise conjunction of two arrays
 +CV_EXPORTS void bitwise_and(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const GpuMat& mask=GpuMat(), Stream& stream = Stream::Null());
 +//! calculates per-element bit-wise conjunction of array and scalar
 +//! supports 1, 3 and 4 channels images with CV_8U, CV_16U or CV_32S depth
 +CV_EXPORTS void bitwise_and(const GpuMat& src1, const Scalar& sc, GpuMat& dst, Stream& stream = Stream::Null());
 +
 +//! calculates per-element bit-wise "exclusive or" operation
 +CV_EXPORTS void bitwise_xor(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const GpuMat& mask=GpuMat(), Stream& stream = Stream::Null());
 +//! calculates per-element bit-wise "exclusive or" of array and scalar
 +//! supports 1, 3 and 4 channels images with CV_8U, CV_16U or CV_32S depth
 +CV_EXPORTS void bitwise_xor(const GpuMat& src1, const Scalar& sc, GpuMat& dst, Stream& stream = Stream::Null());
 +
 +//! pixel by pixel right shift of an image by a constant value
 +//! supports 1, 3 and 4 channels images with integers elements
 +CV_EXPORTS void rshift(const GpuMat& src, Scalar_<int> sc, GpuMat& dst, Stream& stream = Stream::Null());
 +
 +//! pixel by pixel left shift of an image by a constant value
 +//! supports 1, 3 and 4 channels images with CV_8U, CV_16U or CV_32S depth
 +CV_EXPORTS void lshift(const GpuMat& src, Scalar_<int> sc, GpuMat& dst, Stream& stream = Stream::Null());
 +
 +//! computes per-element minimum of two arrays (dst = min(src1, src2))
 +CV_EXPORTS void min(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, Stream& stream = Stream::Null());
 +
 +//! computes per-element minimum of array and scalar (dst = min(src1, src2))
 +CV_EXPORTS void min(const GpuMat& src1, double src2, GpuMat& dst, Stream& stream = Stream::Null());
 +
 +//! computes per-element maximum of two arrays (dst = max(src1, src2))
 +CV_EXPORTS void max(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, Stream& stream = Stream::Null());
 +
 +//! computes per-element maximum of array and scalar (dst = max(src1, src2))
 +CV_EXPORTS void max(const GpuMat& src1, double src2, GpuMat& dst, Stream& stream = Stream::Null());
 +
 +enum { ALPHA_OVER, ALPHA_IN, ALPHA_OUT, ALPHA_ATOP, ALPHA_XOR, ALPHA_PLUS, ALPHA_OVER_PREMUL, ALPHA_IN_PREMUL, ALPHA_OUT_PREMUL,
 +       ALPHA_ATOP_PREMUL, ALPHA_XOR_PREMUL, ALPHA_PLUS_PREMUL, ALPHA_PREMUL};
 +
 +//! Composite two images using alpha opacity values contained in each image
 +//! Supports CV_8UC4, CV_16UC4, CV_32SC4 and CV_32FC4 types
 +CV_EXPORTS void alphaComp(const GpuMat& img1, const GpuMat& img2, GpuMat& dst, int alpha_op, Stream& stream = Stream::Null());
 +
 +
 +////////////////////////////// Image processing //////////////////////////////
 +
 +//! DST[x,y] = SRC[xmap[x,y],ymap[x,y]]
 +//! supports only CV_32FC1 map type
 +CV_EXPORTS void remap(const GpuMat& src, GpuMat& dst, const GpuMat& xmap, const GpuMat& ymap,
 +                      int interpolation, int borderMode = BORDER_CONSTANT, Scalar borderValue = Scalar(),
 +                      Stream& stream = Stream::Null());
 +
 +//! Does mean shift filtering on GPU.
 +CV_EXPORTS void meanShiftFiltering(const GpuMat& src, GpuMat& dst, int sp, int sr,
 +                                   TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1),
 +                                   Stream& stream = Stream::Null());
 +
 +//! Does mean shift procedure on GPU.
 +CV_EXPORTS void meanShiftProc(const GpuMat& src, GpuMat& dstr, GpuMat& dstsp, int sp, int sr,
 +                              TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1),
 +                              Stream& stream = Stream::Null());
 +
 +//! Does mean shift segmentation with elimination of small regions.
 +CV_EXPORTS void meanShiftSegmentation(const GpuMat& src, Mat& dst, int sp, int sr, int minsize,
 +                                      TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1));
 +
 +//! Does coloring of disparity image: [0..ndisp) -> [0..240, 1, 1] in HSV.
 +//! Supported types of input disparity: CV_8U, CV_16S.
 +//! Output disparity has CV_8UC4 type in BGRA format (alpha = 255).
 +CV_EXPORTS void drawColorDisp(const GpuMat& src_disp, GpuMat& dst_disp, int ndisp, Stream& stream = Stream::Null());
 +
 +//! Reprojects disparity image to 3D space.
 +//! Supports CV_8U and CV_16S types of input disparity.
 +//! The output is a 3- or 4-channel floating-point matrix.
 +//! Each element of this matrix will contain the 3D coordinates of the point (x,y,z,1), computed from the disparity map.
 +//! Q is the 4x4 perspective transformation matrix that can be obtained with cvStereoRectify.
 +CV_EXPORTS void reprojectImageTo3D(const GpuMat& disp, GpuMat& xyzw, const Mat& Q, int dst_cn = 4, Stream& stream = Stream::Null());
 +
 +//! converts image from one color space to another
 +CV_EXPORTS void cvtColor(const GpuMat& src, GpuMat& dst, int code, int dcn = 0, Stream& stream = Stream::Null());
 +
 +enum
 +{
 +    // Bayer Demosaicing (Malvar, He, and Cutler)
 +    COLOR_BayerBG2BGR_MHT = 256,
 +    COLOR_BayerGB2BGR_MHT = 257,
 +    COLOR_BayerRG2BGR_MHT = 258,
 +    COLOR_BayerGR2BGR_MHT = 259,
 +
 +    COLOR_BayerBG2RGB_MHT = COLOR_BayerRG2BGR_MHT,
 +    COLOR_BayerGB2RGB_MHT = COLOR_BayerGR2BGR_MHT,
 +    COLOR_BayerRG2RGB_MHT = COLOR_BayerBG2BGR_MHT,
 +    COLOR_BayerGR2RGB_MHT = COLOR_BayerGB2BGR_MHT,
 +
 +    COLOR_BayerBG2GRAY_MHT = 260,
 +    COLOR_BayerGB2GRAY_MHT = 261,
 +    COLOR_BayerRG2GRAY_MHT = 262,
 +    COLOR_BayerGR2GRAY_MHT = 263
 +};
 +CV_EXPORTS void demosaicing(const GpuMat& src, GpuMat& dst, int code, int dcn = -1, Stream& stream = Stream::Null());
 +
 +//! swap channels
 +//! dstOrder - Integer array describing how channel values are permutated. The n-th entry
 +//!            of the array contains the number of the channel that is stored in the n-th channel of
 +//!            the output image. E.g. Given an RGBA image, aDstOrder = [3,2,1,0] converts this to ABGR
 +//!            channel order.
 +CV_EXPORTS void swapChannels(GpuMat& image, const int dstOrder[4], Stream& stream = Stream::Null());
 +
 +//! Routines for correcting image color gamma
 +CV_EXPORTS void gammaCorrection(const GpuMat& src, GpuMat& dst, bool forward = true, Stream& stream = Stream::Null());
 +
 +//! applies fixed threshold to the image
 +CV_EXPORTS double threshold(const GpuMat& src, GpuMat& dst, double thresh, double maxval, int type, Stream& stream = Stream::Null());
 +
 +//! resizes the image
 +//! Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC, INTER_AREA
 +CV_EXPORTS void resize(const GpuMat& src, GpuMat& dst, Size dsize, double fx=0, double fy=0, int interpolation = INTER_LINEAR, Stream& stream = Stream::Null());
 +
 +//! warps the image using affine transformation
 +//! Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC
 +CV_EXPORTS void warpAffine(const GpuMat& src, GpuMat& dst, const Mat& M, Size dsize, int flags = INTER_LINEAR,
 +    int borderMode = BORDER_CONSTANT, Scalar borderValue = Scalar(), Stream& stream = Stream::Null());
 +
 +CV_EXPORTS void buildWarpAffineMaps(const Mat& M, bool inverse, Size dsize, GpuMat& xmap, GpuMat& ymap, Stream& stream = Stream::Null());
 +
 +//! warps the image using perspective transformation
 +//! Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC
 +CV_EXPORTS void warpPerspective(const GpuMat& src, GpuMat& dst, const Mat& M, Size dsize, int flags = INTER_LINEAR,
 +    int borderMode = BORDER_CONSTANT, Scalar borderValue = Scalar(), Stream& stream = Stream::Null());
 +
 +CV_EXPORTS void buildWarpPerspectiveMaps(const Mat& M, bool inverse, Size dsize, GpuMat& xmap, GpuMat& ymap, Stream& stream = Stream::Null());
 +
 +//! 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,
 +                                   GpuMat& map_x, GpuMat& map_y, Stream& stream = Stream::Null());
 +
 +//! builds cylindrical warping maps
 +CV_EXPORTS void buildWarpCylindricalMaps(Size src_size, Rect dst_roi, const Mat &K, const Mat& R, float scale,
 +                                         GpuMat& map_x, GpuMat& map_y, Stream& stream = Stream::Null());
 +
 +//! builds spherical warping maps
 +CV_EXPORTS void buildWarpSphericalMaps(Size src_size, Rect dst_roi, const Mat &K, const Mat& R, float scale,
 +                                       GpuMat& map_x, GpuMat& map_y, Stream& stream = Stream::Null());
 +
 +//! rotates an image around the origin (0,0) and then shifts it
 +//! supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC
 +//! supports 1, 3 or 4 channels images with CV_8U, CV_16U or CV_32F depth
 +CV_EXPORTS void rotate(const GpuMat& src, GpuMat& dst, Size dsize, double angle, double xShift = 0, double yShift = 0,
 +                       int interpolation = INTER_LINEAR, Stream& stream = Stream::Null());
 +
 +//! copies 2D array to a larger destination array and pads borders with user-specifiable constant
 +CV_EXPORTS void copyMakeBorder(const GpuMat& src, GpuMat& dst, int top, int bottom, int left, int right, int borderType,
 +                               const Scalar& value = Scalar(), Stream& stream = Stream::Null());
 +
 +//! computes the integral image
 +//! sum will have CV_32S type, but will contain unsigned int values
 +//! supports only CV_8UC1 source type
 +CV_EXPORTS void integral(const GpuMat& src, GpuMat& sum, Stream& stream = Stream::Null());
 +//! buffered version
 +CV_EXPORTS void integralBuffered(const GpuMat& src, GpuMat& sum, GpuMat& buffer, Stream& stream = Stream::Null());
 +
 +//! computes squared integral image
 +//! result matrix will have 64F type, but will contain 64U values
 +//! supports source images of 8UC1 type only
 +CV_EXPORTS void sqrIntegral(const GpuMat& src, GpuMat& sqsum, Stream& stream = Stream::Null());
 +
 +//! computes vertical sum, supports only CV_32FC1 images
 +CV_EXPORTS void columnSum(const GpuMat& src, GpuMat& sum);
 +
 +//! computes the standard deviation of integral images
 +//! supports only CV_32SC1 source type and CV_32FC1 sqr type
 +//! output will have CV_32FC1 type
 +CV_EXPORTS void rectStdDev(const GpuMat& src, const GpuMat& sqr, GpuMat& dst, const Rect& rect, Stream& stream = Stream::Null());
 +
 +//! computes Harris cornerness criteria at each image pixel
 +CV_EXPORTS void cornerHarris(const GpuMat& src, GpuMat& dst, int blockSize, int ksize, double k, int borderType = BORDER_REFLECT101);
 +CV_EXPORTS void cornerHarris(const GpuMat& src, GpuMat& dst, GpuMat& Dx, GpuMat& Dy, int blockSize, int ksize, double k, int borderType = BORDER_REFLECT101);
 +CV_EXPORTS void cornerHarris(const GpuMat& src, GpuMat& dst, GpuMat& Dx, GpuMat& Dy, GpuMat& buf, int blockSize, int ksize, double k,
 +                             int borderType = BORDER_REFLECT101, Stream& stream = Stream::Null());
 +
 +//! computes minimum eigen value of 2x2 derivative covariation matrix at each pixel - the cornerness criteria
 +CV_EXPORTS void cornerMinEigenVal(const GpuMat& src, GpuMat& dst, int blockSize, int ksize, int borderType=BORDER_REFLECT101);
 +CV_EXPORTS void cornerMinEigenVal(const GpuMat& src, GpuMat& dst, GpuMat& Dx, GpuMat& Dy, int blockSize, int ksize, int borderType=BORDER_REFLECT101);
 +CV_EXPORTS void cornerMinEigenVal(const GpuMat& src, GpuMat& dst, GpuMat& Dx, GpuMat& Dy, GpuMat& buf, int blockSize, int ksize,
 +    int borderType=BORDER_REFLECT101, Stream& stream = Stream::Null());
 +
 +//! performs per-element multiplication of two full (not packed) Fourier spectrums
 +//! supports 32FC2 matrixes only (interleaved format)
 +CV_EXPORTS void mulSpectrums(const GpuMat& a, const GpuMat& b, GpuMat& c, int flags, bool conjB=false, Stream& stream = Stream::Null());
 +
 +//! performs per-element multiplication of two full (not packed) Fourier spectrums
 +//! supports 32FC2 matrixes only (interleaved format)
 +CV_EXPORTS void mulAndScaleSpectrums(const GpuMat& a, const GpuMat& b, GpuMat& c, int flags, float scale, bool conjB=false, Stream& stream = Stream::Null());
 +
 +//! Performs a forward or inverse discrete Fourier transform (1D or 2D) of floating point matrix.
 +//! Param dft_size is the size of DFT transform.
 +//!
 +//! If the source matrix is not continous, then additional copy will be done,
 +//! so to avoid copying ensure the source matrix is continous one. If you want to use
 +//! preallocated output ensure it is continuous too, otherwise it will be reallocated.
 +//!
 +//! Being implemented via CUFFT real-to-complex transform result contains only non-redundant values
 +//! in CUFFT's format. Result as full complex matrix for such kind of transform cannot be retrieved.
 +//!
 +//! For complex-to-real transform it is assumed that the source matrix is packed in CUFFT's format.
 +CV_EXPORTS void dft(const GpuMat& src, GpuMat& dst, Size dft_size, int flags=0, Stream& stream = Stream::Null());
 +
 +struct CV_EXPORTS ConvolveBuf
 +{
 +    Size result_size;
 +    Size block_size;
 +    Size user_block_size;
 +    Size dft_size;
 +    int spect_len;
 +
 +    GpuMat image_spect, templ_spect, result_spect;
 +    GpuMat 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 (or cross-correlation) of two images using discrete Fourier transform
 +//! supports source images of 32FC1 type only
 +//! result matrix will have 32FC1 type
 +CV_EXPORTS void convolve(const GpuMat& image, const GpuMat& templ, GpuMat& result, bool ccorr = false);
 +CV_EXPORTS void convolve(const GpuMat& image, const GpuMat& templ, GpuMat& result, bool ccorr, ConvolveBuf& buf, Stream& stream = Stream::Null());
 +
 +struct CV_EXPORTS MatchTemplateBuf
 +{
 +    Size user_block_size;
 +    GpuMat imagef, templf;
 +    std::vector<GpuMat> images;
 +    std::vector<GpuMat> image_sums;
 +    std::vector<GpuMat> image_sqsums;
 +};
 +
 +//! computes the proximity map for the raster template and the image where the template is searched for
 +CV_EXPORTS void matchTemplate(const GpuMat& image, const GpuMat& templ, GpuMat& result, int method, Stream &stream = Stream::Null());
 +
 +//! computes the proximity map for the raster template and the image where the template is searched for
 +CV_EXPORTS void matchTemplate(const GpuMat& image, const GpuMat& templ, GpuMat& result, int method, MatchTemplateBuf &buf, Stream& stream = Stream::Null());
 +
 +//! smoothes the source image and downsamples it
 +CV_EXPORTS void pyrDown(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());
 +
 +//! upsamples the source image and then smoothes it
 +CV_EXPORTS void pyrUp(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());
 +
 +//! performs linear blending of two images
 +//! to avoid accuracy errors sum of weigths shouldn't be very close to zero
 +CV_EXPORTS void blendLinear(const GpuMat& img1, const GpuMat& img2, const GpuMat& weights1, const GpuMat& weights2,
 +                            GpuMat& result, Stream& stream = Stream::Null());
 +
 +//! Performa bilateral filtering of passsed image
 +CV_EXPORTS void bilateralFilter(const GpuMat& src, GpuMat& dst, int kernel_size, float sigma_color, float sigma_spatial,
 +                                int borderMode = BORDER_DEFAULT, Stream& stream = Stream::Null());
 +
 +//! Brute force non-local means algorith (slow but universal)
 +CV_EXPORTS void nonLocalMeans(const GpuMat& src, GpuMat& dst, float h, int search_window = 21, int block_size = 7, int borderMode = BORDER_DEFAULT, Stream& s = Stream::Null());
 +
 +//! Fast (but approximate)version of non-local means algorith similar to CPU function (running sums technique)
 +class CV_EXPORTS FastNonLocalMeansDenoising
 +{
 +public:
 +    //! Simple method, recommended for grayscale images (though it supports multichannel images)
 +    void simpleMethod(const GpuMat& src, GpuMat& dst, float h, int search_window = 21, int block_size = 7, Stream& s = Stream::Null());
 +
 +    //! Processes luminance and color components separatelly
 +    void labMethod(const GpuMat& src, GpuMat& dst, float h_luminance, float h_color, int search_window = 21, int block_size = 7, Stream& s = Stream::Null());
 +
 +private:
 +
 +    GpuMat buffer, extended_src_buffer;
 +    GpuMat lab, l, ab;
 +};
 +
 +struct CV_EXPORTS CannyBuf
 +{
 +    void create(const Size& image_size, int apperture_size = 3);
 +    void release();
 +
 +    GpuMat dx, dy;
 +    GpuMat mag;
 +    GpuMat map;
 +    GpuMat st1, st2;
 +    Ptr<FilterEngine_GPU> filterDX, filterDY;
 +};
 +
 +CV_EXPORTS void Canny(const GpuMat& image, GpuMat& edges, double low_thresh, double high_thresh, int apperture_size = 3, bool L2gradient = false);
 +CV_EXPORTS void Canny(const GpuMat& image, CannyBuf& buf, GpuMat& edges, double low_thresh, double high_thresh, int apperture_size = 3, bool L2gradient = false);
 +CV_EXPORTS void Canny(const GpuMat& dx, const GpuMat& dy, GpuMat& edges, double low_thresh, double high_thresh, bool L2gradient = false);
 +CV_EXPORTS void Canny(const GpuMat& dx, const GpuMat& dy, CannyBuf& buf, GpuMat& edges, double low_thresh, double high_thresh, bool L2gradient = false);
 +
 +class CV_EXPORTS ImagePyramid
 +{
 +public:
 +    inline ImagePyramid() : nLayers_(0) {}
 +    inline ImagePyramid(const GpuMat& img, int nLayers, Stream& stream = Stream::Null())
 +    {
 +        build(img, nLayers, stream);
 +    }
 +
 +    void build(const GpuMat& img, int nLayers, Stream& stream = Stream::Null());
 +
 +    void getLayer(GpuMat& outImg, Size outRoi, Stream& stream = Stream::Null()) const;
 +
 +    inline void release()
 +    {
 +        layer0_.release();
 +        pyramid_.clear();
 +        nLayers_ = 0;
 +    }
 +
 +private:
 +    GpuMat layer0_;
 +    std::vector<GpuMat> pyramid_;
 +    int nLayers_;
 +};
 +
 +//! HoughLines
 +
 +struct HoughLinesBuf
 +{
 +    GpuMat accum;
 +    GpuMat list;
 +};
 +
 +CV_EXPORTS void HoughLines(const GpuMat& src, GpuMat& lines, float rho, float theta, int threshold, bool doSort = false, int maxLines = 4096);
 +CV_EXPORTS void HoughLines(const GpuMat& src, GpuMat& lines, HoughLinesBuf& buf, float rho, float theta, int threshold, bool doSort = false, int maxLines = 4096);
 +CV_EXPORTS void HoughLinesDownload(const GpuMat& d_lines, OutputArray h_lines, OutputArray h_votes = noArray());
 +
 +//! HoughLinesP
 +
 +//! finds line segments in the black-n-white image using probabalistic Hough transform
 +CV_EXPORTS void HoughLinesP(const GpuMat& image, GpuMat& lines, HoughLinesBuf& buf, float rho, float theta, int minLineLength, int maxLineGap, int maxLines = 4096);
 +
 +//! HoughCircles
 +
 +struct HoughCirclesBuf
 +{
 +    GpuMat edges;
 +    GpuMat accum;
 +    GpuMat list;
 +    CannyBuf cannyBuf;
 +};
 +
 +CV_EXPORTS void HoughCircles(const GpuMat& src, GpuMat& circles, int method, float dp, float minDist, int cannyThreshold, int votesThreshold, int minRadius, int maxRadius, int maxCircles = 4096);
 +CV_EXPORTS void HoughCircles(const GpuMat& src, GpuMat& 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 GpuMat& d_circles, OutputArray h_circles);
 +
 +//! finds arbitrary template in the grayscale image using Generalized Hough Transform
 +//! Ballard, D.H. (1981). Generalizing the Hough transform to detect arbitrary shapes. Pattern Recognition 13 (2): 111-122.
 +//! Guil, N., González-Linares, J.M. and Zapata, E.L. (1999). Bidimensional shape detection using an invariant approach. Pattern Recognition 32 (6): 1025-1038.
 +class CV_EXPORTS GeneralizedHough_GPU : public cv::Algorithm
 +{
 +public:
 +    static Ptr<GeneralizedHough_GPU> create(int method);
 +
 +    virtual ~GeneralizedHough_GPU();
 +
 +    //! set template to search
 +    void setTemplate(const GpuMat& templ, int cannyThreshold = 100, Point templCenter = Point(-1, -1));
 +    void setTemplate(const GpuMat& edges, const GpuMat& dx, const GpuMat& dy, Point templCenter = Point(-1, -1));
 +
 +    //! find template on image
 +    void detect(const GpuMat& image, GpuMat& positions, int cannyThreshold = 100);
 +    void detect(const GpuMat& edges, const GpuMat& dx, const GpuMat& dy, GpuMat& positions);
 +
 +    void download(const GpuMat& d_positions, OutputArray h_positions, OutputArray h_votes = noArray());
 +
 +    void release();
 +
 +protected:
 +    virtual void setTemplateImpl(const GpuMat& edges, const GpuMat& dx, const GpuMat& dy, Point templCenter) = 0;
 +    virtual void detectImpl(const GpuMat& edges, const GpuMat& dx, const GpuMat& dy, GpuMat& positions) = 0;
 +    virtual void releaseImpl() = 0;
 +
 +private:
 +    GpuMat edges_;
 +    CannyBuf cannyBuf_;
 +};
 +
 +////////////////////////////// Matrix reductions //////////////////////////////
 +
 +//! computes mean value and standard deviation of all or selected array elements
 +//! supports only CV_8UC1 type
 +CV_EXPORTS void meanStdDev(const GpuMat& mtx, Scalar& mean, Scalar& stddev);
 +//! buffered version
 +CV_EXPORTS void meanStdDev(const GpuMat& mtx, Scalar& mean, Scalar& stddev, GpuMat& buf);
 +
 +//! computes norm of array
 +//! supports NORM_INF, NORM_L1, NORM_L2
 +//! supports all matrices except 64F
 +CV_EXPORTS double norm(const GpuMat& src1, int normType=NORM_L2);
 +CV_EXPORTS double norm(const GpuMat& src1, int normType, GpuMat& buf);
 +CV_EXPORTS double norm(const GpuMat& src1, int normType, const GpuMat& mask, GpuMat& buf);
 +
 +//! computes norm of the difference between two arrays
 +//! supports NORM_INF, NORM_L1, NORM_L2
 +//! supports only CV_8UC1 type
 +CV_EXPORTS double norm(const GpuMat& src1, const GpuMat& src2, int normType=NORM_L2);
 +
 +//! computes sum of array elements
 +//! supports only single channel images
 +CV_EXPORTS Scalar sum(const GpuMat& src);
 +CV_EXPORTS Scalar sum(const GpuMat& src, GpuMat& buf);
 +CV_EXPORTS Scalar sum(const GpuMat& src, const GpuMat& mask, GpuMat& buf);
 +
 +//! computes sum of array elements absolute values
 +//! supports only single channel images
 +CV_EXPORTS Scalar absSum(const GpuMat& src);
 +CV_EXPORTS Scalar absSum(const GpuMat& src, GpuMat& buf);
 +CV_EXPORTS Scalar absSum(const GpuMat& src, const GpuMat& mask, GpuMat& buf);
 +
 +//! computes squared sum of array elements
 +//! supports only single channel images
 +CV_EXPORTS Scalar sqrSum(const GpuMat& src);
 +CV_EXPORTS Scalar sqrSum(const GpuMat& src, GpuMat& buf);
 +CV_EXPORTS Scalar sqrSum(const GpuMat& src, const GpuMat& mask, GpuMat& buf);
 +
 +//! finds global minimum and maximum array elements and returns their values
 +CV_EXPORTS void minMax(const GpuMat& src, double* minVal, double* maxVal=0, const GpuMat& mask=GpuMat());
 +CV_EXPORTS void minMax(const GpuMat& src, double* minVal, double* maxVal, const GpuMat& mask, GpuMat& buf);
 +
 +//! finds global minimum and maximum array elements and returns their values with locations
 +CV_EXPORTS void minMaxLoc(const GpuMat& src, double* minVal, double* maxVal=0, Point* minLoc=0, Point* maxLoc=0,
 +                          const GpuMat& mask=GpuMat());
 +CV_EXPORTS void minMaxLoc(const GpuMat& src, double* minVal, double* maxVal, Point* minLoc, Point* maxLoc,
 +                          const GpuMat& mask, GpuMat& valbuf, GpuMat& locbuf);
 +
 +//! counts non-zero array elements
 +CV_EXPORTS int countNonZero(const GpuMat& src);
 +CV_EXPORTS int countNonZero(const GpuMat& src, GpuMat& buf);
 +
 +//! reduces a matrix to a vector
 +CV_EXPORTS void reduce(const GpuMat& mtx, GpuMat& vec, int dim, int reduceOp, int dtype = -1, Stream& stream = Stream::Null());
 +
 +
 +///////////////////////////// Calibration 3D //////////////////////////////////
 +
 +CV_EXPORTS void transformPoints(const GpuMat& src, const Mat& rvec, const Mat& tvec,
 +                                GpuMat& dst, Stream& stream = Stream::Null());
 +
 +CV_EXPORTS void projectPoints(const GpuMat& src, const Mat& rvec, const Mat& tvec,
 +                              const Mat& camera_mat, const Mat& dist_coef, GpuMat& dst,
 +                              Stream& stream = Stream::Null());
 +
 +CV_EXPORTS void solvePnPRansac(const Mat& object, const Mat& image, const Mat& camera_mat,
 +                               const Mat& dist_coef, Mat& rvec, Mat& tvec, bool use_extrinsic_guess=false,
 +                               int num_iters=100, float max_dist=8.0, int min_inlier_count=100,
 +                               std::vector<int>* inliers=NULL);
 +
 +//////////////////////////////// Image Labeling ////////////////////////////////
 +
 +//!performs labeling via graph cuts of a 2D regular 4-connected graph.
 +CV_EXPORTS void graphcut(GpuMat& terminals, GpuMat& leftTransp, GpuMat& rightTransp, GpuMat& top, GpuMat& bottom, GpuMat& labels,
 +                         GpuMat& buf, Stream& stream = Stream::Null());
 +
 +//!performs labeling via graph cuts of a 2D regular 8-connected graph.
 +CV_EXPORTS void graphcut(GpuMat& terminals, GpuMat& leftTransp, GpuMat& rightTransp, GpuMat& top, GpuMat& topLeft, GpuMat& topRight,
 +                         GpuMat& bottom, GpuMat& bottomLeft, GpuMat& bottomRight,
 +                         GpuMat& labels,
 +                         GpuMat& buf, Stream& stream = Stream::Null());
 +
 +//! compute mask for Generalized Flood fill componetns labeling.
 +CV_EXPORTS void connectivityMask(const GpuMat& image, GpuMat& mask, const cv::Scalar& lo, const cv::Scalar& hi, Stream& stream = Stream::Null());
 +
 +//! performs connected componnents labeling.
 +CV_EXPORTS void labelComponents(const GpuMat& mask, GpuMat& components, int flags = 0, Stream& stream = Stream::Null());
 +
 +////////////////////////////////// Histograms //////////////////////////////////
 +
 +//! Compute levels with even distribution. levels will have 1 row and nLevels cols and CV_32SC1 type.
 +CV_EXPORTS void evenLevels(GpuMat& levels, int nLevels, int lowerLevel, int upperLevel);
 +//! Calculates histogram with evenly distributed bins for signle channel source.
 +//! Supports CV_8UC1, CV_16UC1 and CV_16SC1 source types.
 +//! Output hist will have one row and histSize cols and CV_32SC1 type.
 +CV_EXPORTS void histEven(const GpuMat& src, GpuMat& hist, int histSize, int lowerLevel, int upperLevel, Stream& stream = Stream::Null());
 +CV_EXPORTS void histEven(const GpuMat& src, GpuMat& hist, GpuMat& buf, int histSize, int lowerLevel, int upperLevel, Stream& stream = Stream::Null());
 +//! Calculates histogram with evenly distributed bins for four-channel source.
 +//! All channels of source are processed separately.
 +//! Supports CV_8UC4, CV_16UC4 and CV_16SC4 source types.
 +//! Output hist[i] will have one row and histSize[i] cols and CV_32SC1 type.
 +CV_EXPORTS void histEven(const GpuMat& src, GpuMat hist[4], int histSize[4], int lowerLevel[4], int upperLevel[4], Stream& stream = Stream::Null());
 +CV_EXPORTS void histEven(const GpuMat& src, GpuMat hist[4], GpuMat& buf, int histSize[4], int lowerLevel[4], int upperLevel[4], Stream& stream = Stream::Null());
 +//! Calculates histogram with bins determined by levels array.
 +//! levels must have one row and CV_32SC1 type if source has integer type or CV_32FC1 otherwise.
 +//! Supports CV_8UC1, CV_16UC1, CV_16SC1 and CV_32FC1 source types.
 +//! Output hist will have one row and (levels.cols-1) cols and CV_32SC1 type.
 +CV_EXPORTS void histRange(const GpuMat& src, GpuMat& hist, const GpuMat& levels, Stream& stream = Stream::Null());
 +CV_EXPORTS void histRange(const GpuMat& src, GpuMat& hist, const GpuMat& levels, GpuMat& buf, Stream& stream = Stream::Null());
 +//! Calculates histogram with bins determined by levels array.
 +//! All levels must have one row and CV_32SC1 type if source has integer type or CV_32FC1 otherwise.
 +//! All channels of source are processed separately.
 +//! Supports CV_8UC4, CV_16UC4, CV_16SC4 and CV_32FC4 source types.
 +//! Output hist[i] will have one row and (levels[i].cols-1) cols and CV_32SC1 type.
 +CV_EXPORTS void histRange(const GpuMat& src, GpuMat hist[4], const GpuMat levels[4], Stream& stream = Stream::Null());
 +CV_EXPORTS void histRange(const GpuMat& src, GpuMat hist[4], const GpuMat levels[4], GpuMat& buf, Stream& stream = Stream::Null());
 +
 +//! Calculates histogram for 8u one channel image
 +//! Output hist will have one row, 256 cols and CV32SC1 type.
 +CV_EXPORTS void calcHist(const GpuMat& src, GpuMat& hist, Stream& stream = Stream::Null());
 +CV_EXPORTS void calcHist(const GpuMat& src, GpuMat& hist, GpuMat& buf, Stream& stream = Stream::Null());
 +
 +//! normalizes the grayscale image brightness and contrast by normalizing its histogram
 +CV_EXPORTS void equalizeHist(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());
 +CV_EXPORTS void equalizeHist(const GpuMat& src, GpuMat& dst, GpuMat& hist, Stream& stream = Stream::Null());
 +CV_EXPORTS void equalizeHist(const GpuMat& src, GpuMat& dst, GpuMat& hist, GpuMat& buf, Stream& stream = Stream::Null());
 +
++class CV_EXPORTS CLAHE : public cv::CLAHE
++{
++public:
++    using cv::CLAHE::apply;
++    virtual void apply(InputArray src, OutputArray dst, Stream& stream) = 0;
++};
++CV_EXPORTS Ptr<cv::gpu::CLAHE> createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8));
++
 +//////////////////////////////// StereoBM_GPU ////////////////////////////////
 +
 +class CV_EXPORTS StereoBM_GPU
 +{
 +public:
 +    enum { BASIC_PRESET = 0, PREFILTER_XSOBEL = 1 };
 +
 +    enum { DEFAULT_NDISP = 64, DEFAULT_WINSZ = 19 };
 +
 +    //! the default constructor
 +    StereoBM_GPU();
 +    //! the full constructor taking the camera-specific preset, number of disparities and the SAD window size. ndisparities must be multiple of 8.
 +    StereoBM_GPU(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 GpuMat& left, const GpuMat& right, GpuMat& disparity, Stream& stream = Stream::Null());
 +
 +    //! Some heuristics that tries to estmate
 +    // if current GPU will be faster than 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:
 +    GpuMat minSSD, leBuf, riBuf;
 +};
 +
 +////////////////////////// StereoBeliefPropagation ///////////////////////////
 +// "Efficient Belief Propagation for Early Vision"
 +// P.Felzenszwalb
 +
 +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);
 +
 +    //! the default constructor
 +    explicit StereoBeliefPropagation(int ndisp  = DEFAULT_NDISP,
 +                                     int iters  = DEFAULT_ITERS,
 +                                     int levels = DEFAULT_LEVELS,
 +                                     int msg_type = CV_32F);
 +
 +    //! the full constructor taking the number of disparities, number of BP iterations on each level,
 +    //! number of levels, truncation of data cost, data weight,
 +    //! truncation of discontinuity cost and discontinuity single jump
 +    //! DataTerm = data_weight * min(fabs(I2-I1), max_data_term)
 +    //! DiscTerm = min(disc_single_jump * fabs(f1-f2), max_disc_term)
 +    //! please see paper for more details
 +    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);
 +
 +    //! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair,
 +    //! if disparity is empty output type will be CV_16S else output type will be disparity.type().
 +    void operator()(const GpuMat& left, const GpuMat& right, GpuMat& disparity, Stream& stream = Stream::Null());
 +
 +
 +    //! version for user specified data term
 +    void operator()(const GpuMat& data, GpuMat& disparity, Stream& stream = Stream::Null());
 +
 +    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:
 +    GpuMat u, d, l, r, u2, d2, l2, r2;
 +    std::vector<GpuMat> datas;
 +    GpuMat out;
 +};
 +
 +/////////////////////////// StereoConstantSpaceBP ///////////////////////////
 +// "A Constant-Space Belief Propagation Algorithm for Stereo Matching"
 +// Qingxiong Yang, Liang Wang, Narendra Ahuja
 +// http://vision.ai.uiuc.edu/~qyang6/
 +
 +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);
 +
 +    //! the default constructor
 +    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);
 +
 +    //! the full constructor taking the number of disparities, number of BP iterations on each level,
 +    //! number of levels, number of active disparity on the first level, truncation of data cost, data weight,
 +    //! truncation of discontinuity cost, discontinuity single jump and minimum disparity threshold
 +    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);
 +
 +    //! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair,
 +    //! if disparity is empty output type will be CV_16S else output type will be disparity.type().
 +    void operator()(const GpuMat& left, const GpuMat& right, GpuMat& disparity, Stream& stream = Stream::Null());
 +
 +    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:
 +    GpuMat messages_buffers;
 +
 +    GpuMat temp;
 +    GpuMat out;
 +};
 +
 +/////////////////////////// DisparityBilateralFilter ///////////////////////////
 +// Disparity map refinement using joint bilateral filtering given a single color image.
 +// Qingxiong Yang, Liang Wang, Narendra Ahuja
 +// http://vision.ai.uiuc.edu/~qyang6/
 +
 +class CV_EXPORTS DisparityBilateralFilter
 +{
 +public:
 +    enum { DEFAULT_NDISP  = 64 };
 +    enum { DEFAULT_RADIUS = 3 };
 +    enum { DEFAULT_ITERS  = 1 };
 +
 +    //! the default constructor
 +    explicit DisparityBilateralFilter(int ndisp = DEFAULT_NDISP, int radius = DEFAULT_RADIUS, int iters = DEFAULT_ITERS);
 +
 +    //! the full constructor taking the number of disparities, filter radius,
 +    //! number of iterations, truncation of data continuity, truncation of disparity continuity
 +    //! and filter range sigma
 +    DisparityBilateralFilter(int ndisp, int radius, int iters, float edge_threshold, float max_disc_threshold, float sigma_range);
 +
 +    //! the disparity map refinement operator. Refine disparity map using joint bilateral filtering given a single color image.
 +    //! disparity must have CV_8U or CV_16S type, image must have CV_8UC1 or CV_8UC3 type.
 +    void operator()(const GpuMat& disparity, const GpuMat& image, GpuMat& dst, Stream& stream = Stream::Null());
 +
 +private:
 +    int ndisp;
 +    int radius;
 +    int iters;
 +
 +    float edge_threshold;
 +    float max_disc_threshold;
 +    float sigma_range;
 +
 +    GpuMat table_color;
 +    GpuMat table_space;
 +};
 +
 +
 +//////////////// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector //////////////
 +struct CV_EXPORTS HOGConfidence
 +{
 +   double scale;
 +   std::vector<Point> locations;
 +   std::vector<double> confidences;
 +   std::vector<double> part_scores[4];
 +};
 +
 +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 GpuMat& img, std::vector<Point>& found_locations,
 +                double hit_threshold=0, Size win_stride=Size(),
 +                Size padding=Size());
 +
 +    void detectMultiScale(const GpuMat& 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 computeConfidence(const GpuMat& img, std::vector<Point>& hits, double hit_threshold,
 +                                                Size win_stride, Size padding, std::vector<Point>& locations, std::vector<double>& confidences);
 +
 +    void computeConfidenceMultiScale(const GpuMat& img, std::vector<Rect>& found_locations,
 +                                                                    double hit_threshold, Size win_stride, Size padding,
 +                                                                    std::vector<HOGConfidence> &conf_out, int group_threshold);
 +
 +    void getDescriptors(const GpuMat& img, Size win_stride,
 +                        GpuMat& 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:
 +    void computeBlockHistograms(const GpuMat& img);
 +    void computeGradient(const GpuMat& img, GpuMat& grad, GpuMat& 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;
 +    GpuMat detector;
 +
 +    // Results of the last classification step
 +    GpuMat labels, labels_buf;
 +    Mat labels_host;
 +
 +    // Results of the last histogram evaluation step
 +    GpuMat block_hists, block_hists_buf;
 +
 +    // Gradients conputation results
 +    GpuMat grad, qangle, grad_buf, qangle_buf;
 +
 +    // returns subbuffer with required size, reallocates buffer if nessesary.
 +    static GpuMat getBuffer(const Size& sz, int type, GpuMat& buf);
 +    static GpuMat getBuffer(int rows, int cols, int type, GpuMat& buf);
 +
 +    std::vector<GpuMat> image_scales;
 +};
 +
 +
 +////////////////////////////////// BruteForceMatcher //////////////////////////////////
 +
 +class CV_EXPORTS BFMatcher_GPU
 +{
 +public:
 +    explicit BFMatcher_GPU(int norm = cv::NORM_L2);
 +
 +    // Add descriptors to train descriptor collection
 +    void add(const std::vector<GpuMat>& descCollection);
 +
 +    // Get train descriptors collection
 +    const std::vector<GpuMat>& 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 GpuMat& query, const GpuMat& train,
 +        GpuMat& trainIdx, GpuMat& distance,
 +        const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null());
 +
 +    // Download trainIdx and distance and convert it to CPU vector with DMatch
 +    static void matchDownload(const GpuMat& trainIdx, const GpuMat& 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 GpuMat& query, const GpuMat& train, std::vector<DMatch>& matches, const GpuMat& mask = GpuMat());
 +
 +    // Make gpu collection of trains and masks in suitable format for matchCollection function
 +    void makeGpuCollection(GpuMat& trainCollection, GpuMat& maskCollection, const std::vector<GpuMat>& masks = std::vector<GpuMat>());
 +
 +    // Find one best match from train collection for each query descriptor
 +    void matchCollection(const GpuMat& query, const GpuMat& trainCollection,
 +        GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance,
 +        const GpuMat& masks = GpuMat(), Stream& stream = Stream::Null());
 +
 +    // Download trainIdx, imgIdx and distance and convert it to vector with DMatch
 +    static void matchDownload(const GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& 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 GpuMat& query, std::vector<DMatch>& matches, const std::vector<GpuMat>& masks = std::vector<GpuMat>());
 +
 +    // Find k best matches for each query descriptor (in increasing order of distances)
 +    void knnMatchSingle(const GpuMat& query, const GpuMat& train,
 +        GpuMat& trainIdx, GpuMat& distance, GpuMat& allDist, int k,
 +        const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null());
 +
 +    // 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 GpuMat& trainIdx, const GpuMat& 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 GpuMat& query, const GpuMat& train,
 +        std::vector< std::vector<DMatch> >& matches, int k, const GpuMat& mask = GpuMat(),
 +        bool compactResult = false);
 +
 +    // Find k best matches from train collection for each query descriptor (in increasing order of distances)
 +    void knnMatch2Collection(const GpuMat& query, const GpuMat& trainCollection,
 +        GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance,
 +        const GpuMat& maskCollection = GpuMat(), Stream& stream = Stream::Null());
 +
 +    // 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 GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& 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 GpuMat& query, std::vector< std::vector<DMatch> >& matches, int k,
 +        const std::vector<GpuMat>& masks = std::vector<GpuMat>(), 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 GpuMat& query, const GpuMat& train,
 +        GpuMat& trainIdx, GpuMat& distance, GpuMat& nMatches, float maxDistance,
 +        const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null());
 +
 +    // 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 GpuMat& trainIdx, const GpuMat& distance, const GpuMat& 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 GpuMat& query, const GpuMat& train,
 +        std::vector< std::vector<DMatch> >& matches, float maxDistance,
 +        const GpuMat& mask = GpuMat(), 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 GpuMat& query, GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance, GpuMat& nMatches, float maxDistance,
 +        const std::vector<GpuMat>& masks = std::vector<GpuMat>(), Stream& stream = Stream::Null());
 +
 +    // 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 GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& distance, const GpuMat& 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 GpuMat& query, std::vector< std::vector<DMatch> >& matches, float maxDistance,
 +        const std::vector<GpuMat>& masks = std::vector<GpuMat>(), bool compactResult = false);
 +
 +    int norm;
 +
 +private:
 +    std::vector<GpuMat> trainDescCollection;
 +};
 +
 +template <class Distance>
 +class CV_EXPORTS BruteForceMatcher_GPU;
 +
 +template <typename T>
 +class CV_EXPORTS BruteForceMatcher_GPU< L1<T> > : public BFMatcher_GPU
 +{
 +public:
 +    explicit BruteForceMatcher_GPU() : BFMatcher_GPU(NORM_L1) {}
 +    explicit BruteForceMatcher_GPU(L1<T> /*d*/) : BFMatcher_GPU(NORM_L1) {}
 +};
 +template <typename T>
 +class CV_EXPORTS BruteForceMatcher_GPU< L2<T> > : public BFMatcher_GPU
 +{
 +public:
 +    explicit BruteForceMatcher_GPU() : BFMatcher_GPU(NORM_L2) {}
 +    explicit BruteForceMatcher_GPU(L2<T> /*d*/) : BFMatcher_GPU(NORM_L2) {}
 +};
 +template <> class CV_EXPORTS BruteForceMatcher_GPU< Hamming > : public BFMatcher_GPU
 +{
 +public:
 +    explicit BruteForceMatcher_GPU() : BFMatcher_GPU(NORM_HAMMING) {}
 +    explicit BruteForceMatcher_GPU(Hamming /*d*/) : BFMatcher_GPU(NORM_HAMMING) {}
 +};
 +
 +////////////////////////////////// CascadeClassifier_GPU //////////////////////////////////////////
 +// The cascade classifier class for object detection: supports old haar and new lbp xlm formats and nvbin for haar cascades olny.
 +class CV_EXPORTS CascadeClassifier_GPU
 +{
 +public:
 +    CascadeClassifier_GPU();
 +    CascadeClassifier_GPU(const String& filename);
 +    ~CascadeClassifier_GPU();
 +
 +    bool empty() const;
 +    bool load(const String& filename);
 +    void release();
 +
 +    /* returns number of detected objects */
 +    int detectMultiScale(const GpuMat& image, GpuMat& objectsBuf, double scaleFactor = 1.2, int minNeighbors = 4, Size minSize = Size());
 +    int detectMultiScale(const GpuMat& image, GpuMat& objectsBuf, Size maxObjectSize, Size minSize = Size(), double scaleFactor = 1.1, int minNeighbors = 4);
 +
 +    bool findLargestObject;
 +    bool visualizeInPlace;
 +
 +    Size getClassifierSize() const;
 +
 +private:
 +    struct CascadeClassifierImpl;
 +    CascadeClassifierImpl* impl;
 +    struct HaarCascade;
 +    struct LbpCascade;
 +    friend class CascadeClassifier_GPU_LBP;
 +};
 +
 +////////////////////////////////// FAST //////////////////////////////////////////
 +
 +class CV_EXPORTS FAST_GPU
 +{
 +public:
 +    enum
 +    {
 +        LOCATION_ROW = 0,
 +        RESPONSE_ROW,
 +        ROWS_COUNT
 +    };
 +
 +    // all features have same size
 +    static const int FEATURE_SIZE = 7;
 +
 +    explicit FAST_GPU(int threshold, bool nonmaxSupression = true, double keypointsRatio = 0.05);
 +
 +    //! finds the keypoints using FAST detector
 +    //! supports only CV_8UC1 images
 +    void operator ()(const GpuMat& image, const GpuMat& mask, GpuMat& keypoints);
 +    void operator ()(const GpuMat& image, const GpuMat& mask, std::vector<KeyPoint>& keypoints);
 +
 +    //! download keypoints from device to host memory
 +    static void downloadKeypoints(const GpuMat& 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 GpuMat& image, const GpuMat& mask);
 +
 +    //! get final array of keypoints
 +    //! performs nonmax supression if needed
 +    //! return final count of keypoints
 +    int getKeyPoints(GpuMat& keypoints);
 +
 +private:
 +    GpuMat kpLoc_;
 +    int count_;
 +
 +    GpuMat score_;
 +
 +    GpuMat d_keypoints_;
 +};
 +
 +////////////////////////////////// ORB //////////////////////////////////////////
 +
 +class CV_EXPORTS ORB_GPU
 +{
 +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_GPU(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 GpuMat& image, const GpuMat& mask, std::vector<KeyPoint>& keypoints);
 +    void operator()(const GpuMat& image, const GpuMat& mask, GpuMat& 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 GpuMat& image, const GpuMat& mask, std::vector<KeyPoint>& keypoints, GpuMat& descriptors);
 +    void operator()(const GpuMat& image, const GpuMat& mask, GpuMat& keypoints, GpuMat& descriptors);
 +
 +    //! download keypoints from device to host memory
 +    static void downloadKeyPoints(const GpuMat& 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 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 GpuMat& image, const GpuMat& mask);
 +
 +    void computeKeyPointsPyramid();
 +
 +    void computeDescriptors(GpuMat& descriptors);
 +
 +    void mergeKeyPoints(GpuMat& 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
 +    GpuMat pattern_;
 +
 +    std::vector<GpuMat> imagePyr_;
 +    std::vector<GpuMat> maskPyr_;
 +
 +    GpuMat buf_;
 +
 +    std::vector<GpuMat> keyPointsPyr_;
 +    std::vector<int> keyPointsCount_;
 +
 +    FAST_GPU fastDetector_;
 +
 +    Ptr<FilterEngine_GPU> blurFilter;
 +
 +    GpuMat d_keypoints_;
 +};
 +
 +////////////////////////////////// Optical Flow //////////////////////////////////////////
 +
 +class CV_EXPORTS BroxOpticalFlow
 +{
 +public:
 +    BroxOpticalFlow(float alpha_, float gamma_, float scale_factor_, int inner_iterations_, int outer_iterations_, int solver_iterations_) :
 +        alpha(alpha_), gamma(gamma_), scale_factor(scale_factor_),
 +        inner_iterations(inner_iterations_), outer_iterations(outer_iterations_), solver_iterations(solver_iterations_)
 +    {
 +    }
 +
 +    //! Compute optical flow
 +    //! frame0 - source frame (supports only CV_32FC1 type)
 +    //! frame1 - frame to track (with the same size and type as frame0)
 +    //! u      - flow horizontal component (along x axis)
 +    //! v      - flow vertical component (along y axis)
 +    void operator ()(const GpuMat& frame0, const GpuMat& frame1, GpuMat& u, GpuMat& v, Stream& stream = Stream::Null());
 +
 +    //! flow smoothness
 +    float alpha;
 +
 +    //! gradient constancy importance
 +    float gamma;
 +
 +    //! pyramid scale factor
 +    float scale_factor;
 +
 +    //! number of lagged non-linearity iterations (inner loop)
 +    int inner_iterations;
 +
 +    //! number of warping iterations (number of pyramid levels)
 +    int outer_iterations;
 +
 +    //! number of linear system solver iterations
 +    int solver_iterations;
 +
 +    GpuMat buf;
 +};
 +
 +class CV_EXPORTS GoodFeaturesToTrackDetector_GPU
 +{
 +public:
 +    explicit GoodFeaturesToTrackDetector_GPU(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 GpuMat& image, GpuMat& corners, const GpuMat& mask = GpuMat());
 +
 +    int maxCorners;
 +    double qualityLevel;
 +    double minDistance;
 +
 +    int blockSize;
 +    bool useHarrisDetector;
 +    double harrisK;
 +
 +    void releaseMemory()
 +    {
 +        Dx_.release();
 +        Dy_.release();
 +        buf_.release();
 +        eig_.release();
 +        minMaxbuf_.release();
 +        tmpCorners_.release();
 +    }
 +
 +private:
 +    GpuMat Dx_;
 +    GpuMat Dy_;
 +    GpuMat buf_;
 +    GpuMat eig_;
 +    GpuMat minMaxbuf_;
 +    GpuMat tmpCorners_;
 +};
 +
 +inline GoodFeaturesToTrackDetector_GPU::GoodFeaturesToTrackDetector_GPU(int maxCorners_, double qualityLevel_, double minDistance_,
 +        int blockSize_, bool useHarrisDetector_, double harrisK_)
 +{
 +    maxCorners = maxCorners_;
 +    qualityLevel = qualityLevel_;
 +    minDistance = minDistance_;
 +    blockSize = blockSize_;
 +    useHarrisDetector = useHarrisDetector_;
 +    harrisK = harrisK_;
 +}
 +
 +
 +class CV_EXPORTS PyrLKOpticalFlow
 +{
 +public:
 +    PyrLKOpticalFlow();
 +
 +    void sparse(const GpuMat& prevImg, const GpuMat& nextImg, const GpuMat& prevPts, GpuMat& nextPts,
 +        GpuMat& status, GpuMat* err = 0);
 +
 +    void dense(const GpuMat& prevImg, const GpuMat& nextImg, GpuMat& u, GpuMat& v, GpuMat* err = 0);
 +
 +    void releaseMemory();
 +
 +    Size winSize;
 +    int maxLevel;
 +    int iters;
 +    bool useInitialFlow;
 +
 +private:
 +    std::vector<GpuMat> prevPyr_;
 +    std::vector<GpuMat> nextPyr_;
 +
 +    GpuMat buf_;
 +
 +    GpuMat uPyr_[2];
 +    GpuMat vPyr_[2];
 +};
 +
 +
 +class CV_EXPORTS FarnebackOpticalFlow
 +{
 +public:
 +    FarnebackOpticalFlow()
 +    {
 +        numLevels = 5;
 +        pyrScale = 0.5;
 +        fastPyramids = false;
 +        winSize = 13;
 +        numIters = 10;
 +        polyN = 5;
 +        polySigma = 1.1;
 +        flags = 0;
 +    }
 +
 +    int numLevels;
 +    double pyrScale;
 +    bool fastPyramids;
 +    int winSize;
 +    int numIters;
 +    int polyN;
 +    double polySigma;
 +    int flags;
 +
 +    void operator ()(const GpuMat &frame0, const GpuMat &frame1, GpuMat &flowx, GpuMat &flowy, Stream &s = Stream::Null());
 +
 +    void releaseMemory()
 +    {
 +        frames_[0].release();
 +        frames_[1].release();
 +        pyrLevel_[0].release();
 +        pyrLevel_[1].release();
 +        M_.release();
 +        bufM_.release();
 +        R_[0].release();
 +        R_[1].release();
 +        blurredFrame_[0].release();
 +        blurredFrame_[1].release();
 +        pyramid0_.clear();
 +        pyramid1_.clear();
 +    }
 +
 +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 GpuMat& R0, const GpuMat& R1, GpuMat& flowx, GpuMat &flowy,
 +            GpuMat& M, GpuMat &bufM, int blockSize, bool updateMatrices, Stream streams[]);
 +
 +    void updateFlow_gaussianBlur(
 +            const GpuMat& R0, const GpuMat& R1, GpuMat& flowx, GpuMat& flowy,
 +            GpuMat& M, GpuMat &bufM, int blockSize, bool updateMatrices, Stream streams[]);
 +
 +    GpuMat frames_[2];
 +    GpuMat pyrLevel_[2], M_, bufM_, R_[2], blurredFrame_[2];
 +    std::vector<GpuMat> pyramid0_, pyramid1_;
 +};
 +
 +
 +// 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_GPU
 +{
 +public:
 +    OpticalFlowDual_TVL1_GPU();
 +
 +    void operator ()(const GpuMat& I0, const GpuMat& I1, GpuMat& flowx, GpuMat& 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 GpuMat& I0, const GpuMat& I1, GpuMat& u1, GpuMat& u2);
 +
 +    std::vector<GpuMat> I0s;
 +    std::vector<GpuMat> I1s;
 +    std::vector<GpuMat> u1s;
 +    std::vector<GpuMat> u2s;
 +
 +    GpuMat I1x_buf;
 +    GpuMat I1y_buf;
 +
 +    GpuMat I1w_buf;
 +    GpuMat I1wx_buf;
 +    GpuMat I1wy_buf;
 +
 +    GpuMat grad_buf;
 +    GpuMat rho_c_buf;
 +
 +    GpuMat p11_buf;
 +    GpuMat p12_buf;
 +    GpuMat p21_buf;
 +    GpuMat p22_buf;
 +
 +    GpuMat diff_buf;
 +    GpuMat norm_buf;
 +};
 +
 +
 +//! Calculates optical flow for 2 images using block matching algorithm */
 +CV_EXPORTS void calcOpticalFlowBM(const GpuMat& prev, const GpuMat& curr,
 +                                  Size block_size, Size shift_size, Size max_range, bool use_previous,
 +                                  GpuMat& velx, GpuMat& vely, GpuMat& buf,
 +                                  Stream& stream = Stream::Null());
 +
 +class CV_EXPORTS FastOpticalFlowBM
 +{
 +public:
 +    void operator ()(const GpuMat& I0, const GpuMat& I1, GpuMat& flowx, GpuMat& flowy, int search_window = 21, int block_window = 7, Stream& s = Stream::Null());
 +
 +private:
 +    GpuMat buffer;
 +    GpuMat extended_I0;
 +    GpuMat extended_I1;
 +};
 +
 +
 +//! 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 GpuMat;
 +//!            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 GpuMat& frame0, const GpuMat& frame1,
 +                                  const GpuMat& fu, const GpuMat& fv,
 +                                  const GpuMat& bu, const GpuMat& bv,
 +                                  float pos, GpuMat& newFrame, GpuMat& buf,
 +                                  Stream& stream = Stream::Null());
 +
 +CV_EXPORTS void createOpticalFlowNeedleMap(const GpuMat& u, const GpuMat& v, GpuMat& vertex, GpuMat& colors);
 +
 +
 +//////////////////////// Background/foreground segmentation ////////////////////////
 +
 +// Foreground Object Detection from Videos Containing Complex Background.
 +// Liyuan Li, Weimin Huang, Irene Y.H. Gu, and Qi Tian.
 +// ACM MM2003 9p
 +class CV_EXPORTS FGDStatModel
 +{
 +public:
 +    struct CV_EXPORTS Params
 +    {
 +        int Lc;  // Quantized levels per 'color' component. Power of two, typically 32, 64 or 128.
 +        int N1c; // Number of color vectors used to model normal background color variation at a given pixel.
 +        int N2c; // Number of color vectors retained at given pixel.  Must be > N1c, typically ~ 5/3 of N1c.
 +        // Used to allow the first N1c vectors to adapt over time to changing background.
 +
 +        int Lcc;  // Quantized levels per 'color co-occurrence' component.  Power of two, typically 16, 32 or 64.
 +        int N1cc; // Number of color co-occurrence vectors used to model normal background color variation at a given pixel.
 +        int N2cc; // Number of color co-occurrence vectors retained at given pixel.  Must be > N1cc, typically ~ 5/3 of N1cc.
 +        // Used to allow the first N1cc vectors to adapt over time to changing background.
 +
 +        bool is_obj_without_holes; // If TRUE we ignore holes within foreground blobs. Defaults to TRUE.
 +        int perform_morphing;     // Number of erode-dilate-erode foreground-blob cleanup iterations.
 +        // These erase one-pixel junk blobs and merge almost-touching blobs. Default value is 1.
 +
 +        float alpha1; // How quickly we forget old background pixel values seen. Typically set to 0.1.
 +        float alpha2; // "Controls speed of feature learning". Depends on T. Typical value circa 0.005.
 +        float alpha3; // Alternate to alpha2, used (e.g.) for quicker initial convergence. Typical value 0.1.
 +
 +        float delta;   // Affects color and color co-occurrence quantization, typically set to 2.
 +        float T;       // A percentage value which determines when new features can be recognized as new background. (Typically 0.9).
 +        float minArea; // Discard foreground blobs whose bounding box is smaller than this threshold.
 +
 +        // default Params
 +        Params();
 +    };
 +
 +    // out_cn - channels count in output result (can be 3 or 4)
 +    // 4-channels require more memory, but a bit faster
 +    explicit FGDStatModel(int out_cn = 3);
 +    explicit FGDStatModel(const cv::gpu::GpuMat& firstFrame, const Params& params = Params(), int out_cn = 3);
 +
 +    ~FGDStatModel();
 +
 +    void create(const cv::gpu::GpuMat& firstFrame, const Params& params = Params());
 +    void release();
 +
 +    int update(const cv::gpu::GpuMat& curFrame);
 +
 +    //8UC3 or 8UC4 reference background image
 +    cv::gpu::GpuMat background;
 +
 +    //8UC1 foreground image
 +    cv::gpu::GpuMat foreground;
 +
 +    std::vector< std::vector<cv::Point> > foreground_regions;
 +
 +private:
 +    FGDStatModel(const FGDStatModel&);
 +    FGDStatModel& operator=(const FGDStatModel&);
 +
 +    class Impl;
 +    std::auto_ptr<Impl> impl_;
 +};
 +
 +/*!
 + 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_GPU
 +{
 +public:
 +    //! the default constructor
 +    MOG_GPU(int nmixtures = -1);
 +
 +    //! re-initiaization method
 +    void initialize(Size frameSize, int frameType);
 +
 +    //! the update operator
 +    void operator()(const GpuMat& frame, GpuMat& fgmask, float learningRate = 0.0f, Stream& stream = Stream::Null());
 +
 +    //! computes a background image which are the mean of all background gaussians
 +    void getBackgroundImage(GpuMat& backgroundImage, Stream& stream = Stream::Null()) const;
 +
 +    //! releases all inner buffers
 +    void release();
 +
 +    int history;
 +    float varThreshold;
 +    float backgroundRatio;
 +    float noiseSigma;
 +
 +private:
 +    int nmixtures_;
 +
 +    Size frameSize_;
 +    int frameType_;
 +    int nframes_;
 +
 +    GpuMat weight_;
 +    GpuMat sortKey_;
 +    GpuMat mean_;
 +    GpuMat 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_GPU
 +{
 +public:
 +    //! the default constructor
 +    MOG2_GPU(int nmixtures = -1);
 +
 +    //! re-initiaization method
 +    void initialize(Size frameSize, int frameType);
 +
 +    //! the update operator
 +    void operator()(const GpuMat& frame, GpuMat& fgmask, float learningRate = -1.0f, Stream& stream = Stream::Null());
 +
 +    //! computes a background image which are the mean of all background gaussians
 +    void getBackgroundImage(GpuMat& backgroundImage, Stream& stream = Stream::Null()) 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_;
 +
 +    GpuMat weight_;
 +    GpuMat variance_;
 +    GpuMat mean_;
 +
 +    GpuMat bgmodelUsedModes_; //keep track of number of modes per pixel
 +};
 +
 +/**
 + * Background Subtractor module. Takes a series of images and returns a sequence of mask (8UC1)
 + * images of the same size, where 255 indicates Foreground and 0 represents Background.
 + * This class implements an algorithm described in "Visual Tracking of Human Visitors under
 + * Variable-Lighting Conditions for a Responsive Audio Art Installation," A. Godbehere,
 + * A. Matsukawa, K. Goldberg, American Control Conference, Montreal, June 2012.
 + */
 +class CV_EXPORTS GMG_GPU
 +{
 +public:
 +    GMG_GPU();
 +
 +    /**
 +     * Validate parameters and set up data structures for appropriate frame size.
 +     * @param frameSize Input frame size
 +     * @param min       Minimum value taken on by pixels in image sequence. Usually 0
 +     * @param max       Maximum value taken on by pixels in image sequence. e.g. 1.0 or 255
 +     */
 +    void initialize(Size frameSize, float min = 0.0f, float max = 255.0f);
 +
 +    /**
 +     * Performs single-frame background subtraction and builds up a statistical background image
 +     * model.
 +     * @param frame        Input frame
 +     * @param fgmask       Output mask image representing foreground and background pixels
 +     * @param stream       Stream for the asynchronous version
 +     */
 +    void operator ()(const GpuMat& frame, GpuMat& fgmask, float learningRate = -1.0f, Stream& stream = Stream::Null());
 +
 +    //! Releases all inner buffers
 +    void release();
 +
 +    //! Total number of distinct colors to maintain in histogram.
 +    int maxFeatures;
 +
 +    //! Set between 0.0 and 1.0, determines how quickly features are "forgotten" from histograms.
 +    float learningRate;
 +
 +    //! Number of frames of video to use to initialize histograms.
 +    int numInitializationFrames;
 +
 +    //! Number of discrete levels in each channel to be used in histograms.
 +    int quantizationLevels;
 +
 +    //! Prior probability that any given pixel is a background pixel. A sensitivity parameter.
 +    float backgroundPrior;
 +
 +    //! Value above which pixel is determined to be FG.
 +    float decisionThreshold;
 +
 +    //! Smoothing radius, in pixels, for cleaning up FG image.
 +    int smoothingRadius;
 +
 +    //! Perform background model update.
 +    bool updateBackgroundModel;
 +
 +private:
 +    float maxVal_, minVal_;
 +
 +    Size frameSize_;
 +
 +    int frameNum_;
 +
 +    GpuMat nfeatures_;
 +    GpuMat colors_;
 +    GpuMat weights_;
 +
 +    Ptr<FilterEngine_GPU> boxFilter_;
 +    GpuMat buf_;
 +};
 +
 +////////////////////////////////// Video Encoding //////////////////////////////////
 +
 +// Works only under Windows
 +// Supports olny H264 video codec and AVI files
 +class CV_EXPORTS VideoWriter_GPU
 +{
 +public:
 +    struct EncoderParams;
 +
 +    // Callbacks for video encoder, use it if you want to work with raw video stream
 +    class EncoderCallBack;
 +
 +    enum SurfaceFormat
 +    {
 +        SF_UYVY = 0,
 +        SF_YUY2,
 +        SF_YV12,
 +        SF_NV12,
 +        SF_IYUV,
 +        SF_BGR,
 +        SF_GRAY = SF_BGR
 +    };
 +
 +    VideoWriter_GPU();
 +    VideoWriter_GPU(const String& fileName, cv::Size frameSize, double fps, SurfaceFormat format = SF_BGR);
 +    VideoWriter_GPU(const String& fileName, cv::Size frameSize, double fps, const EncoderParams& params, SurfaceFormat format = SF_BGR);
 +    VideoWriter_GPU(const cv::Ptr<EncoderCallBack>& encoderCallback, cv::Size frameSize, double fps, SurfaceFormat format = SF_BGR);
 +    VideoWriter_GPU(const cv::Ptr<EncoderCallBack>& encoderCallback, cv::Size frameSize, double fps, const EncoderParams& params, SurfaceFormat format = SF_BGR);
 +    ~VideoWriter_GPU();
 +
 +    // all methods throws cv::Exception if error occurs
 +    void open(const String& fileName, cv::Size frameSize, double fps, SurfaceFormat format = SF_BGR);
 +    void open(const String& fileName, cv::Size frameSize, double fps, const EncoderParams& params, SurfaceFormat format = SF_BGR);
 +    void open(const cv::Ptr<EncoderCallBack>& encoderCallback, cv::Size frameSize, double fps, SurfaceFormat format = SF_BGR);
 +    void open(const cv::Ptr<EncoderCallBack>& encoderCallback, cv::Size frameSize, double fps, const EncoderParams& params, SurfaceFormat format = SF_BGR);
 +
 +    bool isOpened() const;
 +    void close();
 +
 +    void write(const cv::gpu::GpuMat& image, bool lastFrame = false);
 +
 +    struct CV_EXPORTS EncoderParams
 +    {
 +        int       P_Interval;      //    NVVE_P_INTERVAL,
 +        int       IDR_Period;      //    NVVE_IDR_PERIOD,
 +        int       DynamicGOP;      //    NVVE_DYNAMIC_GOP,
 +        int       RCType;          //    NVVE_RC_TYPE,
 +        int       AvgBitrate;      //    NVVE_AVG_BITRATE,
 +        int       PeakBitrate;     //    NVVE_PEAK_BITRATE,
 +        int       QP_Level_Intra;  //    NVVE_QP_LEVEL_INTRA,
 +        int       QP_Level_InterP; //    NVVE_QP_LEVEL_INTER_P,
 +        int       QP_Level_InterB; //    NVVE_QP_LEVEL_INTER_B,
 +        int       DeblockMode;     //    NVVE_DEBLOCK_MODE,
 +        int       ProfileLevel;    //    NVVE_PROFILE_LEVEL,
 +        int       ForceIntra;      //    NVVE_FORCE_INTRA,
 +        int       ForceIDR;        //    NVVE_FORCE_IDR,
 +        int       ClearStat;       //    NVVE_CLEAR_STAT,
 +        int       DIMode;          //    NVVE_SET_DEINTERLACE,
 +        int       Presets;         //    NVVE_PRESETS,
 +        int       DisableCabac;    //    NVVE_DISABLE_CABAC,
 +        int       NaluFramingType; //    NVVE_CONFIGURE_NALU_FRAMING_TYPE
 +        int       DisableSPSPPS;   //    NVVE_DISABLE_SPS_PPS
 +
 +        EncoderParams();
 +        explicit EncoderParams(const String& configFile);
 +
 +        void load(const String& configFile);
 +        void save(const String& configFile) const;
 +    };
 +
 +    EncoderParams getParams() const;
 +
 +    class CV_EXPORTS EncoderCallBack
 +    {
 +    public:
 +        enum PicType
 +        {
 +            IFRAME = 1,
 +            PFRAME = 2,
 +            BFRAME = 3
 +        };
 +
 +        virtual ~EncoderCallBack() {}
 +
 +        // callback function to signal the start of bitstream that is to be encoded
 +        // must return pointer to buffer
 +        virtual uchar* acquireBitStream(int* bufferSize) = 0;
 +
 +        // callback function to signal that the encoded bitstream is ready to be written to file
 +        virtual void releaseBitStream(unsigned char* data, int size) = 0;
 +
 +        // callback function to signal that the encoding operation on the frame has started
 +        virtual void onBeginFrame(int frameNumber, PicType picType) = 0;
 +
 +        // callback function signals that the encoding operation on the frame has finished
 +        virtual void onEndFrame(int frameNumber, PicType picType) = 0;
 +    };
 +
 +private:
 +    VideoWriter_GPU(const VideoWriter_GPU&);
 +    VideoWriter_GPU& operator=(const VideoWriter_GPU&);
 +
 +    class Impl;
 +    std::auto_ptr<Impl> impl_;
 +};
 +
 +
 +////////////////////////////////// Video Decoding //////////////////////////////////////////
 +
 +namespace detail
 +{
 +    class FrameQueue;
 +    class VideoParser;
 +}
 +
 +class CV_EXPORTS VideoReader_GPU
 +{
 +public:
 +    enum Codec
 +    {
 +        MPEG1 = 0,
 +        MPEG2,
 +        MPEG4,
 +        VC1,
 +        H264,
 +        JPEG,
 +        H264_SVC,
 +        H264_MVC,
 +
 +        Uncompressed_YUV420 = (('I'<<24)|('Y'<<16)|('U'<<8)|('V')),   // Y,U,V (4:2:0)
 +        Uncompressed_YV12   = (('Y'<<24)|('V'<<16)|('1'<<8)|('2')),   // Y,V,U (4:2:0)
 +        Uncompressed_NV12   = (('N'<<24)|('V'<<16)|('1'<<8)|('2')),   // Y,UV  (4:2:0)
 +        Uncompressed_YUYV   = (('Y'<<24)|('U'<<16)|('Y'<<8)|('V')),   // YUYV/YUY2 (4:2:2)
 +        Uncompressed_UYVY   = (('U'<<24)|('Y'<<16)|('V'<<8)|('Y')),   // UYVY (4:2:2)
 +    };
 +
 +    enum ChromaFormat
 +    {
 +        Monochrome=0,
 +        YUV420,
 +        YUV422,
 +        YUV444,
 +    };
 +
 +    struct FormatInfo
 +    {
 +        Codec codec;
 +        ChromaFormat chromaFormat;
 +        int width;
 +        int height;
 +    };
 +
 +    class VideoSource;
 +
 +    VideoReader_GPU();
 +    explicit VideoReader_GPU(const String& filename);
 +    explicit VideoReader_GPU(const cv::Ptr<VideoSource>& source);
 +
 +    ~VideoReader_GPU();
 +
 +    void open(const String& filename);
 +    void open(const cv::Ptr<VideoSource>& source);
 +    bool isOpened() const;
 +
 +    void close();
 +
 +    bool read(GpuMat& image);
 +
 +    FormatInfo format() const;
 +    void dumpFormat(std::ostream& st);
 +
 +    class CV_EXPORTS VideoSource
 +    {
 +    public:
 +        VideoSource() : frameQueue_(0), videoParser_(0) {}
 +        virtual ~VideoSource() {}
 +
 +        virtual FormatInfo format() const = 0;
 +        virtual void start() = 0;
 +        virtual void stop() = 0;
 +        virtual bool isStarted() const = 0;
 +        virtual bool hasError() const = 0;
 +
 +        void setFrameQueue(detail::FrameQueue* frameQueue) { frameQueue_ = frameQueue; }
 +        void setVideoParser(detail::VideoParser* videoParser) { videoParser_ = videoParser; }
 +
 +    protected:
 +        bool parseVideoData(const uchar* data, size_t size, bool endOfStream = false);
 +
 +    private:
 +        VideoSource(const VideoSource&);
 +        VideoSource& operator =(const VideoSource&);
 +
 +        detail::FrameQueue* frameQueue_;
 +        detail::VideoParser* videoParser_;
 +    };
 +
 +private:
 +    VideoReader_GPU(const VideoReader_GPU&);
 +    VideoReader_GPU& operator =(const VideoReader_GPU&);
 +
 +    class Impl;
 +    std::auto_ptr<Impl> impl_;
 +};
 +
 +//! removes points (CV_32FC2, single row matrix) with zero mask value
 +CV_EXPORTS void compactPoints(GpuMat &points0, GpuMat &points1, const GpuMat &mask);
 +
 +CV_EXPORTS void calcWobbleSuppressionMaps(
 +        int left, int idx, int right, Size size, const Mat &ml, const Mat &mr,
 +        GpuMat &mapx, GpuMat &mapy);
 +
 +} // namespace gpu
 +
 +} // namespace cv
 +
 +#endif /* __OPENCV_GPU_HPP__ */
  //
  //M*/
  
 -#ifndef __OPENCV_GPU_HPP__
 -#define __OPENCV_GPU_HPP__
 -
 -#ifndef SKIP_INCLUDES
 -#include <vector>
 -#include <memory>
 -#include <iosfwd>
 +#ifdef __OPENCV_BUILD
 +#error this is a compatibility header which should not be used inside the OpenCV library
  #endif
  
- #include "opencv2/gpu.hpp"
 -#include "opencv2/core/gpumat.hpp"
 -#include "opencv2/imgproc/imgproc.hpp"
 -#include "opencv2/objdetect/objdetect.hpp"
 -#include "opencv2/features2d/features2d.hpp"
 -
 -namespace cv { namespace gpu {
 -
 -//////////////////////////////// CudaMem ////////////////////////////////
 -// CudaMem is limited cv::Mat with page locked memory allocation.
 -// Page locked memory is only needed for async and faster coping to GPU.
 -// It is convertable to cv::Mat header without reference counting
 -// so you can use it with other opencv functions.
 -
 -// Page-locks the matrix m memory and maps it for the device(s)
 -CV_EXPORTS void registerPageLocked(Mat& m);
 -// Unmaps the memory of matrix m, and makes it pageable again.
 -CV_EXPORTS void unregisterPageLocked(Mat& m);
 -
 -class CV_EXPORTS CudaMem
 -{
 -public:
 -    enum  { ALLOC_PAGE_LOCKED = 1, ALLOC_ZEROCOPY = 2, ALLOC_WRITE_COMBINED = 4 };
 -
 -    CudaMem();
 -    CudaMem(const CudaMem& m);
 -
 -    CudaMem(int rows, int cols, int type, int _alloc_type = ALLOC_PAGE_LOCKED);
 -    CudaMem(Size size, int type, int alloc_type = ALLOC_PAGE_LOCKED);
 -
 -
 -    //! creates from cv::Mat with coping data
 -    explicit CudaMem(const Mat& m, int alloc_type = ALLOC_PAGE_LOCKED);
 -
 -    ~CudaMem();
 -
 -    CudaMem& operator = (const CudaMem& m);
 -
 -    //! returns deep copy of the matrix, i.e. the data is copied
 -    CudaMem clone() const;
 -
 -    //! allocates new matrix data unless the matrix already has specified size and type.
 -    void create(int rows, int cols, int type, int alloc_type = ALLOC_PAGE_LOCKED);
 -    void create(Size size, int type, int alloc_type = ALLOC_PAGE_LOCKED);
 -
 -    //! decrements reference counter and released memory if needed.
 -    void release();
 -
 -    //! returns matrix header with disabled reference counting for CudaMem data.
 -    Mat createMatHeader() const;
 -    operator Mat() const;
 -
 -    //! maps host memory into device address space and returns GpuMat header for it. Throws exception if not supported by hardware.
 -    GpuMat createGpuMatHeader() const;
 -    operator GpuMat() const;
 -
 -    //returns if host memory can be mapperd to gpu address space;
 -    static bool canMapHostMemory();
 -
 -    // Please see cv::Mat for descriptions
 -    bool isContinuous() const;
 -    size_t elemSize() const;
 -    size_t elemSize1() const;
 -    int type() const;
 -    int depth() const;
 -    int channels() const;
 -    size_t step1() const;
 -    Size size() const;
 -    bool empty() const;
 -
 -
 -    // Please see cv::Mat for descriptions
 -    int flags;
 -    int rows, cols;
 -    size_t step;
 -
 -    uchar* data;
 -    int* refcount;
 -
 -    uchar* datastart;
 -    uchar* dataend;
 -
 -    int alloc_type;
 -};
 -
 -//////////////////////////////// CudaStream ////////////////////////////////
 -// Encapculates Cuda Stream. Provides interface for async coping.
 -// Passed to each function that supports async kernel execution.
 -// Reference counting is enabled
 -
 -class CV_EXPORTS Stream
 -{
 -public:
 -    Stream();
 -    ~Stream();
 -
 -    Stream(const Stream&);
 -    Stream& operator =(const Stream&);
 -
 -    bool queryIfComplete();
 -    void waitForCompletion();
 -
 -    //! downloads asynchronously
 -    // Warning! cv::Mat must point to page locked memory (i.e. to CudaMem data or to its subMat)
 -    void enqueueDownload(const GpuMat& src, CudaMem& dst);
 -    void enqueueDownload(const GpuMat& src, Mat& dst);
 -
 -    //! uploads asynchronously
 -    // Warning! cv::Mat must point to page locked memory (i.e. to CudaMem data or to its ROI)
 -    void enqueueUpload(const CudaMem& src, GpuMat& dst);
 -    void enqueueUpload(const Mat& src, GpuMat& dst);
 -
 -    //! copy asynchronously
 -    void enqueueCopy(const GpuMat& src, GpuMat& dst);
 -
 -    //! memory set asynchronously
 -    void enqueueMemSet(GpuMat& src, Scalar val);
 -    void enqueueMemSet(GpuMat& src, Scalar val, const GpuMat& mask);
 -
 -    //! converts matrix type, ex from float to uchar depending on type
 -    void enqueueConvert(const GpuMat& src, GpuMat& dst, int dtype, double a = 1, double b = 0);
 -
 -    //! adds a callback to be called on the host after all currently enqueued items in the stream have completed
 -    typedef void (*StreamCallback)(Stream& stream, int status, void* userData);
 -    void enqueueHostCallback(StreamCallback callback, void* userData);
 -
 -    static Stream& Null();
 -
 -    operator bool() const;
 -
 -private:
 -    struct Impl;
 -
 -    explicit Stream(Impl* impl);
 -    void create();
 -    void release();
 -
 -    Impl *impl;
 -
 -    friend struct StreamAccessor;
 -};
 -
 -
 -//////////////////////////////// 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_) : ksize(ksize_), anchor(anchor_) {}
 -    virtual ~BaseRowFilter_GPU() {}
 -    virtual void operator()(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null()) = 0;
 -    int ksize, anchor;
 -};
 -
 -/*!
 -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_) : ksize(ksize_), anchor(anchor_) {}
 -    virtual ~BaseColumnFilter_GPU() {}
 -    virtual void operator()(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null()) = 0;
 -    int ksize, anchor;
 -};
 -
 -/*!
 -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_) : ksize(ksize_), anchor(anchor_) {}
 -    virtual ~BaseFilter_GPU() {}
 -    virtual void operator()(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null()) = 0;
 -    Size ksize;
 -    Point anchor;
 -};
 -
 -/*!
 -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 GpuMat& src, GpuMat& dst, Rect roi = Rect(0,0,-1,-1), Stream& stream = Stream::Null()) = 0;
 -};
 -
 -//! returns the non-separable filter engine with the specified filter
 -CV_EXPORTS Ptr<FilterEngine_GPU> createFilter2D_GPU(const Ptr<BaseFilter_GPU>& filter2D, int srcType, int dstType);
 -
 -//! 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, int srcType, int bufType, int dstType);
 -CV_EXPORTS Ptr<FilterEngine_GPU> createSeparableFilter_GPU(const Ptr<BaseRowFilter_GPU>& rowFilter,
 -    const Ptr<BaseColumnFilter_GPU>& columnFilter, int srcType, int bufType, int dstType, GpuMat& buf);
 -
 -//! returns horizontal 1D box filter
 -//! supports only CV_8UC1 source type and CV_32FC1 sum type
 -CV_EXPORTS Ptr<BaseRowFilter_GPU> getRowSumFilter_GPU(int srcType, int sumType, int ksize, int anchor = -1);
 -
 -//! returns vertical 1D box filter
 -//! supports only CV_8UC1 sum type and CV_32FC1 dst type
 -CV_EXPORTS Ptr<BaseColumnFilter_GPU> getColumnSumFilter_GPU(int sumType, int dstType, int ksize, int anchor = -1);
 -
 -//! returns 2D box filter
 -//! supports CV_8UC1 and CV_8UC4 source type, dst type must be the same as source type
 -CV_EXPORTS Ptr<BaseFilter_GPU> getBoxFilter_GPU(int srcType, int dstType, const Size& ksize, Point anchor = Point(-1, -1));
 -
 -//! returns box filter engine
 -CV_EXPORTS Ptr<FilterEngine_GPU> createBoxFilter_GPU(int srcType, int dstType, const Size& ksize,
 -    const Point& anchor = Point(-1,-1));
 -
 -//! returns 2D morphological filter
 -//! only MORPH_ERODE and MORPH_DILATE are supported
 -//! supports CV_8UC1 and CV_8UC4 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);
 -CV_EXPORTS Ptr<FilterEngine_GPU> createMorphologyFilter_GPU(int op, int type, const Mat& kernel, GpuMat& buf,
 -    const Point& anchor = Point(-1,-1), int iterations = 1);
 -
 -//! returns 2D filter with the specified kernel
 -//! supports CV_8U, CV_16U and CV_32F one and four channel image
 -CV_EXPORTS Ptr<BaseFilter_GPU> getLinearFilter_GPU(int srcType, int dstType, const Mat& kernel, Point anchor = Point(-1, -1), int borderType = BORDER_DEFAULT);
 -
 -//! returns the non-separable linear filter engine
 -CV_EXPORTS Ptr<FilterEngine_GPU> createLinearFilter_GPU(int srcType, int dstType, const Mat& kernel,
 -    Point anchor = Point(-1,-1), int borderType = BORDER_DEFAULT);
 -
 -//! returns the primitive row filter with the specified kernel.
 -//! supports only CV_8UC1, CV_8UC4, CV_16SC1, CV_16SC2, CV_32SC1, CV_32FC1 source type.
 -//! there are two version of algorithm: NPP and OpenCV.
 -//! NPP calls when srcType == CV_8UC1 or srcType == CV_8UC4 and bufType == srcType,
 -//! otherwise calls OpenCV version.
 -//! NPP supports only BORDER_CONSTANT border type.
 -//! OpenCV version supports only CV_32F as buffer depth and
 -//! BORDER_REFLECT101, BORDER_REPLICATE and BORDER_CONSTANT border types.
 -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.
 -//! supports only CV_8UC1, CV_8UC4, CV_16SC1, CV_16SC2, CV_32SC1, CV_32FC1 dst type.
 -//! there are two version of algorithm: NPP and OpenCV.
 -//! NPP calls when dstType == CV_8UC1 or dstType == CV_8UC4 and bufType == dstType,
 -//! otherwise calls OpenCV version.
 -//! NPP supports only BORDER_CONSTANT border type.
 -//! OpenCV version supports only CV_32F as buffer depth and
 -//! BORDER_REFLECT101, BORDER_REPLICATE and BORDER_CONSTANT border types.
 -CV_EXPORTS Ptr<BaseColumnFilter_GPU> getLinearColumnFilter_GPU(int bufType, int dstType, const Mat& columnKernel,
 -    int anchor = -1, int borderType = BORDER_DEFAULT);
 -
 -//! 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), int rowBorderType = BORDER_DEFAULT,
 -    int columnBorderType = -1);
 -CV_EXPORTS Ptr<FilterEngine_GPU> createSeparableLinearFilter_GPU(int srcType, int dstType, const Mat& rowKernel,
 -    const Mat& columnKernel, GpuMat& buf, const Point& anchor = Point(-1,-1), int rowBorderType = BORDER_DEFAULT,
 -    int columnBorderType = -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 rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);
 -CV_EXPORTS Ptr<FilterEngine_GPU> createDerivFilter_GPU(int srcType, int dstType, int dx, int dy, int ksize, GpuMat& buf,
 -                                                       int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);
 -
 -//! returns the Gaussian filter engine
 -CV_EXPORTS Ptr<FilterEngine_GPU> createGaussianFilter_GPU(int type, Size ksize, double sigma1, double sigma2 = 0,
 -                                                          int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);
 -CV_EXPORTS Ptr<FilterEngine_GPU> createGaussianFilter_GPU(int type, Size ksize, GpuMat& buf, double sigma1, double sigma2 = 0,
 -                                                          int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);
 -
 -//! returns maximum filter
 -CV_EXPORTS Ptr<BaseFilter_GPU> getMaxFilter_GPU(int srcType, int dstType, const Size& ksize, Point anchor = Point(-1,-1));
 -
 -//! returns minimum filter
 -CV_EXPORTS Ptr<BaseFilter_GPU> getMinFilter_GPU(int srcType, int dstType, const Size& ksize, Point anchor = Point(-1,-1));
 -
 -//! smooths the image using the normalized box filter
 -//! supports CV_8UC1, CV_8UC4 types
 -CV_EXPORTS void boxFilter(const GpuMat& src, GpuMat& dst, int ddepth, Size ksize, Point anchor = Point(-1,-1), Stream& stream = Stream::Null());
 -
 -//! a synonym for normalized box filter
 -static inline void blur(const GpuMat& src, GpuMat& dst, Size ksize, Point anchor = Point(-1,-1), Stream& stream = Stream::Null())
 -{
 -    boxFilter(src, dst, -1, ksize, anchor, stream);
 -}
 -
 -//! erodes the image (applies the local minimum operator)
 -CV_EXPORTS void erode(const GpuMat& src, GpuMat& dst, const Mat& kernel, Point anchor = Point(-1, -1), int iterations = 1);
 -CV_EXPORTS void erode(const GpuMat& src, GpuMat& dst, const Mat& kernel, GpuMat& buf,
 -                      Point anchor = Point(-1, -1), int iterations = 1,
 -                      Stream& stream = Stream::Null());
 -
 -//! dilates the image (applies the local maximum operator)
 -CV_EXPORTS void dilate(const GpuMat& src, GpuMat& dst, const Mat& kernel, Point anchor = Point(-1, -1), int iterations = 1);
 -CV_EXPORTS void dilate(const GpuMat& src, GpuMat& dst, const Mat& kernel, GpuMat& buf,
 -                       Point anchor = Point(-1, -1), int iterations = 1,
 -                       Stream& stream = Stream::Null());
 -
 -//! applies an advanced morphological operation to the image
 -CV_EXPORTS void morphologyEx(const GpuMat& src, GpuMat& dst, int op, const Mat& kernel, Point anchor = Point(-1, -1), int iterations = 1);
 -CV_EXPORTS void morphologyEx(const GpuMat& src, GpuMat& dst, int op, const Mat& kernel, GpuMat& buf1, GpuMat& buf2,
 -                             Point anchor = Point(-1, -1), int iterations = 1, Stream& stream = Stream::Null());
 -
 -//! applies non-separable 2D linear filter to the image
 -CV_EXPORTS void filter2D(const GpuMat& src, GpuMat& dst, int ddepth, const Mat& kernel, Point anchor=Point(-1,-1), int borderType = BORDER_DEFAULT, Stream& stream = Stream::Null());
 -
 -//! applies separable 2D linear filter to the image
 -CV_EXPORTS void sepFilter2D(const GpuMat& src, GpuMat& dst, int ddepth, const Mat& kernelX, const Mat& kernelY,
 -                            Point anchor = Point(-1,-1), int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);
 -CV_EXPORTS void sepFilter2D(const GpuMat& src, GpuMat& dst, int ddepth, const Mat& kernelX, const Mat& kernelY, GpuMat& buf,
 -                            Point anchor = Point(-1,-1), int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1,
 -                            Stream& stream = Stream::Null());
 -
 -//! applies generalized Sobel operator to the image
 -CV_EXPORTS void Sobel(const GpuMat& src, GpuMat& dst, int ddepth, int dx, int dy, int ksize = 3, double scale = 1,
 -                      int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);
 -CV_EXPORTS void Sobel(const GpuMat& src, GpuMat& dst, int ddepth, int dx, int dy, GpuMat& buf, int ksize = 3, double scale = 1,
 -                      int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1, Stream& stream = Stream::Null());
 -
 -//! applies the vertical or horizontal Scharr operator to the image
 -CV_EXPORTS void Scharr(const GpuMat& src, GpuMat& dst, int ddepth, int dx, int dy, double scale = 1,
 -                       int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);
 -CV_EXPORTS void Scharr(const GpuMat& src, GpuMat& dst, int ddepth, int dx, int dy, GpuMat& buf, double scale = 1,
 -                       int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1, Stream& stream = Stream::Null());
 -
 -//! smooths the image using Gaussian filter.
 -CV_EXPORTS void GaussianBlur(const GpuMat& src, GpuMat& dst, Size ksize, double sigma1, double sigma2 = 0,
 -                             int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1);
 -CV_EXPORTS void GaussianBlur(const GpuMat& src, GpuMat& dst, Size ksize, GpuMat& buf, double sigma1, double sigma2 = 0,
 -                             int rowBorderType = BORDER_DEFAULT, int columnBorderType = -1, Stream& stream = Stream::Null());
 -
 -//! applies Laplacian operator to the image
 -//! supports only ksize = 1 and ksize = 3
 -CV_EXPORTS void Laplacian(const GpuMat& src, GpuMat& dst, int ddepth, int ksize = 1, double scale = 1, int borderType = BORDER_DEFAULT, Stream& stream = Stream::Null());
 -
 -
 -////////////////////////////// Arithmetics ///////////////////////////////////
 -
 -//! implements generalized matrix product algorithm GEMM from BLAS
 -CV_EXPORTS void gemm(const GpuMat& src1, const GpuMat& src2, double alpha,
 -    const GpuMat& src3, double beta, GpuMat& dst, int flags = 0, Stream& stream = Stream::Null());
 -
 -//! transposes the matrix
 -//! supports matrix with element size = 1, 4 and 8 bytes (CV_8UC1, CV_8UC4, CV_16UC2, CV_32FC1, etc)
 -CV_EXPORTS void transpose(const GpuMat& src1, GpuMat& dst, Stream& stream = Stream::Null());
 -
 -//! reverses the order of the rows, columns or both in a matrix
 -//! supports 1, 3 and 4 channels images with CV_8U, CV_16U, CV_32S or CV_32F depth
 -CV_EXPORTS void flip(const GpuMat& a, GpuMat& b, int flipCode, Stream& stream = Stream::Null());
 -
 -//! 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
 -//! supports CV_8UC1, CV_8UC3 types
 -CV_EXPORTS void LUT(const GpuMat& src, const Mat& lut, GpuMat& dst, Stream& stream = Stream::Null());
 -
 -//! makes multi-channel array out of several single-channel arrays
 -CV_EXPORTS void merge(const GpuMat* src, size_t n, GpuMat& dst, Stream& stream = Stream::Null());
 -
 -//! makes multi-channel array out of several single-channel arrays
 -CV_EXPORTS void merge(const vector<GpuMat>& src, GpuMat& dst, Stream& stream = Stream::Null());
 -
 -//! copies each plane of a multi-channel array to a dedicated array
 -CV_EXPORTS void split(const GpuMat& src, GpuMat* dst, Stream& stream = Stream::Null());
 -
 -//! copies each plane of a multi-channel array to a dedicated array
 -CV_EXPORTS void split(const GpuMat& src, vector<GpuMat>& dst, Stream& stream = Stream::Null());
 -
 -//! computes magnitude of complex (x(i).re, x(i).im) vector
 -//! supports only CV_32FC2 type
 -CV_EXPORTS void magnitude(const GpuMat& xy, GpuMat& magnitude, Stream& stream = Stream::Null());
 -
 -//! computes squared magnitude of complex (x(i).re, x(i).im) vector
 -//! supports only CV_32FC2 type
 -CV_EXPORTS void magnitudeSqr(const GpuMat& xy, GpuMat& magnitude, Stream& stream = Stream::Null());
 -
 -//! computes magnitude of each (x(i), y(i)) vector
 -//! supports only floating-point source
 -CV_EXPORTS void magnitude(const GpuMat& x, const GpuMat& y, GpuMat& magnitude, Stream& stream = Stream::Null());
 -
 -//! computes squared magnitude of each (x(i), y(i)) vector
 -//! supports only floating-point source
 -CV_EXPORTS void magnitudeSqr(const GpuMat& x, const GpuMat& y, GpuMat& magnitude, Stream& stream = Stream::Null());
 -
 -//! computes angle (angle(i)) of each (x(i), y(i)) vector
 -//! supports only floating-point source
 -CV_EXPORTS void phase(const GpuMat& x, const GpuMat& y, GpuMat& angle, bool angleInDegrees = false, Stream& stream = Stream::Null());
 -
 -//! converts Cartesian coordinates to polar
 -//! supports only floating-point source
 -CV_EXPORTS void cartToPolar(const GpuMat& x, const GpuMat& y, GpuMat& magnitude, GpuMat& angle, bool angleInDegrees = false, Stream& stream = Stream::Null());
 -
 -//! converts polar coordinates to Cartesian
 -//! supports only floating-point source
 -CV_EXPORTS void polarToCart(const GpuMat& magnitude, const GpuMat& angle, GpuMat& x, GpuMat& y, bool angleInDegrees = false, Stream& stream = Stream::Null());
 -
 -//! scales and shifts array elements so that either the specified norm (alpha) or the minimum (alpha) and maximum (beta) array values get the specified values
 -CV_EXPORTS void normalize(const GpuMat& src, GpuMat& dst, double alpha = 1, double beta = 0,
 -                          int norm_type = NORM_L2, int dtype = -1, const GpuMat& mask = GpuMat());
 -CV_EXPORTS void normalize(const GpuMat& src, GpuMat& dst, double a, double b,
 -                          int norm_type, int dtype, const GpuMat& mask, GpuMat& norm_buf, GpuMat& cvt_buf);
 -
 -
 -//////////////////////////// Per-element operations ////////////////////////////////////
 -
 -//! adds one matrix to another (c = a + b)
 -CV_EXPORTS void add(const GpuMat& a, const GpuMat& b, GpuMat& c, const GpuMat& mask = GpuMat(), int dtype = -1, Stream& stream = Stream::Null());
 -//! adds scalar to a matrix (c = a + s)
 -CV_EXPORTS void add(const GpuMat& a, const Scalar& sc, GpuMat& c, const GpuMat& mask = GpuMat(), int dtype = -1, Stream& stream = Stream::Null());
 -
 -//! subtracts one matrix from another (c = a - b)
 -CV_EXPORTS void subtract(const GpuMat& a, const GpuMat& b, GpuMat& c, const GpuMat& mask = GpuMat(), int dtype = -1, Stream& stream = Stream::Null());
 -//! subtracts scalar from a matrix (c = a - s)
 -CV_EXPORTS void subtract(const GpuMat& a, const Scalar& sc, GpuMat& c, const GpuMat& mask = GpuMat(), int dtype = -1, Stream& stream = Stream::Null());
 -
 -//! computes element-wise weighted product of the two arrays (c = scale * a * b)
 -CV_EXPORTS void multiply(const GpuMat& a, const GpuMat& b, GpuMat& c, double scale = 1, int dtype = -1, Stream& stream = Stream::Null());
 -//! weighted multiplies matrix to a scalar (c = scale * a * s)
 -CV_EXPORTS void multiply(const GpuMat& a, const Scalar& sc, GpuMat& c, double scale = 1, int dtype = -1, Stream& stream = Stream::Null());
 -
 -//! computes element-wise weighted quotient of the two arrays (c = a / b)
 -CV_EXPORTS void divide(const GpuMat& a, const GpuMat& b, GpuMat& c, double scale = 1, int dtype = -1, Stream& stream = Stream::Null());
 -//! computes element-wise weighted quotient of matrix and scalar (c = a / s)
 -CV_EXPORTS void divide(const GpuMat& a, const Scalar& sc, GpuMat& c, double scale = 1, int dtype = -1, Stream& stream = Stream::Null());
 -//! computes element-wise weighted reciprocal of an array (dst = scale/src2)
 -CV_EXPORTS void divide(double scale, const GpuMat& b, GpuMat& c, int dtype = -1, Stream& stream = Stream::Null());
 -
 -//! computes the weighted sum of two arrays (dst = alpha*src1 + beta*src2 + gamma)
 -CV_EXPORTS void addWeighted(const GpuMat& src1, double alpha, const GpuMat& src2, double beta, double gamma, GpuMat& dst,
 -                            int dtype = -1, Stream& stream = Stream::Null());
 -
 -//! adds scaled array to another one (dst = alpha*src1 + src2)
 -static inline void scaleAdd(const GpuMat& src1, double alpha, const GpuMat& src2, GpuMat& dst, Stream& stream = Stream::Null())
 -{
 -    addWeighted(src1, alpha, src2, 1.0, 0.0, dst, -1, stream);
 -}
 -
 -//! computes element-wise absolute difference of two arrays (c = abs(a - b))
 -CV_EXPORTS void absdiff(const GpuMat& a, const GpuMat& b, GpuMat& c, Stream& stream = Stream::Null());
 -//! computes element-wise absolute difference of array and scalar (c = abs(a - s))
 -CV_EXPORTS void absdiff(const GpuMat& a, const Scalar& s, GpuMat& c, Stream& stream = Stream::Null());
 -
 -//! computes absolute value of each matrix element
 -//! supports CV_16S and CV_32F depth
 -CV_EXPORTS void abs(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());
 -
 -//! computes square of each pixel in an image
 -//! supports CV_8U, CV_16U, CV_16S and CV_32F depth
 -CV_EXPORTS void sqr(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());
 -
 -//! computes square root of each pixel in an image
 -//! supports CV_8U, CV_16U, CV_16S and CV_32F depth
 -CV_EXPORTS void sqrt(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());
 -
 -//! computes exponent of each matrix element (b = e**a)
 -//! supports CV_8U, CV_16U, CV_16S and CV_32F depth
 -CV_EXPORTS void exp(const GpuMat& a, GpuMat& b, Stream& stream = Stream::Null());
 -
 -//! computes natural logarithm of absolute value of each matrix element: b = log(abs(a))
 -//! supports CV_8U, CV_16U, CV_16S and CV_32F depth
 -CV_EXPORTS void log(const GpuMat& a, GpuMat& b, Stream& stream = Stream::Null());
 -
 -//! computes power of each matrix element:
 -//    (dst(i,j) = pow(     src(i,j) , power), if src.type() is integer
 -//    (dst(i,j) = pow(fabs(src(i,j)), power), otherwise
 -//! supports all, except depth == CV_64F
 -CV_EXPORTS void pow(const GpuMat& src, double power, GpuMat& dst, Stream& stream = Stream::Null());
 -
 -//! compares elements of two arrays (c = a <cmpop> b)
 -CV_EXPORTS void compare(const GpuMat& a, const GpuMat& b, GpuMat& c, int cmpop, Stream& stream = Stream::Null());
 -CV_EXPORTS void compare(const GpuMat& a, Scalar sc, GpuMat& c, int cmpop, Stream& stream = Stream::Null());
 -
 -//! performs per-elements bit-wise inversion
 -CV_EXPORTS void bitwise_not(const GpuMat& src, GpuMat& dst, const GpuMat& mask=GpuMat(), Stream& stream = Stream::Null());
 -
 -//! calculates per-element bit-wise disjunction of two arrays
 -CV_EXPORTS void bitwise_or(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const GpuMat& mask=GpuMat(), Stream& stream = Stream::Null());
 -//! calculates per-element bit-wise disjunction of array and scalar
 -//! supports 1, 3 and 4 channels images with CV_8U, CV_16U or CV_32S depth
 -CV_EXPORTS void bitwise_or(const GpuMat& src1, const Scalar& sc, GpuMat& dst, Stream& stream = Stream::Null());
 -
 -//! calculates per-element bit-wise conjunction of two arrays
 -CV_EXPORTS void bitwise_and(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const GpuMat& mask=GpuMat(), Stream& stream = Stream::Null());
 -//! calculates per-element bit-wise conjunction of array and scalar
 -//! supports 1, 3 and 4 channels images with CV_8U, CV_16U or CV_32S depth
 -CV_EXPORTS void bitwise_and(const GpuMat& src1, const Scalar& sc, GpuMat& dst, Stream& stream = Stream::Null());
 -
 -//! calculates per-element bit-wise "exclusive or" operation
 -CV_EXPORTS void bitwise_xor(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, const GpuMat& mask=GpuMat(), Stream& stream = Stream::Null());
 -//! calculates per-element bit-wise "exclusive or" of array and scalar
 -//! supports 1, 3 and 4 channels images with CV_8U, CV_16U or CV_32S depth
 -CV_EXPORTS void bitwise_xor(const GpuMat& src1, const Scalar& sc, GpuMat& dst, Stream& stream = Stream::Null());
 -
 -//! pixel by pixel right shift of an image by a constant value
 -//! supports 1, 3 and 4 channels images with integers elements
 -CV_EXPORTS void rshift(const GpuMat& src, Scalar_<int> sc, GpuMat& dst, Stream& stream = Stream::Null());
 -
 -//! pixel by pixel left shift of an image by a constant value
 -//! supports 1, 3 and 4 channels images with CV_8U, CV_16U or CV_32S depth
 -CV_EXPORTS void lshift(const GpuMat& src, Scalar_<int> sc, GpuMat& dst, Stream& stream = Stream::Null());
 -
 -//! computes per-element minimum of two arrays (dst = min(src1, src2))
 -CV_EXPORTS void min(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, Stream& stream = Stream::Null());
 -
 -//! computes per-element minimum of array and scalar (dst = min(src1, src2))
 -CV_EXPORTS void min(const GpuMat& src1, double src2, GpuMat& dst, Stream& stream = Stream::Null());
 -
 -//! computes per-element maximum of two arrays (dst = max(src1, src2))
 -CV_EXPORTS void max(const GpuMat& src1, const GpuMat& src2, GpuMat& dst, Stream& stream = Stream::Null());
 -
 -//! computes per-element maximum of array and scalar (dst = max(src1, src2))
 -CV_EXPORTS void max(const GpuMat& src1, double src2, GpuMat& dst, Stream& stream = Stream::Null());
 -
 -enum { ALPHA_OVER, ALPHA_IN, ALPHA_OUT, ALPHA_ATOP, ALPHA_XOR, ALPHA_PLUS, ALPHA_OVER_PREMUL, ALPHA_IN_PREMUL, ALPHA_OUT_PREMUL,
 -       ALPHA_ATOP_PREMUL, ALPHA_XOR_PREMUL, ALPHA_PLUS_PREMUL, ALPHA_PREMUL};
 -
 -//! Composite two images using alpha opacity values contained in each image
 -//! Supports CV_8UC4, CV_16UC4, CV_32SC4 and CV_32FC4 types
 -CV_EXPORTS void alphaComp(const GpuMat& img1, const GpuMat& img2, GpuMat& dst, int alpha_op, Stream& stream = Stream::Null());
 -
 -
 -////////////////////////////// Image processing //////////////////////////////
 -
 -//! DST[x,y] = SRC[xmap[x,y],ymap[x,y]]
 -//! supports only CV_32FC1 map type
 -CV_EXPORTS void remap(const GpuMat& src, GpuMat& dst, const GpuMat& xmap, const GpuMat& ymap,
 -                      int interpolation, int borderMode = BORDER_CONSTANT, Scalar borderValue = Scalar(),
 -                      Stream& stream = Stream::Null());
 -
 -//! Does mean shift filtering on GPU.
 -CV_EXPORTS void meanShiftFiltering(const GpuMat& src, GpuMat& dst, int sp, int sr,
 -                                   TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1),
 -                                   Stream& stream = Stream::Null());
 -
 -//! Does mean shift procedure on GPU.
 -CV_EXPORTS void meanShiftProc(const GpuMat& src, GpuMat& dstr, GpuMat& dstsp, int sp, int sr,
 -                              TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1),
 -                              Stream& stream = Stream::Null());
 -
 -//! Does mean shift segmentation with elimination of small regions.
 -CV_EXPORTS void meanShiftSegmentation(const GpuMat& src, Mat& dst, int sp, int sr, int minsize,
 -                                      TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, 1));
 -
 -//! Does coloring of disparity image: [0..ndisp) -> [0..240, 1, 1] in HSV.
 -//! Supported types of input disparity: CV_8U, CV_16S.
 -//! Output disparity has CV_8UC4 type in BGRA format (alpha = 255).
 -CV_EXPORTS void drawColorDisp(const GpuMat& src_disp, GpuMat& dst_disp, int ndisp, Stream& stream = Stream::Null());
 -
 -//! Reprojects disparity image to 3D space.
 -//! Supports CV_8U and CV_16S types of input disparity.
 -//! The output is a 3- or 4-channel floating-point matrix.
 -//! Each element of this matrix will contain the 3D coordinates of the point (x,y,z,1), computed from the disparity map.
 -//! Q is the 4x4 perspective transformation matrix that can be obtained with cvStereoRectify.
 -CV_EXPORTS void reprojectImageTo3D(const GpuMat& disp, GpuMat& xyzw, const Mat& Q, int dst_cn = 4, Stream& stream = Stream::Null());
 -
 -//! converts image from one color space to another
 -CV_EXPORTS void cvtColor(const GpuMat& src, GpuMat& dst, int code, int dcn = 0, Stream& stream = Stream::Null());
 -
 -enum
 -{
 -    // Bayer Demosaicing (Malvar, He, and Cutler)
 -    COLOR_BayerBG2BGR_MHT = 256,
 -    COLOR_BayerGB2BGR_MHT = 257,
 -    COLOR_BayerRG2BGR_MHT = 258,
 -    COLOR_BayerGR2BGR_MHT = 259,
 -
 -    COLOR_BayerBG2RGB_MHT = COLOR_BayerRG2BGR_MHT,
 -    COLOR_BayerGB2RGB_MHT = COLOR_BayerGR2BGR_MHT,
 -    COLOR_BayerRG2RGB_MHT = COLOR_BayerBG2BGR_MHT,
 -    COLOR_BayerGR2RGB_MHT = COLOR_BayerGB2BGR_MHT,
 -
 -    COLOR_BayerBG2GRAY_MHT = 260,
 -    COLOR_BayerGB2GRAY_MHT = 261,
 -    COLOR_BayerRG2GRAY_MHT = 262,
 -    COLOR_BayerGR2GRAY_MHT = 263
 -};
 -CV_EXPORTS void demosaicing(const GpuMat& src, GpuMat& dst, int code, int dcn = -1, Stream& stream = Stream::Null());
 -
 -//! swap channels
 -//! dstOrder - Integer array describing how channel values are permutated. The n-th entry
 -//!            of the array contains the number of the channel that is stored in the n-th channel of
 -//!            the output image. E.g. Given an RGBA image, aDstOrder = [3,2,1,0] converts this to ABGR
 -//!            channel order.
 -CV_EXPORTS void swapChannels(GpuMat& image, const int dstOrder[4], Stream& stream = Stream::Null());
 -
 -//! Routines for correcting image color gamma
 -CV_EXPORTS void gammaCorrection(const GpuMat& src, GpuMat& dst, bool forward = true, Stream& stream = Stream::Null());
 -
 -//! applies fixed threshold to the image
 -CV_EXPORTS double threshold(const GpuMat& src, GpuMat& dst, double thresh, double maxval, int type, Stream& stream = Stream::Null());
 -
 -//! resizes the image
 -//! Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC, INTER_AREA
 -CV_EXPORTS void resize(const GpuMat& src, GpuMat& dst, Size dsize, double fx=0, double fy=0, int interpolation = INTER_LINEAR, Stream& stream = Stream::Null());
 -
 -//! warps the image using affine transformation
 -//! Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC
 -CV_EXPORTS void warpAffine(const GpuMat& src, GpuMat& dst, const Mat& M, Size dsize, int flags = INTER_LINEAR,
 -    int borderMode = BORDER_CONSTANT, Scalar borderValue = Scalar(), Stream& stream = Stream::Null());
 -
 -CV_EXPORTS void buildWarpAffineMaps(const Mat& M, bool inverse, Size dsize, GpuMat& xmap, GpuMat& ymap, Stream& stream = Stream::Null());
 -
 -//! warps the image using perspective transformation
 -//! Supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC
 -CV_EXPORTS void warpPerspective(const GpuMat& src, GpuMat& dst, const Mat& M, Size dsize, int flags = INTER_LINEAR,
 -    int borderMode = BORDER_CONSTANT, Scalar borderValue = Scalar(), Stream& stream = Stream::Null());
 -
 -CV_EXPORTS void buildWarpPerspectiveMaps(const Mat& M, bool inverse, Size dsize, GpuMat& xmap, GpuMat& ymap, Stream& stream = Stream::Null());
 -
 -//! 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,
 -                                   GpuMat& map_x, GpuMat& map_y, Stream& stream = Stream::Null());
 -
 -//! builds cylindrical warping maps
 -CV_EXPORTS void buildWarpCylindricalMaps(Size src_size, Rect dst_roi, const Mat &K, const Mat& R, float scale,
 -                                         GpuMat& map_x, GpuMat& map_y, Stream& stream = Stream::Null());
 -
 -//! builds spherical warping maps
 -CV_EXPORTS void buildWarpSphericalMaps(Size src_size, Rect dst_roi, const Mat &K, const Mat& R, float scale,
 -                                       GpuMat& map_x, GpuMat& map_y, Stream& stream = Stream::Null());
 -
 -//! rotates an image around the origin (0,0) and then shifts it
 -//! supports INTER_NEAREST, INTER_LINEAR, INTER_CUBIC
 -//! supports 1, 3 or 4 channels images with CV_8U, CV_16U or CV_32F depth
 -CV_EXPORTS void rotate(const GpuMat& src, GpuMat& dst, Size dsize, double angle, double xShift = 0, double yShift = 0,
 -                       int interpolation = INTER_LINEAR, Stream& stream = Stream::Null());
 -
 -//! copies 2D array to a larger destination array and pads borders with user-specifiable constant
 -CV_EXPORTS void copyMakeBorder(const GpuMat& src, GpuMat& dst, int top, int bottom, int left, int right, int borderType,
 -                               const Scalar& value = Scalar(), Stream& stream = Stream::Null());
 -
 -//! computes the integral image
 -//! sum will have CV_32S type, but will contain unsigned int values
 -//! supports only CV_8UC1 source type
 -CV_EXPORTS void integral(const GpuMat& src, GpuMat& sum, Stream& stream = Stream::Null());
 -//! buffered version
 -CV_EXPORTS void integralBuffered(const GpuMat& src, GpuMat& sum, GpuMat& buffer, Stream& stream = Stream::Null());
 -
 -//! computes squared integral image
 -//! result matrix will have 64F type, but will contain 64U values
 -//! supports source images of 8UC1 type only
 -CV_EXPORTS void sqrIntegral(const GpuMat& src, GpuMat& sqsum, Stream& stream = Stream::Null());
 -
 -//! computes vertical sum, supports only CV_32FC1 images
 -CV_EXPORTS void columnSum(const GpuMat& src, GpuMat& sum);
 -
 -//! computes the standard deviation of integral images
 -//! supports only CV_32SC1 source type and CV_32FC1 sqr type
 -//! output will have CV_32FC1 type
 -CV_EXPORTS void rectStdDev(const GpuMat& src, const GpuMat& sqr, GpuMat& dst, const Rect& rect, Stream& stream = Stream::Null());
 -
 -//! computes Harris cornerness criteria at each image pixel
 -CV_EXPORTS void cornerHarris(const GpuMat& src, GpuMat& dst, int blockSize, int ksize, double k, int borderType = BORDER_REFLECT101);
 -CV_EXPORTS void cornerHarris(const GpuMat& src, GpuMat& dst, GpuMat& Dx, GpuMat& Dy, int blockSize, int ksize, double k, int borderType = BORDER_REFLECT101);
 -CV_EXPORTS void cornerHarris(const GpuMat& src, GpuMat& dst, GpuMat& Dx, GpuMat& Dy, GpuMat& buf, int blockSize, int ksize, double k,
 -                             int borderType = BORDER_REFLECT101, Stream& stream = Stream::Null());
 -
 -//! computes minimum eigen value of 2x2 derivative covariation matrix at each pixel - the cornerness criteria
 -CV_EXPORTS void cornerMinEigenVal(const GpuMat& src, GpuMat& dst, int blockSize, int ksize, int borderType=BORDER_REFLECT101);
 -CV_EXPORTS void cornerMinEigenVal(const GpuMat& src, GpuMat& dst, GpuMat& Dx, GpuMat& Dy, int blockSize, int ksize, int borderType=BORDER_REFLECT101);
 -CV_EXPORTS void cornerMinEigenVal(const GpuMat& src, GpuMat& dst, GpuMat& Dx, GpuMat& Dy, GpuMat& buf, int blockSize, int ksize,
 -    int borderType=BORDER_REFLECT101, Stream& stream = Stream::Null());
 -
 -//! performs per-element multiplication of two full (not packed) Fourier spectrums
 -//! supports 32FC2 matrixes only (interleaved format)
 -CV_EXPORTS void mulSpectrums(const GpuMat& a, const GpuMat& b, GpuMat& c, int flags, bool conjB=false, Stream& stream = Stream::Null());
 -
 -//! performs per-element multiplication of two full (not packed) Fourier spectrums
 -//! supports 32FC2 matrixes only (interleaved format)
 -CV_EXPORTS void mulAndScaleSpectrums(const GpuMat& a, const GpuMat& b, GpuMat& c, int flags, float scale, bool conjB=false, Stream& stream = Stream::Null());
 -
 -//! Performs a forward or inverse discrete Fourier transform (1D or 2D) of floating point matrix.
 -//! Param dft_size is the size of DFT transform.
 -//!
 -//! If the source matrix is not continous, then additional copy will be done,
 -//! so to avoid copying ensure the source matrix is continous one. If you want to use
 -//! preallocated output ensure it is continuous too, otherwise it will be reallocated.
 -//!
 -//! Being implemented via CUFFT real-to-complex transform result contains only non-redundant values
 -//! in CUFFT's format. Result as full complex matrix for such kind of transform cannot be retrieved.
 -//!
 -//! For complex-to-real transform it is assumed that the source matrix is packed in CUFFT's format.
 -CV_EXPORTS void dft(const GpuMat& src, GpuMat& dst, Size dft_size, int flags=0, Stream& stream = Stream::Null());
 -
 -struct CV_EXPORTS ConvolveBuf
 -{
 -    Size result_size;
 -    Size block_size;
 -    Size user_block_size;
 -    Size dft_size;
 -    int spect_len;
 -
 -    GpuMat image_spect, templ_spect, result_spect;
 -    GpuMat 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 (or cross-correlation) of two images using discrete Fourier transform
 -//! supports source images of 32FC1 type only
 -//! result matrix will have 32FC1 type
 -CV_EXPORTS void convolve(const GpuMat& image, const GpuMat& templ, GpuMat& result, bool ccorr = false);
 -CV_EXPORTS void convolve(const GpuMat& image, const GpuMat& templ, GpuMat& result, bool ccorr, ConvolveBuf& buf, Stream& stream = Stream::Null());
 -
 -struct CV_EXPORTS MatchTemplateBuf
 -{
 -    Size user_block_size;
 -    GpuMat imagef, templf;
 -    std::vector<GpuMat> images;
 -    std::vector<GpuMat> image_sums;
 -    std::vector<GpuMat> image_sqsums;
 -};
 -
 -//! computes the proximity map for the raster template and the image where the template is searched for
 -CV_EXPORTS void matchTemplate(const GpuMat& image, const GpuMat& templ, GpuMat& result, int method, Stream &stream = Stream::Null());
 -
 -//! computes the proximity map for the raster template and the image where the template is searched for
 -CV_EXPORTS void matchTemplate(const GpuMat& image, const GpuMat& templ, GpuMat& result, int method, MatchTemplateBuf &buf, Stream& stream = Stream::Null());
 -
 -//! smoothes the source image and downsamples it
 -CV_EXPORTS void pyrDown(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());
 -
 -//! upsamples the source image and then smoothes it
 -CV_EXPORTS void pyrUp(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());
 -
 -//! performs linear blending of two images
 -//! to avoid accuracy errors sum of weigths shouldn't be very close to zero
 -CV_EXPORTS void blendLinear(const GpuMat& img1, const GpuMat& img2, const GpuMat& weights1, const GpuMat& weights2,
 -                            GpuMat& result, Stream& stream = Stream::Null());
 -
 -//! Performa bilateral filtering of passsed image
 -CV_EXPORTS void bilateralFilter(const GpuMat& src, GpuMat& dst, int kernel_size, float sigma_color, float sigma_spatial,
 -                                int borderMode = BORDER_DEFAULT, Stream& stream = Stream::Null());
 -
 -//! Brute force non-local means algorith (slow but universal)
 -CV_EXPORTS void nonLocalMeans(const GpuMat& src, GpuMat& dst, float h, int search_window = 21, int block_size = 7, int borderMode = BORDER_DEFAULT, Stream& s = Stream::Null());
 -
 -//! Fast (but approximate)version of non-local means algorith similar to CPU function (running sums technique)
 -class CV_EXPORTS FastNonLocalMeansDenoising
 -{
 -public:
 -    //! Simple method, recommended for grayscale images (though it supports multichannel images)
 -    void simpleMethod(const GpuMat& src, GpuMat& dst, float h, int search_window = 21, int block_size = 7, Stream& s = Stream::Null());
 -
 -    //! Processes luminance and color components separatelly
 -    void labMethod(const GpuMat& src, GpuMat& dst, float h_luminance, float h_color, int search_window = 21, int block_size = 7, Stream& s = Stream::Null());
 -
 -private:
 -
 -    GpuMat buffer, extended_src_buffer;
 -    GpuMat lab, l, ab;
 -};
 -
 -struct CV_EXPORTS CannyBuf
 -{
 -    void create(const Size& image_size, int apperture_size = 3);
 -    void release();
 -
 -    GpuMat dx, dy;
 -    GpuMat mag;
 -    GpuMat map;
 -    GpuMat st1, st2;
 -    GpuMat unused;
 -    Ptr<FilterEngine_GPU> filterDX, filterDY;
 -
 -    CannyBuf() {}
 -    explicit CannyBuf(const Size& image_size, int apperture_size = 3) {create(image_size, apperture_size);}
 -    CannyBuf(const GpuMat& dx_, const GpuMat& dy_);
 -};
 -
 -CV_EXPORTS void Canny(const GpuMat& image, GpuMat& edges, double low_thresh, double high_thresh, int apperture_size = 3, bool L2gradient = false);
 -CV_EXPORTS void Canny(const GpuMat& image, CannyBuf& buf, GpuMat& edges, double low_thresh, double high_thresh, int apperture_size = 3, bool L2gradient = false);
 -CV_EXPORTS void Canny(const GpuMat& dx, const GpuMat& dy, GpuMat& edges, double low_thresh, double high_thresh, bool L2gradient = false);
 -CV_EXPORTS void Canny(const GpuMat& dx, const GpuMat& dy, CannyBuf& buf, GpuMat& edges, double low_thresh, double high_thresh, bool L2gradient = false);
 -
 -class CV_EXPORTS ImagePyramid
 -{
 -public:
 -    inline ImagePyramid() : nLayers_(0) {}
 -    inline ImagePyramid(const GpuMat& img, int nLayers, Stream& stream = Stream::Null())
 -    {
 -        build(img, nLayers, stream);
 -    }
 -
 -    void build(const GpuMat& img, int nLayers, Stream& stream = Stream::Null());
 -
 -    void getLayer(GpuMat& outImg, Size outRoi, Stream& stream = Stream::Null()) const;
 -
 -    inline void release()
 -    {
 -        layer0_.release();
 -        pyramid_.clear();
 -        nLayers_ = 0;
 -    }
 -
 -private:
 -    GpuMat layer0_;
 -    std::vector<GpuMat> pyramid_;
 -    int nLayers_;
 -};
 -
 -//! HoughLines
 -
 -struct HoughLinesBuf
 -{
 -    GpuMat accum;
 -    GpuMat list;
 -};
 -
 -CV_EXPORTS void HoughLines(const GpuMat& src, GpuMat& lines, float rho, float theta, int threshold, bool doSort = false, int maxLines = 4096);
 -CV_EXPORTS void HoughLines(const GpuMat& src, GpuMat& lines, HoughLinesBuf& buf, float rho, float theta, int threshold, bool doSort = false, int maxLines = 4096);
 -CV_EXPORTS void HoughLinesDownload(const GpuMat& d_lines, OutputArray h_lines, OutputArray h_votes = noArray());
 -
 -//! HoughLinesP
 -
 -//! finds line segments in the black-n-white image using probabalistic Hough transform
 -CV_EXPORTS void HoughLinesP(const GpuMat& image, GpuMat& lines, HoughLinesBuf& buf, float rho, float theta, int minLineLength, int maxLineGap, int maxLines = 4096);
 -
 -//! HoughCircles
 -
 -struct HoughCirclesBuf
 -{
 -    GpuMat edges;
 -    GpuMat accum;
 -    GpuMat list;
 -    CannyBuf cannyBuf;
 -};
 -
 -CV_EXPORTS void HoughCircles(const GpuMat& src, GpuMat& circles, int method, float dp, float minDist, int cannyThreshold, int votesThreshold, int minRadius, int maxRadius, int maxCircles = 4096);
 -CV_EXPORTS void HoughCircles(const GpuMat& src, GpuMat& 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 GpuMat& d_circles, OutputArray h_circles);
 -
 -//! finds arbitrary template in the grayscale image using Generalized Hough Transform
 -//! Ballard, D.H. (1981). Generalizing the Hough transform to detect arbitrary shapes. Pattern Recognition 13 (2): 111-122.
 -//! Guil, N., González-Linares, J.M. and Zapata, E.L. (1999). Bidimensional shape detection using an invariant approach. Pattern Recognition 32 (6): 1025-1038.
 -class CV_EXPORTS GeneralizedHough_GPU : public Algorithm
 -{
 -public:
 -    static Ptr<GeneralizedHough_GPU> create(int method);
 -
 -    virtual ~GeneralizedHough_GPU();
 -
 -    //! set template to search
 -    void setTemplate(const GpuMat& templ, int cannyThreshold = 100, Point templCenter = Point(-1, -1));
 -    void setTemplate(const GpuMat& edges, const GpuMat& dx, const GpuMat& dy, Point templCenter = Point(-1, -1));
 -
 -    //! find template on image
 -    void detect(const GpuMat& image, GpuMat& positions, int cannyThreshold = 100);
 -    void detect(const GpuMat& edges, const GpuMat& dx, const GpuMat& dy, GpuMat& positions);
 -
 -    void download(const GpuMat& d_positions, OutputArray h_positions, OutputArray h_votes = noArray());
 -
 -    void release();
 -
 -protected:
 -    virtual void setTemplateImpl(const GpuMat& edges, const GpuMat& dx, const GpuMat& dy, Point templCenter) = 0;
 -    virtual void detectImpl(const GpuMat& edges, const GpuMat& dx, const GpuMat& dy, GpuMat& positions) = 0;
 -    virtual void releaseImpl() = 0;
 -
 -private:
 -    GpuMat edges_;
 -    CannyBuf cannyBuf_;
 -};
 -
 -////////////////////////////// Matrix reductions //////////////////////////////
 -
 -//! computes mean value and standard deviation of all or selected array elements
 -//! supports only CV_8UC1 type
 -CV_EXPORTS void meanStdDev(const GpuMat& mtx, Scalar& mean, Scalar& stddev);
 -//! buffered version
 -CV_EXPORTS void meanStdDev(const GpuMat& mtx, Scalar& mean, Scalar& stddev, GpuMat& buf);
 -
 -//! computes norm of array
 -//! supports NORM_INF, NORM_L1, NORM_L2
 -//! supports all matrices except 64F
 -CV_EXPORTS double norm(const GpuMat& src1, int normType=NORM_L2);
 -CV_EXPORTS double norm(const GpuMat& src1, int normType, GpuMat& buf);
 -CV_EXPORTS double norm(const GpuMat& src1, int normType, const GpuMat& mask, GpuMat& buf);
 -
 -//! computes norm of the difference between two arrays
 -//! supports NORM_INF, NORM_L1, NORM_L2
 -//! supports only CV_8UC1 type
 -CV_EXPORTS double norm(const GpuMat& src1, const GpuMat& src2, int normType=NORM_L2);
 -
 -//! computes sum of array elements
 -//! supports only single channel images
 -CV_EXPORTS Scalar sum(const GpuMat& src);
 -CV_EXPORTS Scalar sum(const GpuMat& src, GpuMat& buf);
 -CV_EXPORTS Scalar sum(const GpuMat& src, const GpuMat& mask, GpuMat& buf);
 -
 -//! computes sum of array elements absolute values
 -//! supports only single channel images
 -CV_EXPORTS Scalar absSum(const GpuMat& src);
 -CV_EXPORTS Scalar absSum(const GpuMat& src, GpuMat& buf);
 -CV_EXPORTS Scalar absSum(const GpuMat& src, const GpuMat& mask, GpuMat& buf);
 -
 -//! computes squared sum of array elements
 -//! supports only single channel images
 -CV_EXPORTS Scalar sqrSum(const GpuMat& src);
 -CV_EXPORTS Scalar sqrSum(const GpuMat& src, GpuMat& buf);
 -CV_EXPORTS Scalar sqrSum(const GpuMat& src, const GpuMat& mask, GpuMat& buf);
 -
 -//! finds global minimum and maximum array elements and returns their values
 -CV_EXPORTS void minMax(const GpuMat& src, double* minVal, double* maxVal=0, const GpuMat& mask=GpuMat());
 -CV_EXPORTS void minMax(const GpuMat& src, double* minVal, double* maxVal, const GpuMat& mask, GpuMat& buf);
 -
 -//! finds global minimum and maximum array elements and returns their values with locations
 -CV_EXPORTS void minMaxLoc(const GpuMat& src, double* minVal, double* maxVal=0, Point* minLoc=0, Point* maxLoc=0,
 -                          const GpuMat& mask=GpuMat());
 -CV_EXPORTS void minMaxLoc(const GpuMat& src, double* minVal, double* maxVal, Point* minLoc, Point* maxLoc,
 -                          const GpuMat& mask, GpuMat& valbuf, GpuMat& locbuf);
 -
 -//! counts non-zero array elements
 -CV_EXPORTS int countNonZero(const GpuMat& src);
 -CV_EXPORTS int countNonZero(const GpuMat& src, GpuMat& buf);
 -
 -//! reduces a matrix to a vector
 -CV_EXPORTS void reduce(const GpuMat& mtx, GpuMat& vec, int dim, int reduceOp, int dtype = -1, Stream& stream = Stream::Null());
 -
 -
 -///////////////////////////// Calibration 3D //////////////////////////////////
 -
 -CV_EXPORTS void transformPoints(const GpuMat& src, const Mat& rvec, const Mat& tvec,
 -                                GpuMat& dst, Stream& stream = Stream::Null());
 -
 -CV_EXPORTS void projectPoints(const GpuMat& src, const Mat& rvec, const Mat& tvec,
 -                              const Mat& camera_mat, const Mat& dist_coef, GpuMat& dst,
 -                              Stream& stream = Stream::Null());
 -
 -CV_EXPORTS void solvePnPRansac(const Mat& object, const Mat& image, const Mat& camera_mat,
 -                               const Mat& dist_coef, Mat& rvec, Mat& tvec, bool use_extrinsic_guess=false,
 -                               int num_iters=100, float max_dist=8.0, int min_inlier_count=100,
 -                               std::vector<int>* inliers=NULL);
 -
 -//////////////////////////////// Image Labeling ////////////////////////////////
 -
 -//!performs labeling via graph cuts of a 2D regular 4-connected graph.
 -CV_EXPORTS void graphcut(GpuMat& terminals, GpuMat& leftTransp, GpuMat& rightTransp, GpuMat& top, GpuMat& bottom, GpuMat& labels,
 -                         GpuMat& buf, Stream& stream = Stream::Null());
 -
 -//!performs labeling via graph cuts of a 2D regular 8-connected graph.
 -CV_EXPORTS void graphcut(GpuMat& terminals, GpuMat& leftTransp, GpuMat& rightTransp, GpuMat& top, GpuMat& topLeft, GpuMat& topRight,
 -                         GpuMat& bottom, GpuMat& bottomLeft, GpuMat& bottomRight,
 -                         GpuMat& labels,
 -                         GpuMat& buf, Stream& stream = Stream::Null());
 -
 -//! compute mask for Generalized Flood fill componetns labeling.
 -CV_EXPORTS void connectivityMask(const GpuMat& image, GpuMat& mask, const cv::Scalar& lo, const cv::Scalar& hi, Stream& stream = Stream::Null());
 -
 -//! performs connected componnents labeling.
 -CV_EXPORTS void labelComponents(const GpuMat& mask, GpuMat& components, int flags = 0, Stream& stream = Stream::Null());
 -
 -////////////////////////////////// Histograms //////////////////////////////////
 -
 -//! Compute levels with even distribution. levels will have 1 row and nLevels cols and CV_32SC1 type.
 -CV_EXPORTS void evenLevels(GpuMat& levels, int nLevels, int lowerLevel, int upperLevel);
 -//! Calculates histogram with evenly distributed bins for signle channel source.
 -//! Supports CV_8UC1, CV_16UC1 and CV_16SC1 source types.
 -//! Output hist will have one row and histSize cols and CV_32SC1 type.
 -CV_EXPORTS void histEven(const GpuMat& src, GpuMat& hist, int histSize, int lowerLevel, int upperLevel, Stream& stream = Stream::Null());
 -CV_EXPORTS void histEven(const GpuMat& src, GpuMat& hist, GpuMat& buf, int histSize, int lowerLevel, int upperLevel, Stream& stream = Stream::Null());
 -//! Calculates histogram with evenly distributed bins for four-channel source.
 -//! All channels of source are processed separately.
 -//! Supports CV_8UC4, CV_16UC4 and CV_16SC4 source types.
 -//! Output hist[i] will have one row and histSize[i] cols and CV_32SC1 type.
 -CV_EXPORTS void histEven(const GpuMat& src, GpuMat hist[4], int histSize[4], int lowerLevel[4], int upperLevel[4], Stream& stream = Stream::Null());
 -CV_EXPORTS void histEven(const GpuMat& src, GpuMat hist[4], GpuMat& buf, int histSize[4], int lowerLevel[4], int upperLevel[4], Stream& stream = Stream::Null());
 -//! Calculates histogram with bins determined by levels array.
 -//! levels must have one row and CV_32SC1 type if source has integer type or CV_32FC1 otherwise.
 -//! Supports CV_8UC1, CV_16UC1, CV_16SC1 and CV_32FC1 source types.
 -//! Output hist will have one row and (levels.cols-1) cols and CV_32SC1 type.
 -CV_EXPORTS void histRange(const GpuMat& src, GpuMat& hist, const GpuMat& levels, Stream& stream = Stream::Null());
 -CV_EXPORTS void histRange(const GpuMat& src, GpuMat& hist, const GpuMat& levels, GpuMat& buf, Stream& stream = Stream::Null());
 -//! Calculates histogram with bins determined by levels array.
 -//! All levels must have one row and CV_32SC1 type if source has integer type or CV_32FC1 otherwise.
 -//! All channels of source are processed separately.
 -//! Supports CV_8UC4, CV_16UC4, CV_16SC4 and CV_32FC4 source types.
 -//! Output hist[i] will have one row and (levels[i].cols-1) cols and CV_32SC1 type.
 -CV_EXPORTS void histRange(const GpuMat& src, GpuMat hist[4], const GpuMat levels[4], Stream& stream = Stream::Null());
 -CV_EXPORTS void histRange(const GpuMat& src, GpuMat hist[4], const GpuMat levels[4], GpuMat& buf, Stream& stream = Stream::Null());
 -
 -//! Calculates histogram for 8u one channel image
 -//! Output hist will have one row, 256 cols and CV32SC1 type.
 -CV_EXPORTS void calcHist(const GpuMat& src, GpuMat& hist, Stream& stream = Stream::Null());
 -CV_EXPORTS void calcHist(const GpuMat& src, GpuMat& hist, GpuMat& buf, Stream& stream = Stream::Null());
 -
 -//! normalizes the grayscale image brightness and contrast by normalizing its histogram
 -CV_EXPORTS void equalizeHist(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::Null());
 -CV_EXPORTS void equalizeHist(const GpuMat& src, GpuMat& dst, GpuMat& hist, Stream& stream = Stream::Null());
 -CV_EXPORTS void equalizeHist(const GpuMat& src, GpuMat& dst, GpuMat& hist, GpuMat& buf, Stream& stream = Stream::Null());
 -
 -class CV_EXPORTS CLAHE : public cv::CLAHE
 -{
 -public:
 -    using cv::CLAHE::apply;
 -    virtual void apply(InputArray src, OutputArray dst, Stream& stream) = 0;
 -};
 -CV_EXPORTS Ptr<cv::gpu::CLAHE> createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8));
 -
 -//////////////////////////////// StereoBM_GPU ////////////////////////////////
 -
 -class CV_EXPORTS StereoBM_GPU
 -{
 -public:
 -    enum { BASIC_PRESET = 0, PREFILTER_XSOBEL = 1 };
 -
 -    enum { DEFAULT_NDISP = 64, DEFAULT_WINSZ = 19 };
 -
 -    //! the default constructor
 -    StereoBM_GPU();
 -    //! the full constructor taking the camera-specific preset, number of disparities and the SAD window size. ndisparities must be multiple of 8.
 -    StereoBM_GPU(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 GpuMat& left, const GpuMat& right, GpuMat& disparity, Stream& stream = Stream::Null());
 -
 -    //! Some heuristics that tries to estmate
 -    // if current GPU will be faster than 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:
 -    GpuMat minSSD, leBuf, riBuf;
 -};
 -
 -////////////////////////// StereoBeliefPropagation ///////////////////////////
 -// "Efficient Belief Propagation for Early Vision"
 -// P.Felzenszwalb
 -
 -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);
 -
 -    //! the default constructor
 -    explicit StereoBeliefPropagation(int ndisp  = DEFAULT_NDISP,
 -                                     int iters  = DEFAULT_ITERS,
 -                                     int levels = DEFAULT_LEVELS,
 -                                     int msg_type = CV_32F);
 -
 -    //! the full constructor taking the number of disparities, number of BP iterations on each level,
 -    //! number of levels, truncation of data cost, data weight,
 -    //! truncation of discontinuity cost and discontinuity single jump
 -    //! DataTerm = data_weight * min(fabs(I2-I1), max_data_term)
 -    //! DiscTerm = min(disc_single_jump * fabs(f1-f2), max_disc_term)
 -    //! please see paper for more details
 -    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);
 -
 -    //! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair,
 -    //! if disparity is empty output type will be CV_16S else output type will be disparity.type().
 -    void operator()(const GpuMat& left, const GpuMat& right, GpuMat& disparity, Stream& stream = Stream::Null());
 -
 -
 -    //! version for user specified data term
 -    void operator()(const GpuMat& data, GpuMat& disparity, Stream& stream = Stream::Null());
 -
 -    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:
 -    GpuMat u, d, l, r, u2, d2, l2, r2;
 -    std::vector<GpuMat> datas;
 -    GpuMat out;
 -};
 -
 -/////////////////////////// StereoConstantSpaceBP ///////////////////////////
 -// "A Constant-Space Belief Propagation Algorithm for Stereo Matching"
 -// Qingxiong Yang, Liang Wang, Narendra Ahuja
 -// http://vision.ai.uiuc.edu/~qyang6/
 -
 -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);
 -
 -    //! the default constructor
 -    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);
 -
 -    //! the full constructor taking the number of disparities, number of BP iterations on each level,
 -    //! number of levels, number of active disparity on the first level, truncation of data cost, data weight,
 -    //! truncation of discontinuity cost, discontinuity single jump and minimum disparity threshold
 -    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);
 -
 -    //! the stereo correspondence operator. Finds the disparity for the specified rectified stereo pair,
 -    //! if disparity is empty output type will be CV_16S else output type will be disparity.type().
 -    void operator()(const GpuMat& left, const GpuMat& right, GpuMat& disparity, Stream& stream = Stream::Null());
 -
 -    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:
 -    GpuMat messages_buffers;
 -
 -    GpuMat temp;
 -    GpuMat out;
 -};
 -
 -/////////////////////////// DisparityBilateralFilter ///////////////////////////
 -// Disparity map refinement using joint bilateral filtering given a single color image.
 -// Qingxiong Yang, Liang Wang, Narendra Ahuja
 -// http://vision.ai.uiuc.edu/~qyang6/
 -
 -class CV_EXPORTS DisparityBilateralFilter
 -{
 -public:
 -    enum { DEFAULT_NDISP  = 64 };
 -    enum { DEFAULT_RADIUS = 3 };
 -    enum { DEFAULT_ITERS  = 1 };
 -
 -    //! the default constructor
 -    explicit DisparityBilateralFilter(int ndisp = DEFAULT_NDISP, int radius = DEFAULT_RADIUS, int iters = DEFAULT_ITERS);
 -
 -    //! the full constructor taking the number of disparities, filter radius,
 -    //! number of iterations, truncation of data continuity, truncation of disparity continuity
 -    //! and filter range sigma
 -    DisparityBilateralFilter(int ndisp, int radius, int iters, float edge_threshold, float max_disc_threshold, float sigma_range);
 -
 -    //! the disparity map refinement operator. Refine disparity map using joint bilateral filtering given a single color image.
 -    //! disparity must have CV_8U or CV_16S type, image must have CV_8UC1 or CV_8UC3 type.
 -    void operator()(const GpuMat& disparity, const GpuMat& image, GpuMat& dst, Stream& stream = Stream::Null());
 -
 -private:
 -    int ndisp;
 -    int radius;
 -    int iters;
 -
 -    float edge_threshold;
 -    float max_disc_threshold;
 -    float sigma_range;
 -
 -    GpuMat table_color;
 -    GpuMat table_space;
 -};
 -
 -
 -//////////////// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector //////////////
 -struct CV_EXPORTS HOGConfidence
 -{
 -   double scale;
 -   vector<Point> locations;
 -   vector<double> confidences;
 -   vector<double> part_scores[4];
 -};
 -
 -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 vector<float>& detector);
 -
 -    static vector<float> getDefaultPeopleDetector();
 -    static vector<float> getPeopleDetector48x96();
 -    static vector<float> getPeopleDetector64x128();
 -
 -    void detect(const GpuMat& img, vector<Point>& found_locations,
 -                double hit_threshold=0, Size win_stride=Size(),
 -                Size padding=Size());
 -
 -    void detectMultiScale(const GpuMat& img, vector<Rect>& found_locations,
 -                          double hit_threshold=0, Size win_stride=Size(),
 -                          Size padding=Size(), double scale0=1.05,
 -                          int group_threshold=2);
 -
 -    void computeConfidence(const GpuMat& img, vector<Point>& hits, double hit_threshold,
 -                                                Size win_stride, Size padding, vector<Point>& locations, vector<double>& confidences);
 -
 -    void computeConfidenceMultiScale(const GpuMat& img, vector<Rect>& found_locations,
 -                                                                    double hit_threshold, Size win_stride, Size padding,
 -                                                                    vector<HOGConfidence> &conf_out, int group_threshold);
 -
 -    void getDescriptors(const GpuMat& img, Size win_stride,
 -                        GpuMat& 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:
 -    void computeBlockHistograms(const GpuMat& img);
 -    void computeGradient(const GpuMat& img, GpuMat& grad, GpuMat& 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;
 -    GpuMat detector;
 -
 -    // Results of the last classification step
 -    GpuMat labels, labels_buf;
 -    Mat labels_host;
 -
 -    // Results of the last histogram evaluation step
 -    GpuMat block_hists, block_hists_buf;
 -
 -    // Gradients conputation results
 -    GpuMat grad, qangle, grad_buf, qangle_buf;
 -
 -    // returns subbuffer with required size, reallocates buffer if nessesary.
 -    static GpuMat getBuffer(const Size& sz, int type, GpuMat& buf);
 -    static GpuMat getBuffer(int rows, int cols, int type, GpuMat& buf);
 -
 -    std::vector<GpuMat> image_scales;
 -};
 -
 -
 -////////////////////////////////// BruteForceMatcher //////////////////////////////////
 -
 -class CV_EXPORTS BruteForceMatcher_GPU_base
 -{
 -public:
 -    enum DistType {L1Dist = 0, L2Dist, HammingDist};
 -
 -    explicit BruteForceMatcher_GPU_base(DistType distType = L2Dist);
 -
 -    // Add descriptors to train descriptor collection
 -    void add(const std::vector<GpuMat>& descCollection);
 -
 -    // Get train descriptors collection
 -    const std::vector<GpuMat>& 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 GpuMat& query, const GpuMat& train,
 -        GpuMat& trainIdx, GpuMat& distance,
 -        const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null());
 -
 -    // Download trainIdx and distance and convert it to CPU vector with DMatch
 -    static void matchDownload(const GpuMat& trainIdx, const GpuMat& 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 GpuMat& query, const GpuMat& train, std::vector<DMatch>& matches, const GpuMat& mask = GpuMat());
 -
 -    // Make gpu collection of trains and masks in suitable format for matchCollection function
 -    void makeGpuCollection(GpuMat& trainCollection, GpuMat& maskCollection, const std::vector<GpuMat>& masks = std::vector<GpuMat>());
 -
 -    // Find one best match from train collection for each query descriptor
 -    void matchCollection(const GpuMat& query, const GpuMat& trainCollection,
 -        GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance,
 -        const GpuMat& masks = GpuMat(), Stream& stream = Stream::Null());
 -
 -    // Download trainIdx, imgIdx and distance and convert it to vector with DMatch
 -    static void matchDownload(const GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& 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 GpuMat& query, std::vector<DMatch>& matches, const std::vector<GpuMat>& masks = std::vector<GpuMat>());
 -
 -    // Find k best matches for each query descriptor (in increasing order of distances)
 -    void knnMatchSingle(const GpuMat& query, const GpuMat& train,
 -        GpuMat& trainIdx, GpuMat& distance, GpuMat& allDist, int k,
 -        const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null());
 -
 -    // 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 GpuMat& trainIdx, const GpuMat& 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 GpuMat& query, const GpuMat& train,
 -        std::vector< std::vector<DMatch> >& matches, int k, const GpuMat& mask = GpuMat(),
 -        bool compactResult = false);
 -
 -    // Find k best matches from train collection for each query descriptor (in increasing order of distances)
 -    void knnMatch2Collection(const GpuMat& query, const GpuMat& trainCollection,
 -        GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance,
 -        const GpuMat& maskCollection = GpuMat(), Stream& stream = Stream::Null());
 -
 -    // 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 GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& 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 GpuMat& query, std::vector< std::vector<DMatch> >& matches, int k,
 -        const std::vector<GpuMat>& masks = std::vector<GpuMat>(), 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 GpuMat& query, const GpuMat& train,
 -        GpuMat& trainIdx, GpuMat& distance, GpuMat& nMatches, float maxDistance,
 -        const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null());
 -
 -    // 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 GpuMat& trainIdx, const GpuMat& distance, const GpuMat& 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 GpuMat& query, const GpuMat& train,
 -        std::vector< std::vector<DMatch> >& matches, float maxDistance,
 -        const GpuMat& mask = GpuMat(), 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 GpuMat& query, GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance, GpuMat& nMatches, float maxDistance,
 -        const std::vector<GpuMat>& masks = std::vector<GpuMat>(), Stream& stream = Stream::Null());
 -
 -    // 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 GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& distance, const GpuMat& 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 GpuMat& query, std::vector< std::vector<DMatch> >& matches, float maxDistance,
 -        const std::vector<GpuMat>& masks = std::vector<GpuMat>(), bool compactResult = false);
 -
 -    DistType distType;
 -
 -private:
 -    std::vector<GpuMat> trainDescCollection;
 -};
 -
 -template <class Distance>
 -class CV_EXPORTS BruteForceMatcher_GPU;
 -
 -template <typename T>
 -class CV_EXPORTS BruteForceMatcher_GPU< L1<T> > : public BruteForceMatcher_GPU_base
 -{
 -public:
 -    explicit BruteForceMatcher_GPU() : BruteForceMatcher_GPU_base(L1Dist) {}
 -    explicit BruteForceMatcher_GPU(L1<T> /*d*/) : BruteForceMatcher_GPU_base(L1Dist) {}
 -};
 -template <typename T>
 -class CV_EXPORTS BruteForceMatcher_GPU< L2<T> > : public BruteForceMatcher_GPU_base
 -{
 -public:
 -    explicit BruteForceMatcher_GPU() : BruteForceMatcher_GPU_base(L2Dist) {}
 -    explicit BruteForceMatcher_GPU(L2<T> /*d*/) : BruteForceMatcher_GPU_base(L2Dist) {}
 -};
 -template <> class CV_EXPORTS BruteForceMatcher_GPU< Hamming > : public BruteForceMatcher_GPU_base
 -{
 -public:
 -    explicit BruteForceMatcher_GPU() : BruteForceMatcher_GPU_base(HammingDist) {}
 -    explicit BruteForceMatcher_GPU(Hamming /*d*/) : BruteForceMatcher_GPU_base(HammingDist) {}
 -};
 -
 -class CV_EXPORTS BFMatcher_GPU : public BruteForceMatcher_GPU_base
 -{
 -public:
 -    explicit BFMatcher_GPU(int norm = NORM_L2) : BruteForceMatcher_GPU_base(norm == NORM_L1 ? L1Dist : norm == NORM_L2 ? L2Dist : HammingDist) {}
 -};
 -
 -////////////////////////////////// CascadeClassifier_GPU //////////////////////////////////////////
 -// The cascade classifier class for object detection: supports old haar and new lbp xlm formats and nvbin for haar cascades olny.
 -class CV_EXPORTS CascadeClassifier_GPU
 -{
 -public:
 -    CascadeClassifier_GPU();
 -    CascadeClassifier_GPU(const std::string& filename);
 -    ~CascadeClassifier_GPU();
 -
 -    bool empty() const;
 -    bool load(const std::string& filename);
 -    void release();
 -
 -    /* returns number of detected objects */
 -    int detectMultiScale(const GpuMat& image, GpuMat& objectsBuf, double scaleFactor = 1.2, int minNeighbors = 4, Size minSize = Size());
 -    int detectMultiScale(const GpuMat& image, GpuMat& objectsBuf, Size maxObjectSize, Size minSize = Size(), double scaleFactor = 1.1, int minNeighbors = 4);
 -
 -    bool findLargestObject;
 -    bool visualizeInPlace;
 -
 -    Size getClassifierSize() const;
 -
 -private:
 -    struct CascadeClassifierImpl;
 -    CascadeClassifierImpl* impl;
 -    struct HaarCascade;
 -    struct LbpCascade;
 -    friend class CascadeClassifier_GPU_LBP;
 -};
 -
 -////////////////////////////////// FAST //////////////////////////////////////////
 -
 -class CV_EXPORTS FAST_GPU
 -{
 -public:
 -    enum
 -    {
 -        LOCATION_ROW = 0,
 -        RESPONSE_ROW,
 -        ROWS_COUNT
 -    };
 -
 -    // all features have same size
 -    static const int FEATURE_SIZE = 7;
 -
 -    explicit FAST_GPU(int threshold, bool nonmaxSupression = true, double keypointsRatio = 0.05);
 -
 -    //! finds the keypoints using FAST detector
 -    //! supports only CV_8UC1 images
 -    void operator ()(const GpuMat& image, const GpuMat& mask, GpuMat& keypoints);
 -    void operator ()(const GpuMat& image, const GpuMat& mask, std::vector<KeyPoint>& keypoints);
 -
 -    //! download keypoints from device to host memory
 -    void downloadKeypoints(const GpuMat& d_keypoints, std::vector<KeyPoint>& keypoints);
 -
 -    //! convert keypoints to KeyPoint vector
 -    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 GpuMat& image, const GpuMat& mask);
 -
 -    //! get final array of keypoints
 -    //! performs nonmax supression if needed
 -    //! return final count of keypoints
 -    int getKeyPoints(GpuMat& keypoints);
 -
 -private:
 -    GpuMat kpLoc_;
 -    int count_;
 -
 -    GpuMat score_;
 -
 -    GpuMat d_keypoints_;
 -};
 -
 -////////////////////////////////// ORB //////////////////////////////////////////
 -
 -class CV_EXPORTS ORB_GPU
 -{
 -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_GPU(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 GpuMat& image, const GpuMat& mask, std::vector<KeyPoint>& keypoints);
 -    void operator()(const GpuMat& image, const GpuMat& mask, GpuMat& 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 GpuMat& image, const GpuMat& mask, std::vector<KeyPoint>& keypoints, GpuMat& descriptors);
 -    void operator()(const GpuMat& image, const GpuMat& mask, GpuMat& keypoints, GpuMat& descriptors);
 -
 -    //! download keypoints from device to host memory
 -    void downloadKeyPoints(GpuMat& d_keypoints, std::vector<KeyPoint>& keypoints);
 -
 -    //! convert keypoints to KeyPoint vector
 -    void convertKeyPoints(Mat& d_keypoints, std::vector<KeyPoint>& keypoints);
 -
 -    //! returns the descriptor size in bytes
 -    inline int descriptorSize() const { return kBytes; }
 -
 -    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 GpuMat& image, const GpuMat& mask);
 -
 -    void computeKeyPointsPyramid();
 -
 -    void computeDescriptors(GpuMat& descriptors);
 -
 -    void mergeKeyPoints(GpuMat& 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
 -    GpuMat pattern_;
 -
 -    std::vector<GpuMat> imagePyr_;
 -    std::vector<GpuMat> maskPyr_;
 -
 -    GpuMat buf_;
 -
 -    std::vector<GpuMat> keyPointsPyr_;
 -    std::vector<int> keyPointsCount_;
 -
 -    FAST_GPU fastDetector_;
 -
 -    Ptr<FilterEngine_GPU> blurFilter;
 -
 -    GpuMat d_keypoints_;
 -};
 -
 -////////////////////////////////// Optical Flow //////////////////////////////////////////
 -
 -class CV_EXPORTS BroxOpticalFlow
 -{
 -public:
 -    BroxOpticalFlow(float alpha_, float gamma_, float scale_factor_, int inner_iterations_, int outer_iterations_, int solver_iterations_) :
 -        alpha(alpha_), gamma(gamma_), scale_factor(scale_factor_),
 -        inner_iterations(inner_iterations_), outer_iterations(outer_iterations_), solver_iterations(solver_iterations_)
 -    {
 -    }
 -
 -    //! Compute optical flow
 -    //! frame0 - source frame (supports only CV_32FC1 type)
 -    //! frame1 - frame to track (with the same size and type as frame0)
 -    //! u      - flow horizontal component (along x axis)
 -    //! v      - flow vertical component (along y axis)
 -    void operator ()(const GpuMat& frame0, const GpuMat& frame1, GpuMat& u, GpuMat& v, Stream& stream = Stream::Null());
 -
 -    //! flow smoothness
 -    float alpha;
 -
 -    //! gradient constancy importance
 -    float gamma;
 -
 -    //! pyramid scale factor
 -    float scale_factor;
 -
 -    //! number of lagged non-linearity iterations (inner loop)
 -    int inner_iterations;
 -
 -    //! number of warping iterations (number of pyramid levels)
 -    int outer_iterations;
 -
 -    //! number of linear system solver iterations
 -    int solver_iterations;
 -
 -    GpuMat buf;
 -};
 -
 -class CV_EXPORTS GoodFeaturesToTrackDetector_GPU
 -{
 -public:
 -    explicit GoodFeaturesToTrackDetector_GPU(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 GpuMat& image, GpuMat& corners, const GpuMat& mask = GpuMat());
 -
 -    int maxCorners;
 -    double qualityLevel;
 -    double minDistance;
 -
 -    int blockSize;
 -    bool useHarrisDetector;
 -    double harrisK;
 -
 -    void releaseMemory()
 -    {
 -        Dx_.release();
 -        Dy_.release();
 -        buf_.release();
 -        eig_.release();
 -        minMaxbuf_.release();
 -        tmpCorners_.release();
 -    }
 -
 -private:
 -    GpuMat Dx_;
 -    GpuMat Dy_;
 -    GpuMat buf_;
 -    GpuMat eig_;
 -    GpuMat minMaxbuf_;
 -    GpuMat tmpCorners_;
 -};
 -
 -inline GoodFeaturesToTrackDetector_GPU::GoodFeaturesToTrackDetector_GPU(int maxCorners_, double qualityLevel_, double minDistance_,
 -        int blockSize_, bool useHarrisDetector_, double harrisK_)
 -{
 -    maxCorners = maxCorners_;
 -    qualityLevel = qualityLevel_;
 -    minDistance = minDistance_;
 -    blockSize = blockSize_;
 -    useHarrisDetector = useHarrisDetector_;
 -    harrisK = harrisK_;
 -}
 -
 -
 -class CV_EXPORTS PyrLKOpticalFlow
 -{
 -public:
 -    PyrLKOpticalFlow();
 -
 -    void sparse(const GpuMat& prevImg, const GpuMat& nextImg, const GpuMat& prevPts, GpuMat& nextPts,
 -        GpuMat& status, GpuMat* err = 0);
 -
 -    void dense(const GpuMat& prevImg, const GpuMat& nextImg, GpuMat& u, GpuMat& v, GpuMat* err = 0);
 -
 -    void releaseMemory();
 -
 -    Size winSize;
 -    int maxLevel;
 -    int iters;
 -    double derivLambda; //unused
 -    bool useInitialFlow;
 -    float minEigThreshold; //unused
 -    bool getMinEigenVals;  //unused
 -
 -private:
 -    GpuMat uPyr_[2];
 -    vector<GpuMat> prevPyr_;
 -    vector<GpuMat> nextPyr_;
 -    GpuMat vPyr_[2];
 -    vector<GpuMat> buf_;
 -    vector<GpuMat> unused;
 -    bool isDeviceArch11_;
 -};
 -
 -
 -class CV_EXPORTS FarnebackOpticalFlow
 -{
 -public:
 -    FarnebackOpticalFlow()
 -    {
 -        numLevels = 5;
 -        pyrScale = 0.5;
 -        fastPyramids = false;
 -        winSize = 13;
 -        numIters = 10;
 -        polyN = 5;
 -        polySigma = 1.1;
 -        flags = 0;
 -        isDeviceArch11_ = !DeviceInfo().supports(FEATURE_SET_COMPUTE_12);
 -    }
 -
 -    int numLevels;
 -    double pyrScale;
 -    bool fastPyramids;
 -    int winSize;
 -    int numIters;
 -    int polyN;
 -    double polySigma;
 -    int flags;
 -
 -    void operator ()(const GpuMat &frame0, const GpuMat &frame1, GpuMat &flowx, GpuMat &flowy, Stream &s = Stream::Null());
 -
 -    void releaseMemory()
 -    {
 -        frames_[0].release();
 -        frames_[1].release();
 -        pyrLevel_[0].release();
 -        pyrLevel_[1].release();
 -        M_.release();
 -        bufM_.release();
 -        R_[0].release();
 -        R_[1].release();
 -        blurredFrame_[0].release();
 -        blurredFrame_[1].release();
 -        pyramid0_.clear();
 -        pyramid1_.clear();
 -    }
 -
 -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 GpuMat& R0, const GpuMat& R1, GpuMat& flowx, GpuMat &flowy,
 -            GpuMat& M, GpuMat &bufM, int blockSize, bool updateMatrices, Stream streams[]);
 -
 -    void updateFlow_gaussianBlur(
 -            const GpuMat& R0, const GpuMat& R1, GpuMat& flowx, GpuMat& flowy,
 -            GpuMat& M, GpuMat &bufM, int blockSize, bool updateMatrices, Stream streams[]);
 -
 -    GpuMat frames_[2];
 -    GpuMat pyrLevel_[2], M_, bufM_, R_[2], blurredFrame_[2];
 -    std::vector<GpuMat> pyramid0_, pyramid1_;
 -
 -    bool isDeviceArch11_;
 -};
 -
 -
 -// 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_GPU
 -{
 -public:
 -    OpticalFlowDual_TVL1_GPU();
 -
 -    void operator ()(const GpuMat& I0, const GpuMat& I1, GpuMat& flowx, GpuMat& 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 GpuMat& I0, const GpuMat& I1, GpuMat& u1, GpuMat& u2);
 -
 -    std::vector<GpuMat> I0s;
 -    std::vector<GpuMat> I1s;
 -    std::vector<GpuMat> u1s;
 -    std::vector<GpuMat> u2s;
 -
 -    GpuMat I1x_buf;
 -    GpuMat I1y_buf;
 -
 -    GpuMat I1w_buf;
 -    GpuMat I1wx_buf;
 -    GpuMat I1wy_buf;
 -
 -    GpuMat grad_buf;
 -    GpuMat rho_c_buf;
 -
 -    GpuMat p11_buf;
 -    GpuMat p12_buf;
 -    GpuMat p21_buf;
 -    GpuMat p22_buf;
 -
 -    GpuMat diff_buf;
 -    GpuMat norm_buf;
 -};
 -
 -
 -//! Calculates optical flow for 2 images using block matching algorithm */
 -CV_EXPORTS void calcOpticalFlowBM(const GpuMat& prev, const GpuMat& curr,
 -                                  Size block_size, Size shift_size, Size max_range, bool use_previous,
 -                                  GpuMat& velx, GpuMat& vely, GpuMat& buf,
 -                                  Stream& stream = Stream::Null());
 -
 -class CV_EXPORTS FastOpticalFlowBM
 -{
 -public:
 -    void operator ()(const GpuMat& I0, const GpuMat& I1, GpuMat& flowx, GpuMat& flowy, int search_window = 21, int block_window = 7, Stream& s = Stream::Null());
 -
 -private:
 -    GpuMat buffer;
 -    GpuMat extended_I0;
 -    GpuMat extended_I1;
 -};
 -
 -
 -//! 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 GpuMat;
 -//!            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 GpuMat& frame0, const GpuMat& frame1,
 -                                  const GpuMat& fu, const GpuMat& fv,
 -                                  const GpuMat& bu, const GpuMat& bv,
 -                                  float pos, GpuMat& newFrame, GpuMat& buf,
 -                                  Stream& stream = Stream::Null());
 -
 -CV_EXPORTS void createOpticalFlowNeedleMap(const GpuMat& u, const GpuMat& v, GpuMat& vertex, GpuMat& colors);
 -
 -
 -//////////////////////// Background/foreground segmentation ////////////////////////
 -
 -// Foreground Object Detection from Videos Containing Complex Background.
 -// Liyuan Li, Weimin Huang, Irene Y.H. Gu, and Qi Tian.
 -// ACM MM2003 9p
 -class CV_EXPORTS FGDStatModel
 -{
 -public:
 -    struct CV_EXPORTS Params
 -    {
 -        int Lc;  // Quantized levels per 'color' component. Power of two, typically 32, 64 or 128.
 -        int N1c; // Number of color vectors used to model normal background color variation at a given pixel.
 -        int N2c; // Number of color vectors retained at given pixel.  Must be > N1c, typically ~ 5/3 of N1c.
 -        // Used to allow the first N1c vectors to adapt over time to changing background.
 -
 -        int Lcc;  // Quantized levels per 'color co-occurrence' component.  Power of two, typically 16, 32 or 64.
 -        int N1cc; // Number of color co-occurrence vectors used to model normal background color variation at a given pixel.
 -        int N2cc; // Number of color co-occurrence vectors retained at given pixel.  Must be > N1cc, typically ~ 5/3 of N1cc.
 -        // Used to allow the first N1cc vectors to adapt over time to changing background.
 -
 -        bool is_obj_without_holes; // If TRUE we ignore holes within foreground blobs. Defaults to TRUE.
 -        int perform_morphing;     // Number of erode-dilate-erode foreground-blob cleanup iterations.
 -        // These erase one-pixel junk blobs and merge almost-touching blobs. Default value is 1.
 -
 -        float alpha1; // How quickly we forget old background pixel values seen. Typically set to 0.1.
 -        float alpha2; // "Controls speed of feature learning". Depends on T. Typical value circa 0.005.
 -        float alpha3; // Alternate to alpha2, used (e.g.) for quicker initial convergence. Typical value 0.1.
 -
 -        float delta;   // Affects color and color co-occurrence quantization, typically set to 2.
 -        float T;       // A percentage value which determines when new features can be recognized as new background. (Typically 0.9).
 -        float minArea; // Discard foreground blobs whose bounding box is smaller than this threshold.
 -
 -        // default Params
 -        Params();
 -    };
 -
 -    // out_cn - channels count in output result (can be 3 or 4)
 -    // 4-channels require more memory, but a bit faster
 -    explicit FGDStatModel(int out_cn = 3);
 -    explicit FGDStatModel(const cv::gpu::GpuMat& firstFrame, const Params& params = Params(), int out_cn = 3);
 -
 -    ~FGDStatModel();
 -
 -    void create(const cv::gpu::GpuMat& firstFrame, const Params& params = Params());
 -    void release();
 -
 -    int update(const cv::gpu::GpuMat& curFrame);
 -
 -    //8UC3 or 8UC4 reference background image
 -    cv::gpu::GpuMat background;
 -
 -    //8UC1 foreground image
 -    cv::gpu::GpuMat foreground;
 -
 -    std::vector< std::vector<cv::Point> > foreground_regions;
 -
 -private:
 -    FGDStatModel(const FGDStatModel&);
 -    FGDStatModel& operator=(const FGDStatModel&);
 -
 -    class Impl;
 -    std::auto_ptr<Impl> impl_;
 -};
 -
 -/*!
 - 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_GPU
 -{
 -public:
 -    //! the default constructor
 -    MOG_GPU(int nmixtures = -1);
 -
 -    //! re-initiaization method
 -    void initialize(Size frameSize, int frameType);
 -
 -    //! the update operator
 -    void operator()(const GpuMat& frame, GpuMat& fgmask, float learningRate = 0.0f, Stream& stream = Stream::Null());
 -
 -    //! computes a background image which are the mean of all background gaussians
 -    void getBackgroundImage(GpuMat& backgroundImage, Stream& stream = Stream::Null()) const;
 -
 -    //! releases all inner buffers
 -    void release();
 -
 -    int history;
 -    float varThreshold;
 -    float backgroundRatio;
 -    float noiseSigma;
 -
 -private:
 -    int nmixtures_;
 -
 -    Size frameSize_;
 -    int frameType_;
 -    int nframes_;
 -
 -    GpuMat weight_;
 -    GpuMat sortKey_;
 -    GpuMat mean_;
 -    GpuMat 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_GPU
 -{
 -public:
 -    //! the default constructor
 -    MOG2_GPU(int nmixtures = -1);
 -
 -    //! re-initiaization method
 -    void initialize(Size frameSize, int frameType);
 -
 -    //! the update operator
 -    void operator()(const GpuMat& frame, GpuMat& fgmask, float learningRate = -1.0f, Stream& stream = Stream::Null());
 -
 -    //! computes a background image which are the mean of all background gaussians
 -    void getBackgroundImage(GpuMat& backgroundImage, Stream& stream = Stream::Null()) 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_;
 -
 -    GpuMat weight_;
 -    GpuMat variance_;
 -    GpuMat mean_;
 -
 -    GpuMat bgmodelUsedModes_; //keep track of number of modes per pixel
 -};
 -
 -/**
 - * Background Subtractor module. Takes a series of images and returns a sequence of mask (8UC1)
 - * images of the same size, where 255 indicates Foreground and 0 represents Background.
 - * This class implements an algorithm described in "Visual Tracking of Human Visitors under
 - * Variable-Lighting Conditions for a Responsive Audio Art Installation," A. Godbehere,
 - * A. Matsukawa, K. Goldberg, American Control Conference, Montreal, June 2012.
 - */
 -class CV_EXPORTS GMG_GPU
 -{
 -public:
 -    GMG_GPU();
 -
 -    /**
 -     * Validate parameters and set up data structures for appropriate frame size.
 -     * @param frameSize Input frame size
 -     * @param min       Minimum value taken on by pixels in image sequence. Usually 0
 -     * @param max       Maximum value taken on by pixels in image sequence. e.g. 1.0 or 255
 -     */
 -    void initialize(Size frameSize, float min = 0.0f, float max = 255.0f);
 -
 -    /**
 -     * Performs single-frame background subtraction and builds up a statistical background image
 -     * model.
 -     * @param frame        Input frame
 -     * @param fgmask       Output mask image representing foreground and background pixels
 -     * @param stream       Stream for the asynchronous version
 -     */
 -    void operator ()(const GpuMat& frame, GpuMat& fgmask, float learningRate = -1.0f, Stream& stream = Stream::Null());
 -
 -    //! Releases all inner buffers
 -    void release();
 -
 -    //! Total number of distinct colors to maintain in histogram.
 -    int maxFeatures;
 -
 -    //! Set between 0.0 and 1.0, determines how quickly features are "forgotten" from histograms.
 -    float learningRate;
 -
 -    //! Number of frames of video to use to initialize histograms.
 -    int numInitializationFrames;
 -
 -    //! Number of discrete levels in each channel to be used in histograms.
 -    int quantizationLevels;
 -
 -    //! Prior probability that any given pixel is a background pixel. A sensitivity parameter.
 -    float backgroundPrior;
 -
 -    //! Value above which pixel is determined to be FG.
 -    float decisionThreshold;
 -
 -    //! Smoothing radius, in pixels, for cleaning up FG image.
 -    int smoothingRadius;
 -
 -    //! Perform background model update.
 -    bool updateBackgroundModel;
 -
 -private:
 -    float maxVal_, minVal_;
 -
 -    Size frameSize_;
 -
 -    int frameNum_;
 -
 -    GpuMat nfeatures_;
 -    GpuMat colors_;
 -    GpuMat weights_;
 -
 -    Ptr<FilterEngine_GPU> boxFilter_;
 -    GpuMat buf_;
 -};
 -
 -////////////////////////////////// Video Encoding //////////////////////////////////
 -
 -// Works only under Windows
 -// Supports olny H264 video codec and AVI files
 -class CV_EXPORTS VideoWriter_GPU
 -{
 -public:
 -    struct EncoderParams;
 -
 -    // Callbacks for video encoder, use it if you want to work with raw video stream
 -    class EncoderCallBack;
 -
 -    enum SurfaceFormat
 -    {
 -        SF_UYVY = 0,
 -        SF_YUY2,
 -        SF_YV12,
 -        SF_NV12,
 -        SF_IYUV,
 -        SF_BGR,
 -        SF_GRAY = SF_BGR
 -    };
 -
 -    VideoWriter_GPU();
 -    VideoWriter_GPU(const std::string& fileName, cv::Size frameSize, double fps, SurfaceFormat format = SF_BGR);
 -    VideoWriter_GPU(const std::string& fileName, cv::Size frameSize, double fps, const EncoderParams& params, SurfaceFormat format = SF_BGR);
 -    VideoWriter_GPU(const cv::Ptr<EncoderCallBack>& encoderCallback, cv::Size frameSize, double fps, SurfaceFormat format = SF_BGR);
 -    VideoWriter_GPU(const cv::Ptr<EncoderCallBack>& encoderCallback, cv::Size frameSize, double fps, const EncoderParams& params, SurfaceFormat format = SF_BGR);
 -    ~VideoWriter_GPU();
 -
 -    // all methods throws cv::Exception if error occurs
 -    void open(const std::string& fileName, cv::Size frameSize, double fps, SurfaceFormat format = SF_BGR);
 -    void open(const std::string& fileName, cv::Size frameSize, double fps, const EncoderParams& params, SurfaceFormat format = SF_BGR);
 -    void open(const cv::Ptr<EncoderCallBack>& encoderCallback, cv::Size frameSize, double fps, SurfaceFormat format = SF_BGR);
 -    void open(const cv::Ptr<EncoderCallBack>& encoderCallback, cv::Size frameSize, double fps, const EncoderParams& params, SurfaceFormat format = SF_BGR);
 -
 -    bool isOpened() const;
 -    void close();
 -
 -    void write(const cv::gpu::GpuMat& image, bool lastFrame = false);
 -
 -    struct CV_EXPORTS EncoderParams
 -    {
 -        int       P_Interval;      //    NVVE_P_INTERVAL,
 -        int       IDR_Period;      //    NVVE_IDR_PERIOD,
 -        int       DynamicGOP;      //    NVVE_DYNAMIC_GOP,
 -        int       RCType;          //    NVVE_RC_TYPE,
 -        int       AvgBitrate;      //    NVVE_AVG_BITRATE,
 -        int       PeakBitrate;     //    NVVE_PEAK_BITRATE,
 -        int       QP_Level_Intra;  //    NVVE_QP_LEVEL_INTRA,
 -        int       QP_Level_InterP; //    NVVE_QP_LEVEL_INTER_P,
 -        int       QP_Level_InterB; //    NVVE_QP_LEVEL_INTER_B,
 -        int       DeblockMode;     //    NVVE_DEBLOCK_MODE,
 -        int       ProfileLevel;    //    NVVE_PROFILE_LEVEL,
 -        int       ForceIntra;      //    NVVE_FORCE_INTRA,
 -        int       ForceIDR;        //    NVVE_FORCE_IDR,
 -        int       ClearStat;       //    NVVE_CLEAR_STAT,
 -        int       DIMode;          //    NVVE_SET_DEINTERLACE,
 -        int       Presets;         //    NVVE_PRESETS,
 -        int       DisableCabac;    //    NVVE_DISABLE_CABAC,
 -        int       NaluFramingType; //    NVVE_CONFIGURE_NALU_FRAMING_TYPE
 -        int       DisableSPSPPS;   //    NVVE_DISABLE_SPS_PPS
 -
 -        EncoderParams();
 -        explicit EncoderParams(const std::string& configFile);
 -
 -        void load(const std::string& configFile);
 -        void save(const std::string& configFile) const;
 -    };
 -
 -    EncoderParams getParams() const;
 -
 -    class CV_EXPORTS EncoderCallBack
 -    {
 -    public:
 -        enum PicType
 -        {
 -            IFRAME = 1,
 -            PFRAME = 2,
 -            BFRAME = 3
 -        };
 -
 -        virtual ~EncoderCallBack() {}
 -
 -        // callback function to signal the start of bitstream that is to be encoded
 -        // must return pointer to buffer
 -        virtual uchar* acquireBitStream(int* bufferSize) = 0;
 -
 -        // callback function to signal that the encoded bitstream is ready to be written to file
 -        virtual void releaseBitStream(unsigned char* data, int size) = 0;
 -
 -        // callback function to signal that the encoding operation on the frame has started
 -        virtual void onBeginFrame(int frameNumber, PicType picType) = 0;
 -
 -        // callback function signals that the encoding operation on the frame has finished
 -        virtual void onEndFrame(int frameNumber, PicType picType) = 0;
 -    };
 -
 -private:
 -    VideoWriter_GPU(const VideoWriter_GPU&);
 -    VideoWriter_GPU& operator=(const VideoWriter_GPU&);
 -
 -    class Impl;
 -    std::auto_ptr<Impl> impl_;
 -};
 -
 -
 -////////////////////////////////// Video Decoding //////////////////////////////////////////
 -
 -namespace detail
 -{
 -    class FrameQueue;
 -    class VideoParser;
 -}
 -
 -class CV_EXPORTS VideoReader_GPU
 -{
 -public:
 -    enum Codec
 -    {
 -        MPEG1 = 0,
 -        MPEG2,
 -        MPEG4,
 -        VC1,
 -        H264,
 -        JPEG,
 -        H264_SVC,
 -        H264_MVC,
 -
 -        Uncompressed_YUV420 = (('I'<<24)|('Y'<<16)|('U'<<8)|('V')),   // Y,U,V (4:2:0)
 -        Uncompressed_YV12   = (('Y'<<24)|('V'<<16)|('1'<<8)|('2')),   // Y,V,U (4:2:0)
 -        Uncompressed_NV12   = (('N'<<24)|('V'<<16)|('1'<<8)|('2')),   // Y,UV  (4:2:0)
 -        Uncompressed_YUYV   = (('Y'<<24)|('U'<<16)|('Y'<<8)|('V')),   // YUYV/YUY2 (4:2:2)
 -        Uncompressed_UYVY   = (('U'<<24)|('Y'<<16)|('V'<<8)|('Y')),   // UYVY (4:2:2)
 -    };
 -
 -    enum ChromaFormat
 -    {
 -        Monochrome=0,
 -        YUV420,
 -        YUV422,
 -        YUV444,
 -    };
 -
 -    struct FormatInfo
 -    {
 -        Codec codec;
 -        ChromaFormat chromaFormat;
 -        int width;
 -        int height;
 -    };
 -
 -    class VideoSource;
 -
 -    VideoReader_GPU();
 -    explicit VideoReader_GPU(const std::string& filename);
 -    explicit VideoReader_GPU(const cv::Ptr<VideoSource>& source);
 -
 -    ~VideoReader_GPU();
 -
 -    void open(const std::string& filename);
 -    void open(const cv::Ptr<VideoSource>& source);
 -    bool isOpened() const;
 -
 -    void close();
 -
 -    bool read(GpuMat& image);
 -
 -    FormatInfo format() const;
 -    void dumpFormat(std::ostream& st);
 -
 -    class CV_EXPORTS VideoSource
 -    {
 -    public:
 -        VideoSource() : frameQueue_(0), videoParser_(0) {}
 -        virtual ~VideoSource() {}
 -
 -        virtual FormatInfo format() const = 0;
 -        virtual void start() = 0;
 -        virtual void stop() = 0;
 -        virtual bool isStarted() const = 0;
 -        virtual bool hasError() const = 0;
 -
 -        void setFrameQueue(detail::FrameQueue* frameQueue) { frameQueue_ = frameQueue; }
 -        void setVideoParser(detail::VideoParser* videoParser) { videoParser_ = videoParser; }
 -
 -    protected:
 -        bool parseVideoData(const uchar* data, size_t size, bool endOfStream = false);
 -
 -    private:
 -        VideoSource(const VideoSource&);
 -        VideoSource& operator =(const VideoSource&);
 -
 -        detail::FrameQueue* frameQueue_;
 -        detail::VideoParser* videoParser_;
 -    };
 -
 -private:
 -    VideoReader_GPU(const VideoReader_GPU&);
 -    VideoReader_GPU& operator =(const VideoReader_GPU&);
 -
 -    class Impl;
 -    std::auto_ptr<Impl> impl_;
 -};
 -
 -//! removes points (CV_32FC2, single row matrix) with zero mask value
 -CV_EXPORTS void compactPoints(GpuMat &points0, GpuMat &points1, const GpuMat &mask);
 -
 -CV_EXPORTS void calcWobbleSuppressionMaps(
 -        int left, int idx, int right, Size size, const Mat &ml, const Mat &mr,
 -        GpuMat &mapx, GpuMat &mapy);
 -
 -} // namespace gpu
 -
 -} // namespace cv
 -
 -#endif /* __OPENCV_GPU_HPP__ */
++#include "opencv2/gpu.hpp"
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
@@@ -39,8 -40,8 +40,7 @@@
  //
  //M*/
  
  #include <iostream>
 -#include <string>
  #include <vector>
  #include "NCV.hpp"
  
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
Simple merge
index df456b5,0000000..10a5d53
mode 100644,000000..100644
--- /dev/null
@@@ -1,1299 -1,0 +1,1314 @@@
 +/*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_IMGPROC_HPP__
 +#define __OPENCV_IMGPROC_HPP__
 +
 +#include "opencv2/core.hpp"
 +#include "opencv2/imgproc/types_c.h"
 +
 +#ifdef __cplusplus
 +
 +/*! \namespace cv
 + Namespace where all the C++ OpenCV functionality resides
 + */
 +namespace cv
 +{
 +
 +//! various border interpolation methods
 +enum { BORDER_REPLICATE=IPL_BORDER_REPLICATE, BORDER_CONSTANT=IPL_BORDER_CONSTANT,
 +       BORDER_REFLECT=IPL_BORDER_REFLECT, BORDER_WRAP=IPL_BORDER_WRAP,
 +       BORDER_REFLECT_101=IPL_BORDER_REFLECT_101, BORDER_REFLECT101=BORDER_REFLECT_101,
 +       BORDER_TRANSPARENT=IPL_BORDER_TRANSPARENT,
 +       BORDER_DEFAULT=BORDER_REFLECT_101, BORDER_ISOLATED=16 };
 +
 +//! 1D interpolation function: returns coordinate of the "donor" pixel for the specified location p.
 +CV_EXPORTS_W int borderInterpolate( int p, int len, int borderType );
 +
 +/*!
 + 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.
 +
 + Several functions in OpenCV return Ptr<BaseRowFilter> for the specific types of filters,
 + and those pointers can be used directly or within cv::FilterEngine.
 +*/
 +class CV_EXPORTS BaseRowFilter
 +{
 +public:
 +    //! the default constructor
 +    BaseRowFilter();
 +    //! the destructor
 +    virtual ~BaseRowFilter();
 +    //! the filtering operator. Must be overrided in the derived classes. The horizontal border interpolation is done outside of the class.
 +    virtual void operator()(const uchar* src, uchar* dst,
 +                            int width, int cn) = 0;
 +    int ksize, anchor;
 +};
 +
 +
 +/*!
 + 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.
 +
 + Several functions in OpenCV return Ptr<BaseColumnFilter> for the specific types of filters,
 + and those pointers can be used directly or within cv::FilterEngine.
 +
 + Unlike cv::BaseRowFilter, cv::BaseColumnFilter may have some context information,
 + i.e. box filter keeps the sliding sum of elements. To reset the state BaseColumnFilter::reset()
 + must be called (e.g. the method is called by cv::FilterEngine)
 + */
 +class CV_EXPORTS BaseColumnFilter
 +{
 +public:
 +    //! the default constructor
 +    BaseColumnFilter();
 +    //! the destructor
 +    virtual ~BaseColumnFilter();
 +    //! the filtering operator. Must be overrided in the derived classes. The vertical border interpolation is done outside of the class.
 +    virtual void operator()(const uchar** src, uchar* dst, int dststep,
 +                            int dstcount, int width) = 0;
 +    //! resets the internal buffers, if any
 +    virtual void reset();
 +    int ksize, anchor;
 +};
 +
 +/*!
 + The Base Class for Non-Separable 2D Filters.
 +
 + This is the base class for linear or non-linear 2D filters.
 +
 + Several functions in OpenCV return Ptr<BaseFilter> for the specific types of filters,
 + and those pointers can be used directly or within cv::FilterEngine.
 +
 + Similar to cv::BaseColumnFilter, the class may have some context information,
 + that should be reset using BaseFilter::reset() method before processing the new array.
 +*/
 +class CV_EXPORTS BaseFilter
 +{
 +public:
 +    //! the default constructor
 +    BaseFilter();
 +    //! the destructor
 +    virtual ~BaseFilter();
 +    //! the filtering operator. The horizontal and the vertical border interpolation is done outside of the class.
 +    virtual void operator()(const uchar** src, uchar* dst, int dststep,
 +                            int dstcount, int width, int cn) = 0;
 +    //! resets the internal buffers, if any
 +    virtual void reset();
 +    Size ksize;
 +    Point anchor;
 +};
 +
 +/*!
 + The Main Class for Image Filtering.
 +
 + The class can be used to apply an arbitrary filtering operation to an image.
 + It contains all the necessary intermediate buffers, it computes extrapolated values
 + of the "virtual" pixels outside of the image etc.
 + Pointers to the initialized cv::FilterEngine instances
 + are returned by various OpenCV functions, such as cv::createSeparableLinearFilter(),
 + cv::createLinearFilter(), cv::createGaussianFilter(), cv::createDerivFilter(),
 + cv::createBoxFilter() and cv::createMorphologyFilter().
 +
 + Using the class you can process large images by parts and build complex pipelines
 + that include filtering as some of the stages. If all you need is to apply some pre-defined
 + filtering operation, you may use cv::filter2D(), cv::erode(), cv::dilate() etc.
 + functions that create FilterEngine internally.
 +
 + Here is the example on how to use the class to implement Laplacian operator, which is the sum of
 + second-order derivatives. More complex variant for different types is implemented in cv::Laplacian().
 +
 + \code
 + void laplace_f(const Mat& src, Mat& dst)
 + {
 +     CV_Assert( src.type() == CV_32F );
 +     // make sure the destination array has the proper size and type
 +     dst.create(src.size(), src.type());
 +
 +     // get the derivative and smooth kernels for d2I/dx2.
 +     // for d2I/dy2 we could use the same kernels, just swapped
 +     Mat kd, ks;
 +     getSobelKernels( kd, ks, 2, 0, ksize, false, ktype );
 +
 +     // let's process 10 source rows at once
 +     int DELTA = std::min(10, src.rows);
 +     Ptr<FilterEngine> Fxx = createSeparableLinearFilter(src.type(),
 +     dst.type(), kd, ks, Point(-1,-1), 0, borderType, borderType, Scalar() );
 +     Ptr<FilterEngine> Fyy = createSeparableLinearFilter(src.type(),
 +     dst.type(), ks, kd, Point(-1,-1), 0, borderType, borderType, Scalar() );
 +
 +     int y = Fxx->start(src), dsty = 0, dy = 0;
 +     Fyy->start(src);
 +     const uchar* sptr = src.data + y*src.step;
 +
 +     // allocate the buffers for the spatial image derivatives;
 +     // the buffers need to have more than DELTA rows, because at the
 +     // last iteration the output may take max(kd.rows-1,ks.rows-1)
 +     // rows more than the input.
 +     Mat Ixx( DELTA + kd.rows - 1, src.cols, dst.type() );
 +     Mat Iyy( DELTA + kd.rows - 1, src.cols, dst.type() );
 +
 +     // inside the loop we always pass DELTA rows to the filter
 +     // (note that the "proceed" method takes care of possibe overflow, since
 +     // it was given the actual image height in the "start" method)
 +     // on output we can get:
 +     //  * < DELTA rows (the initial buffer accumulation stage)
 +     //  * = DELTA rows (settled state in the middle)
 +     //  * > DELTA rows (then the input image is over, but we generate
 +     //                  "virtual" rows using the border mode and filter them)
 +     // this variable number of output rows is dy.
 +     // dsty is the current output row.
 +     // sptr is the pointer to the first input row in the portion to process
 +     for( ; dsty < dst.rows; sptr += DELTA*src.step, dsty += dy )
 +     {
 +         Fxx->proceed( sptr, (int)src.step, DELTA, Ixx.data, (int)Ixx.step );
 +         dy = Fyy->proceed( sptr, (int)src.step, DELTA, d2y.data, (int)Iyy.step );
 +         if( dy > 0 )
 +         {
 +             Mat dstripe = dst.rowRange(dsty, dsty + dy);
 +             add(Ixx.rowRange(0, dy), Iyy.rowRange(0, dy), dstripe);
 +         }
 +     }
 + }
 + \endcode
 +*/
 +class CV_EXPORTS FilterEngine
 +{
 +public:
 +    //! the default constructor
 +    FilterEngine();
 +    //! the full constructor. Either _filter2D or both _rowFilter and _columnFilter must be non-empty.
 +    FilterEngine(const Ptr<BaseFilter>& _filter2D,
 +                 const Ptr<BaseRowFilter>& _rowFilter,
 +                 const Ptr<BaseColumnFilter>& _columnFilter,
 +                 int srcType, int dstType, int bufType,
 +                 int _rowBorderType=BORDER_REPLICATE,
 +                 int _columnBorderType=-1,
 +                 const Scalar& _borderValue=Scalar());
 +    //! the destructor
 +    virtual ~FilterEngine();
 +    //! reinitializes the engine. The previously assigned filters are released.
 +    void init(const Ptr<BaseFilter>& _filter2D,
 +              const Ptr<BaseRowFilter>& _rowFilter,
 +              const Ptr<BaseColumnFilter>& _columnFilter,
 +              int srcType, int dstType, int bufType,
 +              int _rowBorderType=BORDER_REPLICATE, int _columnBorderType=-1,
 +              const Scalar& _borderValue=Scalar());
 +    //! starts filtering of the specified ROI of an image of size wholeSize.
 +    virtual int start(Size wholeSize, Rect roi, int maxBufRows=-1);
 +    //! starts filtering of the specified ROI of the specified image.
 +    virtual int start(const Mat& src, const Rect& srcRoi=Rect(0,0,-1,-1),
 +                      bool isolated=false, int maxBufRows=-1);
 +    //! processes the next srcCount rows of the image.
 +    virtual int proceed(const uchar* src, int srcStep, int srcCount,
 +                        uchar* dst, int dstStep);
 +    //! applies filter to the specified ROI of the image. if srcRoi=(0,0,-1,-1), the whole image is filtered.
 +    virtual void apply( const Mat& src, Mat& dst,
 +                        const Rect& srcRoi=Rect(0,0,-1,-1),
 +                        Point dstOfs=Point(0,0),
 +                        bool isolated=false);
 +    //! returns true if the filter is separable
 +    bool isSeparable() const { return (const BaseFilter*)filter2D == 0; }
 +    //! returns the number
 +    int remainingInputRows() const;
 +    int remainingOutputRows() const;
 +
 +    int srcType, dstType, bufType;
 +    Size ksize;
 +    Point anchor;
 +    int maxWidth;
 +    Size wholeSize;
 +    Rect roi;
 +    int dx1, dx2;
 +    int rowBorderType, columnBorderType;
 +    std::vector<int> borderTab;
 +    int borderElemSize;
 +    std::vector<uchar> ringBuf;
 +    std::vector<uchar> srcRow;
 +    std::vector<uchar> constBorderValue;
 +    std::vector<uchar> constBorderRow;
 +    int bufStep, startY, startY0, endY, rowCount, dstY;
 +    std::vector<uchar*> rows;
 +
 +    Ptr<BaseFilter> filter2D;
 +    Ptr<BaseRowFilter> rowFilter;
 +    Ptr<BaseColumnFilter> columnFilter;
 +};
 +
 +//! type of the kernel
 +enum { KERNEL_GENERAL=0, KERNEL_SYMMETRICAL=1, KERNEL_ASYMMETRICAL=2,
 +       KERNEL_SMOOTH=4, KERNEL_INTEGER=8 };
 +
 +//! returns type (one of KERNEL_*) of 1D or 2D kernel specified by its coefficients.
 +CV_EXPORTS int getKernelType(InputArray kernel, Point anchor);
 +
 +//! returns the primitive row filter with the specified kernel
 +CV_EXPORTS Ptr<BaseRowFilter> getLinearRowFilter(int srcType, int bufType,
 +                                            InputArray kernel, int anchor,
 +                                            int symmetryType);
 +
 +//! returns the primitive column filter with the specified kernel
 +CV_EXPORTS Ptr<BaseColumnFilter> getLinearColumnFilter(int bufType, int dstType,
 +                                            InputArray kernel, int anchor,
 +                                            int symmetryType, double delta=0,
 +                                            int bits=0);
 +
 +//! returns 2D filter with the specified kernel
 +CV_EXPORTS Ptr<BaseFilter> getLinearFilter(int srcType, int dstType,
 +                                           InputArray kernel,
 +                                           Point anchor=Point(-1,-1),
 +                                           double delta=0, int bits=0);
 +
 +//! returns the separable linear filter engine
 +CV_EXPORTS Ptr<FilterEngine> createSeparableLinearFilter(int srcType, int dstType,
 +                          InputArray rowKernel, InputArray columnKernel,
 +                          Point anchor=Point(-1,-1), double delta=0,
 +                          int rowBorderType=BORDER_DEFAULT,
 +                          int columnBorderType=-1,
 +                          const Scalar& borderValue=Scalar());
 +
 +//! returns the non-separable linear filter engine
 +CV_EXPORTS Ptr<FilterEngine> createLinearFilter(int srcType, int dstType,
 +                 InputArray kernel, Point _anchor=Point(-1,-1),
 +                 double delta=0, int rowBorderType=BORDER_DEFAULT,
 +                 int columnBorderType=-1, const Scalar& borderValue=Scalar());
 +
 +//! returns the Gaussian kernel with the specified parameters
 +CV_EXPORTS_W Mat getGaussianKernel( int ksize, double sigma, int ktype=CV_64F );
 +
 +//! returns the Gaussian filter engine
 +CV_EXPORTS Ptr<FilterEngine> createGaussianFilter( int type, Size ksize,
 +                                    double sigma1, double sigma2=0,
 +                                    int borderType=BORDER_DEFAULT);
 +//! initializes kernels of the generalized Sobel operator
 +CV_EXPORTS_W void getDerivKernels( OutputArray kx, OutputArray ky,
 +                                   int dx, int dy, int ksize,
 +                                   bool normalize=false, int ktype=CV_32F );
 +//! returns filter engine for the generalized Sobel operator
 +CV_EXPORTS Ptr<FilterEngine> createDerivFilter( int srcType, int dstType,
 +                                        int dx, int dy, int ksize,
 +                                        int borderType=BORDER_DEFAULT );
 +//! returns horizontal 1D box filter
 +CV_EXPORTS Ptr<BaseRowFilter> getRowSumFilter(int srcType, int sumType,
 +                                              int ksize, int anchor=-1);
 +//! returns vertical 1D box filter
 +CV_EXPORTS Ptr<BaseColumnFilter> getColumnSumFilter( int sumType, int dstType,
 +                                                     int ksize, int anchor=-1,
 +                                                     double scale=1);
 +//! returns box filter engine
 +CV_EXPORTS Ptr<FilterEngine> createBoxFilter( int srcType, int dstType, Size ksize,
 +                                              Point anchor=Point(-1,-1),
 +                                              bool normalize=true,
 +                                              int borderType=BORDER_DEFAULT);
 +
 +//! returns the Gabor kernel with the specified parameters
 +CV_EXPORTS_W Mat getGaborKernel( Size ksize, double sigma, double theta, double lambd,
 +                                 double gamma, double psi=CV_PI*0.5, int ktype=CV_64F );
 +
 +//! type of morphological operation
 +enum { MORPH_ERODE=CV_MOP_ERODE, MORPH_DILATE=CV_MOP_DILATE,
 +       MORPH_OPEN=CV_MOP_OPEN, MORPH_CLOSE=CV_MOP_CLOSE,
 +       MORPH_GRADIENT=CV_MOP_GRADIENT, MORPH_TOPHAT=CV_MOP_TOPHAT,
 +       MORPH_BLACKHAT=CV_MOP_BLACKHAT };
 +
 +//! returns horizontal 1D morphological filter
 +CV_EXPORTS Ptr<BaseRowFilter> getMorphologyRowFilter(int op, int type, int ksize, int anchor=-1);
 +//! returns vertical 1D morphological filter
 +CV_EXPORTS Ptr<BaseColumnFilter> getMorphologyColumnFilter(int op, int type, int ksize, int anchor=-1);
 +//! returns 2D morphological filter
 +CV_EXPORTS Ptr<BaseFilter> getMorphologyFilter(int op, int type, InputArray kernel,
 +                                               Point anchor=Point(-1,-1));
 +
 +//! returns "magic" border value for erosion and dilation. It is automatically transformed to Scalar::all(-DBL_MAX) for dilation.
 +static inline Scalar morphologyDefaultBorderValue() { return Scalar::all(DBL_MAX); }
 +
 +//! returns morphological filter engine. Only MORPH_ERODE and MORPH_DILATE are supported.
 +CV_EXPORTS Ptr<FilterEngine> createMorphologyFilter(int op, int type, InputArray kernel,
 +                    Point anchor=Point(-1,-1), int rowBorderType=BORDER_CONSTANT,
 +                    int columnBorderType=-1,
 +                    const Scalar& borderValue=morphologyDefaultBorderValue());
 +
 +//! shape of the structuring element
 +enum { MORPH_RECT=0, MORPH_CROSS=1, MORPH_ELLIPSE=2 };
 +//! returns structuring element of the specified shape and size
 +CV_EXPORTS_W Mat getStructuringElement(int shape, Size ksize, Point anchor=Point(-1,-1));
 +
 +template<> CV_EXPORTS void Ptr<IplConvKernel>::delete_obj();
 +
 +//! copies 2D array to a larger destination array with extrapolation of the outer part of src using the specified border mode
 +CV_EXPORTS_W void copyMakeBorder( InputArray src, OutputArray dst,
 +                                int top, int bottom, int left, int right,
 +                                int borderType, const Scalar& value=Scalar() );
 +
 +//! smooths the image using median filter.
 +CV_EXPORTS_W void medianBlur( InputArray src, OutputArray dst, int ksize );
 +//! smooths the image using Gaussian filter.
 +CV_EXPORTS_W void GaussianBlur( InputArray src,
 +                                               OutputArray dst, Size ksize,
 +                                               double sigmaX, double sigmaY=0,
 +                                               int borderType=BORDER_DEFAULT );
 +//! smooths the image using bilateral filter
 +CV_EXPORTS_W void bilateralFilter( InputArray src, OutputArray dst, int d,
 +                                   double sigmaColor, double sigmaSpace,
 +                                   int borderType=BORDER_DEFAULT );
 +//! smooths the image using the box filter. Each pixel is processed in O(1) time
 +CV_EXPORTS_W void boxFilter( InputArray src, OutputArray dst, int ddepth,
 +                             Size ksize, Point anchor=Point(-1,-1),
 +                             bool normalize=true,
 +                             int borderType=BORDER_DEFAULT );
 +//! a synonym for normalized box filter
 +CV_EXPORTS_W void blur( InputArray src, OutputArray dst,
 +                        Size ksize, Point anchor=Point(-1,-1),
 +                        int borderType=BORDER_DEFAULT );
 +
 +//! applies non-separable 2D linear filter to the image
 +CV_EXPORTS_W void filter2D( InputArray src, OutputArray dst, int ddepth,
 +                            InputArray kernel, Point anchor=Point(-1,-1),
 +                            double delta=0, int borderType=BORDER_DEFAULT );
 +
 +//! applies separable 2D linear filter to the image
 +CV_EXPORTS_W void sepFilter2D( InputArray src, OutputArray dst, int ddepth,
 +                               InputArray kernelX, InputArray kernelY,
 +                               Point anchor=Point(-1,-1),
 +                               double delta=0, int borderType=BORDER_DEFAULT );
 +
 +//! applies generalized Sobel operator to the image
 +CV_EXPORTS_W void Sobel( InputArray src, OutputArray dst, int ddepth,
 +                         int dx, int dy, int ksize=3,
 +                         double scale=1, double delta=0,
 +                         int borderType=BORDER_DEFAULT );
 +
 +//! applies the vertical or horizontal Scharr operator to the image
 +CV_EXPORTS_W void Scharr( InputArray src, OutputArray dst, int ddepth,
 +                          int dx, int dy, double scale=1, double delta=0,
 +                          int borderType=BORDER_DEFAULT );
 +
 +//! applies Laplacian operator to the image
 +CV_EXPORTS_W void Laplacian( InputArray src, OutputArray dst, int ddepth,
 +                             int ksize=1, double scale=1, double delta=0,
 +                             int borderType=BORDER_DEFAULT );
 +
 +//! applies Canny edge detector and produces the edge map.
 +CV_EXPORTS_W void Canny( InputArray image, OutputArray edges,
 +                         double threshold1, double threshold2,
 +                         int apertureSize=3, bool L2gradient=false );
 +
 +//! computes minimum eigen value of 2x2 derivative covariation matrix at each pixel - the cornerness criteria
 +CV_EXPORTS_W void cornerMinEigenVal( InputArray src, OutputArray dst,
 +                                   int blockSize, int ksize=3,
 +                                   int borderType=BORDER_DEFAULT );
 +
 +//! computes Harris cornerness criteria at each image pixel
 +CV_EXPORTS_W void cornerHarris( InputArray src, OutputArray dst, int blockSize,
 +                                int ksize, double k,
 +                                int borderType=BORDER_DEFAULT );
 +
 +// low-level function for computing eigenvalues and eigenvectors of 2x2 matrices
 +CV_EXPORTS void eigen2x2( const float* a, float* e, int n );
 +
 +//! computes both eigenvalues and the eigenvectors of 2x2 derivative covariation matrix  at each pixel. The output is stored as 6-channel matrix.
 +CV_EXPORTS_W void cornerEigenValsAndVecs( InputArray src, OutputArray dst,
 +                                          int blockSize, int ksize,
 +                                          int borderType=BORDER_DEFAULT );
 +
 +//! computes another complex cornerness criteria at each pixel
 +CV_EXPORTS_W void preCornerDetect( InputArray src, OutputArray dst, int ksize,
 +                                   int borderType=BORDER_DEFAULT );
 +
 +//! adjusts the corner locations with sub-pixel accuracy to maximize the certain cornerness criteria
 +CV_EXPORTS_W void cornerSubPix( InputArray image, InputOutputArray corners,
 +                                Size winSize, Size zeroZone,
 +                                TermCriteria criteria );
 +
 +//! finds the strong enough corners where the cornerMinEigenVal() or cornerHarris() report the local maxima
 +CV_EXPORTS_W void goodFeaturesToTrack( InputArray image, OutputArray corners,
 +                                     int maxCorners, double qualityLevel, double minDistance,
 +                                     InputArray mask=noArray(), int blockSize=3,
 +                                     bool useHarrisDetector=false, double k=0.04 );
 +
 +//! finds lines in the black-n-white image using the standard or pyramid Hough transform
 +CV_EXPORTS_W void HoughLines( InputArray image, OutputArray lines,
 +                              double rho, double theta, int threshold,
 +                              double srn=0, double stn=0 );
 +
 +//! finds line segments in the black-n-white image using probabalistic Hough transform
 +CV_EXPORTS_W void HoughLinesP( InputArray image, OutputArray lines,
 +                               double rho, double theta, int threshold,
 +                               double minLineLength=0, double maxLineGap=0 );
 +
 +//! finds circles in the grayscale image using 2+1 gradient Hough transform
 +CV_EXPORTS_W void HoughCircles( InputArray image, OutputArray circles,
 +                               int method, double dp, double minDist,
 +                               double param1=100, double param2=100,
 +                               int minRadius=0, int maxRadius=0 );
 +
 +enum
 +{
 +    GHT_POSITION = 0,
 +    GHT_SCALE = 1,
 +    GHT_ROTATION = 2
 +};
 +
 +//! finds arbitrary template in the grayscale image using Generalized Hough Transform
 +//! Ballard, D.H. (1981). Generalizing the Hough transform to detect arbitrary shapes. Pattern Recognition 13 (2): 111-122.
 +//! Guil, N., González-Linares, J.M. and Zapata, E.L. (1999). Bidimensional shape detection using an invariant approach. Pattern Recognition 32 (6): 1025-1038.
 +class CV_EXPORTS GeneralizedHough : public Algorithm
 +{
 +public:
 +    static Ptr<GeneralizedHough> create(int method);
 +
 +    virtual ~GeneralizedHough();
 +
 +    //! set template to search
 +    void setTemplate(InputArray templ, int cannyThreshold = 100, Point templCenter = Point(-1, -1));
 +    void setTemplate(InputArray edges, InputArray dx, InputArray dy, Point templCenter = Point(-1, -1));
 +
 +    //! find template on image
 +    void detect(InputArray image, OutputArray positions, OutputArray votes = cv::noArray(), int cannyThreshold = 100);
 +    void detect(InputArray edges, InputArray dx, InputArray dy, OutputArray positions, OutputArray votes = cv::noArray());
 +
 +    void release();
 +
 +protected:
 +    virtual void setTemplateImpl(const Mat& edges, const Mat& dx, const Mat& dy, Point templCenter) = 0;
 +    virtual void detectImpl(const Mat& edges, const Mat& dx, const Mat& dy, OutputArray positions, OutputArray votes) = 0;
 +    virtual void releaseImpl() = 0;
 +
 +private:
 +    Mat edges_, dx_, dy_;
 +};
 +
 +//! erodes the image (applies the local minimum operator)
 +CV_EXPORTS_W void erode( InputArray src, OutputArray dst, InputArray 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)
 +CV_EXPORTS_W void dilate( InputArray src, OutputArray dst, InputArray 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_W void morphologyEx( InputArray src, OutputArray dst,
 +                                int op, InputArray kernel,
 +                                Point anchor=Point(-1,-1), int iterations=1,
 +                                int borderType=BORDER_CONSTANT,
 +                                const Scalar& borderValue=morphologyDefaultBorderValue() );
 +
 +//! interpolation algorithm
 +enum
 +{
 +    INTER_NEAREST=CV_INTER_NN, //!< nearest neighbor interpolation
 +    INTER_LINEAR=CV_INTER_LINEAR, //!< bilinear interpolation
 +    INTER_CUBIC=CV_INTER_CUBIC, //!< bicubic interpolation
 +    INTER_AREA=CV_INTER_AREA, //!< area-based (or super) interpolation
 +    INTER_LANCZOS4=CV_INTER_LANCZOS4, //!< Lanczos interpolation over 8x8 neighborhood
 +    INTER_MAX=7,
 +    WARP_INVERSE_MAP=CV_WARP_INVERSE_MAP
 +};
 +
 +//! resizes the image
 +CV_EXPORTS_W void resize( InputArray src, OutputArray dst,
 +                          Size dsize, double fx=0, double fy=0,
 +                          int interpolation=INTER_LINEAR );
 +
 +//! warps the image using affine transformation
 +CV_EXPORTS_W void warpAffine( InputArray src, OutputArray dst,
 +                              InputArray M, Size dsize,
 +                              int flags=INTER_LINEAR,
 +                              int borderMode=BORDER_CONSTANT,
 +                              const Scalar& borderValue=Scalar());
 +
 +//! warps the image using perspective transformation
 +CV_EXPORTS_W void warpPerspective( InputArray src, OutputArray dst,
 +                                   InputArray M, Size dsize,
 +                                   int flags=INTER_LINEAR,
 +                                   int borderMode=BORDER_CONSTANT,
 +                                   const Scalar& borderValue=Scalar());
 +
 +enum
 +{
 +    INTER_BITS=5, INTER_BITS2=INTER_BITS*2,
 +    INTER_TAB_SIZE=(1<<INTER_BITS),
 +    INTER_TAB_SIZE2=INTER_TAB_SIZE*INTER_TAB_SIZE
 +};
 +
 +//! warps the image using the precomputed maps. The maps are stored in either floating-point or integer fixed-point format
 +CV_EXPORTS_W void remap( InputArray src, OutputArray dst,
 +                         InputArray map1, InputArray map2,
 +                         int interpolation, int borderMode=BORDER_CONSTANT,
 +                         const Scalar& borderValue=Scalar());
 +
 +//! converts maps for remap from floating-point to fixed-point format or backwards
 +CV_EXPORTS_W void convertMaps( InputArray map1, InputArray map2,
 +                               OutputArray dstmap1, OutputArray dstmap2,
 +                               int dstmap1type, bool nninterpolation=false );
 +
 +//! returns 2x3 affine transformation matrix for the planar rotation.
 +CV_EXPORTS_W Mat getRotationMatrix2D( Point2f center, double angle, double scale );
 +//! returns 3x3 perspective transformation for the corresponding 4 point pairs.
 +CV_EXPORTS Mat getPerspectiveTransform( const Point2f src[], const Point2f dst[] );
 +//! returns 2x3 affine transformation for the corresponding 3 point pairs.
 +CV_EXPORTS Mat getAffineTransform( const Point2f src[], const Point2f dst[] );
 +//! computes 2x3 affine transformation matrix that is inverse to the specified 2x3 affine transformation.
 +CV_EXPORTS_W void invertAffineTransform( InputArray M, OutputArray iM );
 +
 +CV_EXPORTS_W Mat getPerspectiveTransform( InputArray src, InputArray dst );
 +CV_EXPORTS_W Mat getAffineTransform( InputArray src, InputArray dst );
 +
 +//! extracts rectangle from the image at sub-pixel location
 +CV_EXPORTS_W void getRectSubPix( InputArray image, Size patchSize,
 +                                 Point2f center, OutputArray patch, int patchType=-1 );
 +
 +//! computes the integral image
 +CV_EXPORTS_W void integral( InputArray src, OutputArray sum, int sdepth=-1 );
 +
 +//! computes the integral image and integral for the squared image
 +CV_EXPORTS_AS(integral2) void integral( InputArray src, OutputArray sum,
 +                                        OutputArray sqsum, int sdepth=-1 );
 +//! computes the integral image, integral for the squared image and the tilted integral image
 +CV_EXPORTS_AS(integral3) void integral( InputArray src, OutputArray sum,
 +                                        OutputArray sqsum, OutputArray tilted,
 +                                        int sdepth=-1 );
 +
 +//! adds image to the accumulator (dst += src). Unlike cv::add, dst and src can have different types.
 +CV_EXPORTS_W void accumulate( InputArray src, InputOutputArray dst,
 +                              InputArray mask=noArray() );
 +//! adds squared src image to the accumulator (dst += src*src).
 +CV_EXPORTS_W void accumulateSquare( InputArray src, InputOutputArray dst,
 +                                    InputArray mask=noArray() );
 +//! adds product of the 2 images to the accumulator (dst += src1*src2).
 +CV_EXPORTS_W void accumulateProduct( InputArray src1, InputArray src2,
 +                                     InputOutputArray dst, InputArray mask=noArray() );
 +//! updates the running average (dst = dst*(1-alpha) + src*alpha)
 +CV_EXPORTS_W void accumulateWeighted( InputArray src, InputOutputArray dst,
 +                                      double alpha, InputArray mask=noArray() );
 +
 +//! computes PSNR image/video quality metric
 +CV_EXPORTS_W double PSNR(InputArray src1, InputArray src2);
 +
 +CV_EXPORTS_W Point2d phaseCorrelate(InputArray src1, InputArray src2,
 +                                    InputArray window = noArray(), CV_OUT double* response=0);
 +CV_EXPORTS_W void createHanningWindow(OutputArray dst, Size winSize, int type);
 +
 +//! type of the threshold operation
 +enum { THRESH_BINARY=CV_THRESH_BINARY, THRESH_BINARY_INV=CV_THRESH_BINARY_INV,
 +       THRESH_TRUNC=CV_THRESH_TRUNC, THRESH_TOZERO=CV_THRESH_TOZERO,
 +       THRESH_TOZERO_INV=CV_THRESH_TOZERO_INV, THRESH_MASK=CV_THRESH_MASK,
 +       THRESH_OTSU=CV_THRESH_OTSU };
 +
 +//! applies fixed threshold to the image
 +CV_EXPORTS_W double threshold( InputArray src, OutputArray dst,
 +                               double thresh, double maxval, int type );
 +
 +//! adaptive threshold algorithm
 +enum { ADAPTIVE_THRESH_MEAN_C=0, ADAPTIVE_THRESH_GAUSSIAN_C=1 };
 +
 +//! applies variable (adaptive) threshold to the image
 +CV_EXPORTS_W void adaptiveThreshold( InputArray src, OutputArray dst,
 +                                     double maxValue, int adaptiveMethod,
 +                                     int thresholdType, int blockSize, double C );
 +
 +//! smooths and downsamples the image
 +CV_EXPORTS_W void pyrDown( InputArray src, OutputArray dst,
 +                           const Size& dstsize=Size(), int borderType=BORDER_DEFAULT );
 +//! upsamples and smoothes the image
 +CV_EXPORTS_W void pyrUp( InputArray src, OutputArray dst,
 +                         const Size& dstsize=Size(), int borderType=BORDER_DEFAULT );
 +
 +//! builds the gaussian pyramid using pyrDown() as a basic operation
 +CV_EXPORTS void buildPyramid( InputArray src, OutputArrayOfArrays dst,
 +                              int maxlevel, int borderType=BORDER_DEFAULT );
 +
 +//! corrects lens distortion for the given camera matrix and distortion coefficients
 +CV_EXPORTS_W void undistort( InputArray src, OutputArray dst,
 +                             InputArray cameraMatrix,
 +                             InputArray distCoeffs,
 +                             InputArray newCameraMatrix=noArray() );
 +
 +//! initializes maps for cv::remap() to correct lens distortion and optionally rectify the image
 +CV_EXPORTS_W void initUndistortRectifyMap( InputArray cameraMatrix, InputArray distCoeffs,
 +                           InputArray R, InputArray newCameraMatrix,
 +                           Size size, int m1type, OutputArray map1, OutputArray map2 );
 +
 +enum
 +{
 +    PROJ_SPHERICAL_ORTHO = 0,
 +    PROJ_SPHERICAL_EQRECT = 1
 +};
 +
 +//! initializes maps for cv::remap() for wide-angle
 +CV_EXPORTS_W float initWideAngleProjMap( InputArray cameraMatrix, InputArray distCoeffs,
 +                                         Size imageSize, int destImageWidth,
 +                                         int m1type, OutputArray map1, OutputArray map2,
 +                                         int projType=PROJ_SPHERICAL_EQRECT, double alpha=0);
 +
 +//! returns the default new camera matrix (by default it is the same as cameraMatrix unless centerPricipalPoint=true)
 +CV_EXPORTS_W Mat getDefaultNewCameraMatrix( InputArray cameraMatrix, Size imgsize=Size(),
 +                                            bool centerPrincipalPoint=false );
 +
 +//! returns points' coordinates after lens distortion correction
 +CV_EXPORTS_W void undistortPoints( InputArray src, OutputArray dst,
 +                                   InputArray cameraMatrix, InputArray distCoeffs,
 +                                   InputArray R=noArray(), InputArray P=noArray());
 +
 +template<> CV_EXPORTS void Ptr<CvHistogram>::delete_obj();
 +
 +//! computes the joint dense histogram for a set of images.
 +CV_EXPORTS void calcHist( const Mat* images, int nimages,
 +                          const int* channels, InputArray mask,
 +                          OutputArray hist, int dims, const int* histSize,
 +                          const float** ranges, bool uniform=true, bool accumulate=false );
 +
 +//! computes the joint sparse histogram for a set of images.
 +CV_EXPORTS void calcHist( const Mat* images, int nimages,
 +                          const int* channels, InputArray mask,
 +                          SparseMat& hist, int dims,
 +                          const int* histSize, const float** ranges,
 +                          bool uniform=true, bool accumulate=false );
 +
 +CV_EXPORTS_W void calcHist( InputArrayOfArrays images,
 +                            const std::vector<int>& channels,
 +                            InputArray mask, OutputArray hist,
 +                            const std::vector<int>& histSize,
 +                            const std::vector<float>& ranges,
 +                            bool accumulate=false );
 +
 +//! computes back projection for the set of images
 +CV_EXPORTS void calcBackProject( const Mat* images, int nimages,
 +                                 const int* channels, InputArray hist,
 +                                 OutputArray backProject, const float** ranges,
 +                                 double scale=1, bool uniform=true );
 +
 +//! computes back projection for the set of images
 +CV_EXPORTS void calcBackProject( const Mat* images, int nimages,
 +                                 const int* channels, const SparseMat& hist,
 +                                 OutputArray backProject, const float** ranges,
 +                                 double scale=1, bool uniform=true );
 +
 +CV_EXPORTS_W void calcBackProject( InputArrayOfArrays images, const std::vector<int>& channels,
 +                                   InputArray hist, OutputArray dst,
 +                                   const std::vector<float>& ranges,
 +                                   double scale );
 +
 +/*CV_EXPORTS void calcBackProjectPatch( const Mat* images, int nimages, const int* channels,
 +                                      InputArray hist, OutputArray dst, Size patchSize,
 +                                      int method, double factor=1 );
 +
 +CV_EXPORTS_W void calcBackProjectPatch( InputArrayOfArrays images, const std::vector<int>& channels,
 +                                        InputArray hist, OutputArray dst, Size patchSize,
 +                                        int method, double factor=1 );*/
 +
 +//! compares two histograms stored in dense arrays
 +CV_EXPORTS_W double compareHist( InputArray H1, InputArray H2, int method );
 +
 +//! compares two histograms stored in sparse arrays
 +CV_EXPORTS double compareHist( const SparseMat& H1, const SparseMat& H2, int method );
 +
 +//! normalizes the grayscale image brightness and contrast by normalizing its histogram
 +CV_EXPORTS_W void equalizeHist( InputArray src, OutputArray dst );
 +
++class CV_EXPORTS CLAHE : public Algorithm
++{
++public:
++    virtual void apply(InputArray src, OutputArray dst) = 0;
++
++    virtual void setClipLimit(double clipLimit) = 0;
++    virtual double getClipLimit() const = 0;
++
++    virtual void setTilesGridSize(Size tileGridSize) = 0;
++    virtual Size getTilesGridSize() const = 0;
++
++    virtual void collectGarbage() = 0;
++};
++CV_EXPORTS Ptr<CLAHE> createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8));
++
 +CV_EXPORTS float EMD( InputArray signature1, InputArray signature2,
 +                      int distType, InputArray cost=noArray(),
 +                      float* lowerBound=0, OutputArray flow=noArray() );
 +
 +//! segments the image using watershed algorithm
 +CV_EXPORTS_W void watershed( InputArray image, InputOutputArray markers );
 +
 +//! filters image using meanshift algorithm
 +CV_EXPORTS_W void pyrMeanShiftFiltering( InputArray src, OutputArray dst,
 +                                         double sp, double sr, int maxLevel=1,
 +                                         TermCriteria termcrit=TermCriteria(
 +                                            TermCriteria::MAX_ITER+TermCriteria::EPS,5,1) );
 +
 +//! class of the pixel in GrabCut algorithm
 +enum
 +{
 +    GC_BGD    = 0,  //!< background
 +    GC_FGD    = 1,  //!< foreground
 +    GC_PR_BGD = 2,  //!< most probably background
 +    GC_PR_FGD = 3   //!< most probably foreground
 +};
 +
 +//! GrabCut algorithm flags
 +enum
 +{
 +    GC_INIT_WITH_RECT  = 0,
 +    GC_INIT_WITH_MASK  = 1,
 +    GC_EVAL            = 2
 +};
 +
 +//! segments the image using GrabCut algorithm
 +CV_EXPORTS_W void grabCut( InputArray img, InputOutputArray mask, Rect rect,
 +                           InputOutputArray bgdModel, InputOutputArray fgdModel,
 +                           int iterCount, int mode = GC_EVAL );
 +
 +enum
 +{
 +    DIST_LABEL_CCOMP = 0,
 +    DIST_LABEL_PIXEL = 1
 +};
 +
 +//! builds the discrete Voronoi diagram
 +CV_EXPORTS_AS(distanceTransformWithLabels) void distanceTransform( InputArray src, OutputArray dst,
 +                                     OutputArray labels, int distanceType, int maskSize,
 +                                     int labelType=DIST_LABEL_CCOMP );
 +
 +//! computes the distance transform map
 +CV_EXPORTS_W void distanceTransform( InputArray src, OutputArray dst,
 +                                     int distanceType, int maskSize );
 +
 +enum { FLOODFILL_FIXED_RANGE = 1 << 16, FLOODFILL_MASK_ONLY = 1 << 17 };
 +
 +//! fills the semi-uniform image region starting from the specified seed point
 +CV_EXPORTS int floodFill( InputOutputArray image,
 +                          Point seedPoint, Scalar newVal, CV_OUT Rect* rect=0,
 +                          Scalar loDiff=Scalar(), Scalar upDiff=Scalar(),
 +                          int flags=4 );
 +
 +//! fills the semi-uniform image region and/or the mask starting from the specified seed point
 +CV_EXPORTS_W int floodFill( InputOutputArray image, InputOutputArray mask,
 +                            Point seedPoint, Scalar newVal, CV_OUT Rect* rect=0,
 +                            Scalar loDiff=Scalar(), Scalar upDiff=Scalar(),
 +                            int flags=4 );
 +
 +
 +enum
 +{
 +    COLOR_BGR2BGRA    =0,
 +    COLOR_RGB2RGBA    =COLOR_BGR2BGRA,
 +
 +    COLOR_BGRA2BGR    =1,
 +    COLOR_RGBA2RGB    =COLOR_BGRA2BGR,
 +
 +    COLOR_BGR2RGBA    =2,
 +    COLOR_RGB2BGRA    =COLOR_BGR2RGBA,
 +
 +    COLOR_RGBA2BGR    =3,
 +    COLOR_BGRA2RGB    =COLOR_RGBA2BGR,
 +
 +    COLOR_BGR2RGB     =4,
 +    COLOR_RGB2BGR     =COLOR_BGR2RGB,
 +
 +    COLOR_BGRA2RGBA   =5,
 +    COLOR_RGBA2BGRA   =COLOR_BGRA2RGBA,
 +
 +    COLOR_BGR2GRAY    =6,
 +    COLOR_RGB2GRAY    =7,
 +    COLOR_GRAY2BGR    =8,
 +    COLOR_GRAY2RGB    =COLOR_GRAY2BGR,
 +    COLOR_GRAY2BGRA   =9,
 +    COLOR_GRAY2RGBA   =COLOR_GRAY2BGRA,
 +    COLOR_BGRA2GRAY   =10,
 +    COLOR_RGBA2GRAY   =11,
 +
 +    COLOR_BGR2BGR565  =12,
 +    COLOR_RGB2BGR565  =13,
 +    COLOR_BGR5652BGR  =14,
 +    COLOR_BGR5652RGB  =15,
 +    COLOR_BGRA2BGR565 =16,
 +    COLOR_RGBA2BGR565 =17,
 +    COLOR_BGR5652BGRA =18,
 +    COLOR_BGR5652RGBA =19,
 +
 +    COLOR_GRAY2BGR565 =20,
 +    COLOR_BGR5652GRAY =21,
 +
 +    COLOR_BGR2BGR555  =22,
 +    COLOR_RGB2BGR555  =23,
 +    COLOR_BGR5552BGR  =24,
 +    COLOR_BGR5552RGB  =25,
 +    COLOR_BGRA2BGR555 =26,
 +    COLOR_RGBA2BGR555 =27,
 +    COLOR_BGR5552BGRA =28,
 +    COLOR_BGR5552RGBA =29,
 +
 +    COLOR_GRAY2BGR555 =30,
 +    COLOR_BGR5552GRAY =31,
 +
 +    COLOR_BGR2XYZ     =32,
 +    COLOR_RGB2XYZ     =33,
 +    COLOR_XYZ2BGR     =34,
 +    COLOR_XYZ2RGB     =35,
 +
 +    COLOR_BGR2YCrCb   =36,
 +    COLOR_RGB2YCrCb   =37,
 +    COLOR_YCrCb2BGR   =38,
 +    COLOR_YCrCb2RGB   =39,
 +
 +    COLOR_BGR2HSV     =40,
 +    COLOR_RGB2HSV     =41,
 +
 +    COLOR_BGR2Lab     =44,
 +    COLOR_RGB2Lab     =45,
 +
 +    COLOR_BayerBG2BGR =46,
 +    COLOR_BayerGB2BGR =47,
 +    COLOR_BayerRG2BGR =48,
 +    COLOR_BayerGR2BGR =49,
 +
 +    COLOR_BayerBG2RGB =COLOR_BayerRG2BGR,
 +    COLOR_BayerGB2RGB =COLOR_BayerGR2BGR,
 +    COLOR_BayerRG2RGB =COLOR_BayerBG2BGR,
 +    COLOR_BayerGR2RGB =COLOR_BayerGB2BGR,
 +
 +    COLOR_BGR2Luv     =50,
 +    COLOR_RGB2Luv     =51,
 +    COLOR_BGR2HLS     =52,
 +    COLOR_RGB2HLS     =53,
 +
 +    COLOR_HSV2BGR     =54,
 +    COLOR_HSV2RGB     =55,
 +
 +    COLOR_Lab2BGR     =56,
 +    COLOR_Lab2RGB     =57,
 +    COLOR_Luv2BGR     =58,
 +    COLOR_Luv2RGB     =59,
 +    COLOR_HLS2BGR     =60,
 +    COLOR_HLS2RGB     =61,
 +
 +    COLOR_BayerBG2BGR_VNG =62,
 +    COLOR_BayerGB2BGR_VNG =63,
 +    COLOR_BayerRG2BGR_VNG =64,
 +    COLOR_BayerGR2BGR_VNG =65,
 +
 +    COLOR_BayerBG2RGB_VNG =COLOR_BayerRG2BGR_VNG,
 +    COLOR_BayerGB2RGB_VNG =COLOR_BayerGR2BGR_VNG,
 +    COLOR_BayerRG2RGB_VNG =COLOR_BayerBG2BGR_VNG,
 +    COLOR_BayerGR2RGB_VNG =COLOR_BayerGB2BGR_VNG,
 +
 +    COLOR_BGR2HSV_FULL = 66,
 +    COLOR_RGB2HSV_FULL = 67,
 +    COLOR_BGR2HLS_FULL = 68,
 +    COLOR_RGB2HLS_FULL = 69,
 +
 +    COLOR_HSV2BGR_FULL = 70,
 +    COLOR_HSV2RGB_FULL = 71,
 +    COLOR_HLS2BGR_FULL = 72,
 +    COLOR_HLS2RGB_FULL = 73,
 +
 +    COLOR_LBGR2Lab     = 74,
 +    COLOR_LRGB2Lab     = 75,
 +    COLOR_LBGR2Luv     = 76,
 +    COLOR_LRGB2Luv     = 77,
 +
 +    COLOR_Lab2LBGR     = 78,
 +    COLOR_Lab2LRGB     = 79,
 +    COLOR_Luv2LBGR     = 80,
 +    COLOR_Luv2LRGB     = 81,
 +
 +    COLOR_BGR2YUV      = 82,
 +    COLOR_RGB2YUV      = 83,
 +    COLOR_YUV2BGR      = 84,
 +    COLOR_YUV2RGB      = 85,
 +
 +    COLOR_BayerBG2GRAY = 86,
 +    COLOR_BayerGB2GRAY = 87,
 +    COLOR_BayerRG2GRAY = 88,
 +    COLOR_BayerGR2GRAY = 89,
 +
 +    //YUV 4:2:0 formats family
 +    COLOR_YUV2RGB_NV12 = 90,
 +    COLOR_YUV2BGR_NV12 = 91,
 +    COLOR_YUV2RGB_NV21 = 92,
 +    COLOR_YUV2BGR_NV21 = 93,
 +    COLOR_YUV420sp2RGB = COLOR_YUV2RGB_NV21,
 +    COLOR_YUV420sp2BGR = COLOR_YUV2BGR_NV21,
 +
 +    COLOR_YUV2RGBA_NV12 = 94,
 +    COLOR_YUV2BGRA_NV12 = 95,
 +    COLOR_YUV2RGBA_NV21 = 96,
 +    COLOR_YUV2BGRA_NV21 = 97,
 +    COLOR_YUV420sp2RGBA = COLOR_YUV2RGBA_NV21,
 +    COLOR_YUV420sp2BGRA = COLOR_YUV2BGRA_NV21,
 +
 +    COLOR_YUV2RGB_YV12 = 98,
 +    COLOR_YUV2BGR_YV12 = 99,
 +    COLOR_YUV2RGB_IYUV = 100,
 +    COLOR_YUV2BGR_IYUV = 101,
 +    COLOR_YUV2RGB_I420 = COLOR_YUV2RGB_IYUV,
 +    COLOR_YUV2BGR_I420 = COLOR_YUV2BGR_IYUV,
 +    COLOR_YUV420p2RGB = COLOR_YUV2RGB_YV12,
 +    COLOR_YUV420p2BGR = COLOR_YUV2BGR_YV12,
 +
 +    COLOR_YUV2RGBA_YV12 = 102,
 +    COLOR_YUV2BGRA_YV12 = 103,
 +    COLOR_YUV2RGBA_IYUV = 104,
 +    COLOR_YUV2BGRA_IYUV = 105,
 +    COLOR_YUV2RGBA_I420 = COLOR_YUV2RGBA_IYUV,
 +    COLOR_YUV2BGRA_I420 = COLOR_YUV2BGRA_IYUV,
 +    COLOR_YUV420p2RGBA = COLOR_YUV2RGBA_YV12,
 +    COLOR_YUV420p2BGRA = COLOR_YUV2BGRA_YV12,
 +
 +    COLOR_YUV2GRAY_420 = 106,
 +    COLOR_YUV2GRAY_NV21 = COLOR_YUV2GRAY_420,
 +    COLOR_YUV2GRAY_NV12 = COLOR_YUV2GRAY_420,
 +    COLOR_YUV2GRAY_YV12 = COLOR_YUV2GRAY_420,
 +    COLOR_YUV2GRAY_IYUV = COLOR_YUV2GRAY_420,
 +    COLOR_YUV2GRAY_I420 = COLOR_YUV2GRAY_420,
 +    COLOR_YUV420sp2GRAY = COLOR_YUV2GRAY_420,
 +    COLOR_YUV420p2GRAY = COLOR_YUV2GRAY_420,
 +
 +    //YUV 4:2:2 formats family
 +    COLOR_YUV2RGB_UYVY = 107,
 +    COLOR_YUV2BGR_UYVY = 108,
 +    //COLOR_YUV2RGB_VYUY = 109,
 +    //COLOR_YUV2BGR_VYUY = 110,
 +    COLOR_YUV2RGB_Y422 = COLOR_YUV2RGB_UYVY,
 +    COLOR_YUV2BGR_Y422 = COLOR_YUV2BGR_UYVY,
 +    COLOR_YUV2RGB_UYNV = COLOR_YUV2RGB_UYVY,
 +    COLOR_YUV2BGR_UYNV = COLOR_YUV2BGR_UYVY,
 +
 +    COLOR_YUV2RGBA_UYVY = 111,
 +    COLOR_YUV2BGRA_UYVY = 112,
 +    //COLOR_YUV2RGBA_VYUY = 113,
 +    //COLOR_YUV2BGRA_VYUY = 114,
 +    COLOR_YUV2RGBA_Y422 = COLOR_YUV2RGBA_UYVY,
 +    COLOR_YUV2BGRA_Y422 = COLOR_YUV2BGRA_UYVY,
 +    COLOR_YUV2RGBA_UYNV = COLOR_YUV2RGBA_UYVY,
 +    COLOR_YUV2BGRA_UYNV = COLOR_YUV2BGRA_UYVY,
 +
 +    COLOR_YUV2RGB_YUY2 = 115,
 +    COLOR_YUV2BGR_YUY2 = 116,
 +    COLOR_YUV2RGB_YVYU = 117,
 +    COLOR_YUV2BGR_YVYU = 118,
 +    COLOR_YUV2RGB_YUYV = COLOR_YUV2RGB_YUY2,
 +    COLOR_YUV2BGR_YUYV = COLOR_YUV2BGR_YUY2,
 +    COLOR_YUV2RGB_YUNV = COLOR_YUV2RGB_YUY2,
 +    COLOR_YUV2BGR_YUNV = COLOR_YUV2BGR_YUY2,
 +
 +    COLOR_YUV2RGBA_YUY2 = 119,
 +    COLOR_YUV2BGRA_YUY2 = 120,
 +    COLOR_YUV2RGBA_YVYU = 121,
 +    COLOR_YUV2BGRA_YVYU = 122,
 +    COLOR_YUV2RGBA_YUYV = COLOR_YUV2RGBA_YUY2,
 +    COLOR_YUV2BGRA_YUYV = COLOR_YUV2BGRA_YUY2,
 +    COLOR_YUV2RGBA_YUNV = COLOR_YUV2RGBA_YUY2,
 +    COLOR_YUV2BGRA_YUNV = COLOR_YUV2BGRA_YUY2,
 +
 +    COLOR_YUV2GRAY_UYVY = 123,
 +    COLOR_YUV2GRAY_YUY2 = 124,
 +    //COLOR_YUV2GRAY_VYUY = COLOR_YUV2GRAY_UYVY,
 +    COLOR_YUV2GRAY_Y422 = COLOR_YUV2GRAY_UYVY,
 +    COLOR_YUV2GRAY_UYNV = COLOR_YUV2GRAY_UYVY,
 +    COLOR_YUV2GRAY_YVYU = COLOR_YUV2GRAY_YUY2,
 +    COLOR_YUV2GRAY_YUYV = COLOR_YUV2GRAY_YUY2,
 +    COLOR_YUV2GRAY_YUNV = COLOR_YUV2GRAY_YUY2,
 +
 +    // alpha premultiplication
 +    COLOR_RGBA2mRGBA = 125,
 +    COLOR_mRGBA2RGBA = 126,
 +
 +    COLOR_RGB2YUV_I420 = 127,
 +    COLOR_BGR2YUV_I420 = 128,
 +    COLOR_RGB2YUV_IYUV = COLOR_RGB2YUV_I420,
 +    COLOR_BGR2YUV_IYUV = COLOR_BGR2YUV_I420,
 +
 +    COLOR_RGBA2YUV_I420 = 129,
 +    COLOR_BGRA2YUV_I420 = 130,
 +    COLOR_RGBA2YUV_IYUV = COLOR_RGBA2YUV_I420,
 +    COLOR_BGRA2YUV_IYUV = COLOR_BGRA2YUV_I420,
 +    COLOR_RGB2YUV_YV12  = 131,
 +    COLOR_BGR2YUV_YV12  = 132,
 +    COLOR_RGBA2YUV_YV12 = 133,
 +    COLOR_BGRA2YUV_YV12 = 134,
 +
 +    // Edge-Aware Demosaicing
 +    COLOR_BayerBG2BGR_EA = 135,
 +    COLOR_BayerGB2BGR_EA = 136,
 +    COLOR_BayerRG2BGR_EA = 137,
 +    COLOR_BayerGR2BGR_EA = 138,
 +
 +    COLOR_BayerBG2RGB_EA = COLOR_BayerRG2BGR_EA,
 +    COLOR_BayerGB2RGB_EA = COLOR_BayerGR2BGR_EA,
 +    COLOR_BayerRG2RGB_EA = COLOR_BayerBG2BGR_EA,
 +    COLOR_BayerGR2RGB_EA = COLOR_BayerGB2BGR_EA,
 +
 +    COLOR_COLORCVT_MAX  = 139
 +};
 +
 +
 +//! converts image from one color space to another
 +CV_EXPORTS_W void cvtColor( InputArray src, OutputArray dst, int code, int dstCn=0 );
 +
 +//! raster image moments
 +class CV_EXPORTS_W_MAP Moments
 +{
 +public:
 +    //! the default constructor
 +    Moments();
 +    //! the full constructor
 +    Moments(double m00, double m10, double m01, double m20, double m11,
 +            double m02, double m30, double m21, double m12, double m03 );
 +    //! the conversion from CvMoments
 +    Moments( const CvMoments& moments );
 +    //! the conversion to CvMoments
 +    operator CvMoments() const;
 +
 +    //! spatial moments
 +    CV_PROP_RW double  m00, m10, m01, m20, m11, m02, m30, m21, m12, m03;
 +    //! central moments
 +    CV_PROP_RW double  mu20, mu11, mu02, mu30, mu21, mu12, mu03;
 +    //! central normalized moments
 +    CV_PROP_RW double  nu20, nu11, nu02, nu30, nu21, nu12, nu03;
 +};
 +
 +//! computes moments of the rasterized shape or a vector of points
 +CV_EXPORTS_W Moments moments( InputArray array, bool binaryImage=false );
 +
 +//! computes 7 Hu invariants from the moments
 +CV_EXPORTS void HuMoments( const Moments& moments, double hu[7] );
 +CV_EXPORTS_W void HuMoments( const Moments& m, OutputArray hu );
 +
 +//! type of the template matching operation
 +enum { TM_SQDIFF=0, TM_SQDIFF_NORMED=1, TM_CCORR=2, TM_CCORR_NORMED=3, TM_CCOEFF=4, TM_CCOEFF_NORMED=5 };
 +
 +//! computes the proximity map for the raster template and the image where the template is searched for
 +CV_EXPORTS_W void matchTemplate( InputArray image, InputArray templ,
 +                                 OutputArray result, int method );
 +
 +enum { CC_STAT_LEFT=0, CC_STAT_TOP=1, CC_STAT_WIDTH=2, CC_STAT_HEIGHT=3, CC_STAT_AREA=4, CC_STAT_MAX = 5};
 +
 +// computes the connected components labeled image of boolean image ``image``
 +// with 4 or 8 way connectivity - returns N, the total
 +// number of labels [0, N-1] where 0 represents the background label.
 +// ltype specifies the output label image type, an important
 +// consideration based on the total number of labels or
 +// alternatively the total number of pixels in the source image.
 +CV_EXPORTS_W int connectedComponents(InputArray image, OutputArray labels,
 +                                     int connectivity = 8, int ltype=CV_32S);
 +CV_EXPORTS_W int connectedComponentsWithStats(InputArray image, OutputArray labels,
 +                                              OutputArray stats, OutputArray centroids,
 +                                              int connectivity = 8, int ltype=CV_32S);
 +
 +//! mode of the contour retrieval algorithm
 +enum
 +{
 +    RETR_EXTERNAL=CV_RETR_EXTERNAL, //!< retrieve only the most external (top-level) contours
 +    RETR_LIST=CV_RETR_LIST, //!< retrieve all the contours without any hierarchical information
 +    RETR_CCOMP=CV_RETR_CCOMP, //!< retrieve the connected components (that can possibly be nested)
 +    RETR_TREE=CV_RETR_TREE, //!< retrieve all the contours and the whole hierarchy
 +    RETR_FLOODFILL=CV_RETR_FLOODFILL
 +};
 +
 +//! the contour approximation algorithm
 +enum
 +{
 +    CHAIN_APPROX_NONE=CV_CHAIN_APPROX_NONE,
 +    CHAIN_APPROX_SIMPLE=CV_CHAIN_APPROX_SIMPLE,
 +    CHAIN_APPROX_TC89_L1=CV_CHAIN_APPROX_TC89_L1,
 +    CHAIN_APPROX_TC89_KCOS=CV_CHAIN_APPROX_TC89_KCOS
 +};
 +
 +//! retrieves contours and the hierarchical information from black-n-white image.
 +CV_EXPORTS_W void findContours( InputOutputArray image, OutputArrayOfArrays contours,
 +                              OutputArray hierarchy, int mode,
 +                              int method, Point offset=Point());
 +
 +//! retrieves contours from black-n-white image.
 +CV_EXPORTS void findContours( InputOutputArray image, OutputArrayOfArrays contours,
 +                              int mode, int method, Point offset=Point());
 +
 +//! approximates contour or a curve using Douglas-Peucker algorithm
 +CV_EXPORTS_W void approxPolyDP( InputArray curve,
 +                                OutputArray approxCurve,
 +                                double epsilon, bool closed );
 +
 +//! computes the contour perimeter (closed=true) or a curve length
 +CV_EXPORTS_W double arcLength( InputArray curve, bool closed );
 +//! computes the bounding rectangle for a contour
 +CV_EXPORTS_W Rect boundingRect( InputArray points );
 +//! computes the contour area
 +CV_EXPORTS_W double contourArea( InputArray contour, bool oriented=false );
 +//! computes the minimal rotated rectangle for a set of points
 +CV_EXPORTS_W RotatedRect minAreaRect( InputArray points );
 +//! computes the minimal enclosing circle for a set of points
 +CV_EXPORTS_W void minEnclosingCircle( InputArray points,
 +                                      CV_OUT Point2f& center, CV_OUT float& radius );
 +//! matches two contours using one of the available algorithms
 +CV_EXPORTS_W double matchShapes( InputArray contour1, InputArray contour2,
 +                                 int method, double parameter );
 +//! computes convex hull for a set of 2D points.
 +CV_EXPORTS_W void convexHull( InputArray points, OutputArray hull,
 +                              bool clockwise=false, bool returnPoints=true );
 +//! computes the contour convexity defects
 +CV_EXPORTS_W void convexityDefects( InputArray contour, InputArray convexhull, OutputArray convexityDefects );
 +
 +//! returns true if the contour is convex. Does not support contours with self-intersection
 +CV_EXPORTS_W bool isContourConvex( InputArray contour );
 +
 +//! finds intersection of two convex polygons
 +CV_EXPORTS_W float intersectConvexConvex( InputArray _p1, InputArray _p2,
 +                                          OutputArray _p12, bool handleNested=true );
 +
 +//! fits ellipse to the set of 2D points
 +CV_EXPORTS_W RotatedRect fitEllipse( InputArray points );
 +
 +//! fits line to the set of 2D points using M-estimator algorithm
 +CV_EXPORTS_W void fitLine( InputArray points, OutputArray line, int distType,
 +                           double param, double reps, double aeps );
 +//! checks if the point is inside the contour. Optionally computes the signed distance from the point to the contour boundary
 +CV_EXPORTS_W double pointPolygonTest( InputArray contour, Point2f pt, bool measureDist );
 +
 +
 +class CV_EXPORTS_W Subdiv2D
 +{
 +public:
 +    enum
 +    {
 +        PTLOC_ERROR = -2,
 +        PTLOC_OUTSIDE_RECT = -1,
 +        PTLOC_INSIDE = 0,
 +        PTLOC_VERTEX = 1,
 +        PTLOC_ON_EDGE = 2
 +    };
 +
 +    enum
 +    {
 +        NEXT_AROUND_ORG   = 0x00,
 +        NEXT_AROUND_DST   = 0x22,
 +        PREV_AROUND_ORG   = 0x11,
 +        PREV_AROUND_DST   = 0x33,
 +        NEXT_AROUND_LEFT  = 0x13,
 +        NEXT_AROUND_RIGHT = 0x31,
 +        PREV_AROUND_LEFT  = 0x20,
 +        PREV_AROUND_RIGHT = 0x02
 +    };
 +
 +    CV_WRAP Subdiv2D();
 +    CV_WRAP Subdiv2D(Rect rect);
 +    CV_WRAP void initDelaunay(Rect rect);
 +
 +    CV_WRAP int insert(Point2f pt);
 +    CV_WRAP void insert(const std::vector<Point2f>& ptvec);
 +    CV_WRAP int locate(Point2f pt, CV_OUT int& edge, CV_OUT int& vertex);
 +
 +    CV_WRAP int findNearest(Point2f pt, CV_OUT Point2f* nearestPt=0);
 +    CV_WRAP void getEdgeList(CV_OUT std::vector<Vec4f>& edgeList) const;
 +    CV_WRAP void getTriangleList(CV_OUT std::vector<Vec6f>& triangleList) const;
 +    CV_WRAP void getVoronoiFacetList(const std::vector<int>& idx, CV_OUT std::vector<std::vector<Point2f> >& facetList,
 +                                     CV_OUT std::vector<Point2f>& facetCenters);
 +
 +    CV_WRAP Point2f getVertex(int vertex, CV_OUT int* firstEdge=0) const;
 +
 +    CV_WRAP int getEdge( int edge, int nextEdgeType ) const;
 +    CV_WRAP int nextEdge(int edge) const;
 +    CV_WRAP int rotateEdge(int edge, int rotate) const;
 +    CV_WRAP int symEdge(int edge) const;
 +    CV_WRAP int edgeOrg(int edge, CV_OUT Point2f* orgpt=0) const;
 +    CV_WRAP int edgeDst(int edge, CV_OUT Point2f* dstpt=0) const;
 +
 +protected:
 +    int newEdge();
 +    void deleteEdge(int edge);
 +    int newPoint(Point2f pt, bool isvirtual, int firstEdge=0);
 +    void deletePoint(int vtx);
 +    void setEdgePoints( int edge, int orgPt, int dstPt );
 +    void splice( int edgeA, int edgeB );
 +    int connectEdges( int edgeA, int edgeB );
 +    void swapEdges( int edge );
 +    int isRightOf(Point2f pt, int edge) const;
 +    void calcVoronoi();
 +    void clearVoronoi();
 +    void checkSubdiv() const;
 +
 +    struct CV_EXPORTS Vertex
 +    {
 +        Vertex();
 +        Vertex(Point2f pt, bool _isvirtual, int _firstEdge=0);
 +        bool isvirtual() const;
 +        bool isfree() const;
 +        int firstEdge;
 +        int type;
 +        Point2f pt;
 +    };
 +    struct CV_EXPORTS QuadEdge
 +    {
 +        QuadEdge();
 +        QuadEdge(int edgeidx);
 +        bool isfree() const;
 +        int next[4];
 +        int pt[4];
 +    };
 +
 +    std::vector<Vertex> vtx;
 +    std::vector<QuadEdge> qedges;
 +    int freeQEdge;
 +    int freePoint;
 +    bool validGeometry;
 +
 +    int recentEdge;
 +    Point2f topLeft;
 +    Point2f bottomRight;
 +};
 +
 +// main function for all demosaicing procceses
 +CV_EXPORTS_W void demosaicing(InputArray _src, OutputArray _dst, int code, int dcn = 0);
 +
 +}
 +
 +#endif /* __cplusplus */
 +
 +#endif
 +
 +/* End of file. */
  //
  //M*/
  
 -#ifndef __OPENCV_IMGPROC_HPP__
 -#define __OPENCV_IMGPROC_HPP__
 -
 -#include "opencv2/core/core.hpp"
 -#include "opencv2/imgproc/types_c.h"
 -
 -#ifdef __cplusplus
 -
 -/*! \namespace cv
 - Namespace where all the C++ OpenCV functionality resides
 - */
 -namespace cv
 -{
 -
 -//! various border interpolation methods
 -enum { BORDER_REPLICATE=IPL_BORDER_REPLICATE, BORDER_CONSTANT=IPL_BORDER_CONSTANT,
 -       BORDER_REFLECT=IPL_BORDER_REFLECT, BORDER_WRAP=IPL_BORDER_WRAP,
 -       BORDER_REFLECT_101=IPL_BORDER_REFLECT_101, BORDER_REFLECT101=BORDER_REFLECT_101,
 -       BORDER_TRANSPARENT=IPL_BORDER_TRANSPARENT,
 -       BORDER_DEFAULT=BORDER_REFLECT_101, BORDER_ISOLATED=16 };
 -
 -//! 1D interpolation function: returns coordinate of the "donor" pixel for the specified location p.
 -CV_EXPORTS_W int borderInterpolate( int p, int len, int borderType );
 -
 -/*!
 - 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.
 -
 - Several functions in OpenCV return Ptr<BaseRowFilter> for the specific types of filters,
 - and those pointers can be used directly or within cv::FilterEngine.
 -*/
 -class CV_EXPORTS BaseRowFilter
 -{
 -public:
 -    //! the default constructor
 -    BaseRowFilter();
 -    //! the destructor
 -    virtual ~BaseRowFilter();
 -    //! the filtering operator. Must be overrided in the derived classes. The horizontal border interpolation is done outside of the class.
 -    virtual void operator()(const uchar* src, uchar* dst,
 -                            int width, int cn) = 0;
 -    int ksize, anchor;
 -};
 -
 -
 -/*!
 - 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.
 -
 - Several functions in OpenCV return Ptr<BaseColumnFilter> for the specific types of filters,
 - and those pointers can be used directly or within cv::FilterEngine.
 -
 - Unlike cv::BaseRowFilter, cv::BaseColumnFilter may have some context information,
 - i.e. box filter keeps the sliding sum of elements. To reset the state BaseColumnFilter::reset()
 - must be called (e.g. the method is called by cv::FilterEngine)
 - */
 -class CV_EXPORTS BaseColumnFilter
 -{
 -public:
 -    //! the default constructor
 -    BaseColumnFilter();
 -    //! the destructor
 -    virtual ~BaseColumnFilter();
 -    //! the filtering operator. Must be overrided in the derived classes. The vertical border interpolation is done outside of the class.
 -    virtual void operator()(const uchar** src, uchar* dst, int dststep,
 -                            int dstcount, int width) = 0;
 -    //! resets the internal buffers, if any
 -    virtual void reset();
 -    int ksize, anchor;
 -};
 -
 -/*!
 - The Base Class for Non-Separable 2D Filters.
 -
 - This is the base class for linear or non-linear 2D filters.
 -
 - Several functions in OpenCV return Ptr<BaseFilter> for the specific types of filters,
 - and those pointers can be used directly or within cv::FilterEngine.
 -
 - Similar to cv::BaseColumnFilter, the class may have some context information,
 - that should be reset using BaseFilter::reset() method before processing the new array.
 -*/
 -class CV_EXPORTS BaseFilter
 -{
 -public:
 -    //! the default constructor
 -    BaseFilter();
 -    //! the destructor
 -    virtual ~BaseFilter();
 -    //! the filtering operator. The horizontal and the vertical border interpolation is done outside of the class.
 -    virtual void operator()(const uchar** src, uchar* dst, int dststep,
 -                            int dstcount, int width, int cn) = 0;
 -    //! resets the internal buffers, if any
 -    virtual void reset();
 -    Size ksize;
 -    Point anchor;
 -};
 -
 -/*!
 - The Main Class for Image Filtering.
 -
 - The class can be used to apply an arbitrary filtering operation to an image.
 - It contains all the necessary intermediate buffers, it computes extrapolated values
 - of the "virtual" pixels outside of the image etc.
 - Pointers to the initialized cv::FilterEngine instances
 - are returned by various OpenCV functions, such as cv::createSeparableLinearFilter(),
 - cv::createLinearFilter(), cv::createGaussianFilter(), cv::createDerivFilter(),
 - cv::createBoxFilter() and cv::createMorphologyFilter().
 -
 - Using the class you can process large images by parts and build complex pipelines
 - that include filtering as some of the stages. If all you need is to apply some pre-defined
 - filtering operation, you may use cv::filter2D(), cv::erode(), cv::dilate() etc.
 - functions that create FilterEngine internally.
 -
 - Here is the example on how to use the class to implement Laplacian operator, which is the sum of
 - second-order derivatives. More complex variant for different types is implemented in cv::Laplacian().
 -
 - \code
 - void laplace_f(const Mat& src, Mat& dst)
 - {
 -     CV_Assert( src.type() == CV_32F );
 -     // make sure the destination array has the proper size and type
 -     dst.create(src.size(), src.type());
 -
 -     // get the derivative and smooth kernels for d2I/dx2.
 -     // for d2I/dy2 we could use the same kernels, just swapped
 -     Mat kd, ks;
 -     getSobelKernels( kd, ks, 2, 0, ksize, false, ktype );
 -
 -     // let's process 10 source rows at once
 -     int DELTA = std::min(10, src.rows);
 -     Ptr<FilterEngine> Fxx = createSeparableLinearFilter(src.type(),
 -     dst.type(), kd, ks, Point(-1,-1), 0, borderType, borderType, Scalar() );
 -     Ptr<FilterEngine> Fyy = createSeparableLinearFilter(src.type(),
 -     dst.type(), ks, kd, Point(-1,-1), 0, borderType, borderType, Scalar() );
 -
 -     int y = Fxx->start(src), dsty = 0, dy = 0;
 -     Fyy->start(src);
 -     const uchar* sptr = src.data + y*src.step;
 -
 -     // allocate the buffers for the spatial image derivatives;
 -     // the buffers need to have more than DELTA rows, because at the
 -     // last iteration the output may take max(kd.rows-1,ks.rows-1)
 -     // rows more than the input.
 -     Mat Ixx( DELTA + kd.rows - 1, src.cols, dst.type() );
 -     Mat Iyy( DELTA + kd.rows - 1, src.cols, dst.type() );
 -
 -     // inside the loop we always pass DELTA rows to the filter
 -     // (note that the "proceed" method takes care of possibe overflow, since
 -     // it was given the actual image height in the "start" method)
 -     // on output we can get:
 -     //  * < DELTA rows (the initial buffer accumulation stage)
 -     //  * = DELTA rows (settled state in the middle)
 -     //  * > DELTA rows (then the input image is over, but we generate
 -     //                  "virtual" rows using the border mode and filter them)
 -     // this variable number of output rows is dy.
 -     // dsty is the current output row.
 -     // sptr is the pointer to the first input row in the portion to process
 -     for( ; dsty < dst.rows; sptr += DELTA*src.step, dsty += dy )
 -     {
 -         Fxx->proceed( sptr, (int)src.step, DELTA, Ixx.data, (int)Ixx.step );
 -         dy = Fyy->proceed( sptr, (int)src.step, DELTA, d2y.data, (int)Iyy.step );
 -         if( dy > 0 )
 -         {
 -             Mat dstripe = dst.rowRange(dsty, dsty + dy);
 -             add(Ixx.rowRange(0, dy), Iyy.rowRange(0, dy), dstripe);
 -         }
 -     }
 - }
 - \endcode
 -*/
 -class CV_EXPORTS FilterEngine
 -{
 -public:
 -    //! the default constructor
 -    FilterEngine();
 -    //! the full constructor. Either _filter2D or both _rowFilter and _columnFilter must be non-empty.
 -    FilterEngine(const Ptr<BaseFilter>& _filter2D,
 -                 const Ptr<BaseRowFilter>& _rowFilter,
 -                 const Ptr<BaseColumnFilter>& _columnFilter,
 -                 int srcType, int dstType, int bufType,
 -                 int _rowBorderType=BORDER_REPLICATE,
 -                 int _columnBorderType=-1,
 -                 const Scalar& _borderValue=Scalar());
 -    //! the destructor
 -    virtual ~FilterEngine();
 -    //! reinitializes the engine. The previously assigned filters are released.
 -    void init(const Ptr<BaseFilter>& _filter2D,
 -              const Ptr<BaseRowFilter>& _rowFilter,
 -              const Ptr<BaseColumnFilter>& _columnFilter,
 -              int srcType, int dstType, int bufType,
 -              int _rowBorderType=BORDER_REPLICATE, int _columnBorderType=-1,
 -              const Scalar& _borderValue=Scalar());
 -    //! starts filtering of the specified ROI of an image of size wholeSize.
 -    virtual int start(Size wholeSize, Rect roi, int maxBufRows=-1);
 -    //! starts filtering of the specified ROI of the specified image.
 -    virtual int start(const Mat& src, const Rect& srcRoi=Rect(0,0,-1,-1),
 -                      bool isolated=false, int maxBufRows=-1);
 -    //! processes the next srcCount rows of the image.
 -    virtual int proceed(const uchar* src, int srcStep, int srcCount,
 -                        uchar* dst, int dstStep);
 -    //! applies filter to the specified ROI of the image. if srcRoi=(0,0,-1,-1), the whole image is filtered.
 -    virtual void apply( const Mat& src, Mat& dst,
 -                        const Rect& srcRoi=Rect(0,0,-1,-1),
 -                        Point dstOfs=Point(0,0),
 -                        bool isolated=false);
 -    //! returns true if the filter is separable
 -    bool isSeparable() const { return (const BaseFilter*)filter2D == 0; }
 -    //! returns the number
 -    int remainingInputRows() const;
 -    int remainingOutputRows() const;
 -
 -    int srcType, dstType, bufType;
 -    Size ksize;
 -    Point anchor;
 -    int maxWidth;
 -    Size wholeSize;
 -    Rect roi;
 -    int dx1, dx2;
 -    int rowBorderType, columnBorderType;
 -    vector<int> borderTab;
 -    int borderElemSize;
 -    vector<uchar> ringBuf;
 -    vector<uchar> srcRow;
 -    vector<uchar> constBorderValue;
 -    vector<uchar> constBorderRow;
 -    int bufStep, startY, startY0, endY, rowCount, dstY;
 -    vector<uchar*> rows;
 -
 -    Ptr<BaseFilter> filter2D;
 -    Ptr<BaseRowFilter> rowFilter;
 -    Ptr<BaseColumnFilter> columnFilter;
 -};
 -
 -//! type of the kernel
 -enum { KERNEL_GENERAL=0, KERNEL_SYMMETRICAL=1, KERNEL_ASYMMETRICAL=2,
 -       KERNEL_SMOOTH=4, KERNEL_INTEGER=8 };
 -
 -//! returns type (one of KERNEL_*) of 1D or 2D kernel specified by its coefficients.
 -CV_EXPORTS int getKernelType(InputArray kernel, Point anchor);
 -
 -//! returns the primitive row filter with the specified kernel
 -CV_EXPORTS Ptr<BaseRowFilter> getLinearRowFilter(int srcType, int bufType,
 -                                            InputArray kernel, int anchor,
 -                                            int symmetryType);
 -
 -//! returns the primitive column filter with the specified kernel
 -CV_EXPORTS Ptr<BaseColumnFilter> getLinearColumnFilter(int bufType, int dstType,
 -                                            InputArray kernel, int anchor,
 -                                            int symmetryType, double delta=0,
 -                                            int bits=0);
 -
 -//! returns 2D filter with the specified kernel
 -CV_EXPORTS Ptr<BaseFilter> getLinearFilter(int srcType, int dstType,
 -                                           InputArray kernel,
 -                                           Point anchor=Point(-1,-1),
 -                                           double delta=0, int bits=0);
 -
 -//! returns the separable linear filter engine
 -CV_EXPORTS Ptr<FilterEngine> createSeparableLinearFilter(int srcType, int dstType,
 -                          InputArray rowKernel, InputArray columnKernel,
 -                          Point anchor=Point(-1,-1), double delta=0,
 -                          int rowBorderType=BORDER_DEFAULT,
 -                          int columnBorderType=-1,
 -                          const Scalar& borderValue=Scalar());
 -
 -//! returns the non-separable linear filter engine
 -CV_EXPORTS Ptr<FilterEngine> createLinearFilter(int srcType, int dstType,
 -                 InputArray kernel, Point _anchor=Point(-1,-1),
 -                 double delta=0, int rowBorderType=BORDER_DEFAULT,
 -                 int columnBorderType=-1, const Scalar& borderValue=Scalar());
 -
 -//! returns the Gaussian kernel with the specified parameters
 -CV_EXPORTS_W Mat getGaussianKernel( int ksize, double sigma, int ktype=CV_64F );
 -
 -//! returns the Gaussian filter engine
 -CV_EXPORTS Ptr<FilterEngine> createGaussianFilter( int type, Size ksize,
 -                                    double sigma1, double sigma2=0,
 -                                    int borderType=BORDER_DEFAULT);
 -//! initializes kernels of the generalized Sobel operator
 -CV_EXPORTS_W void getDerivKernels( OutputArray kx, OutputArray ky,
 -                                   int dx, int dy, int ksize,
 -                                   bool normalize=false, int ktype=CV_32F );
 -//! returns filter engine for the generalized Sobel operator
 -CV_EXPORTS Ptr<FilterEngine> createDerivFilter( int srcType, int dstType,
 -                                        int dx, int dy, int ksize,
 -                                        int borderType=BORDER_DEFAULT );
 -//! returns horizontal 1D box filter
 -CV_EXPORTS Ptr<BaseRowFilter> getRowSumFilter(int srcType, int sumType,
 -                                              int ksize, int anchor=-1);
 -//! returns vertical 1D box filter
 -CV_EXPORTS Ptr<BaseColumnFilter> getColumnSumFilter( int sumType, int dstType,
 -                                                     int ksize, int anchor=-1,
 -                                                     double scale=1);
 -//! returns box filter engine
 -CV_EXPORTS Ptr<FilterEngine> createBoxFilter( int srcType, int dstType, Size ksize,
 -                                              Point anchor=Point(-1,-1),
 -                                              bool normalize=true,
 -                                              int borderType=BORDER_DEFAULT);
 -
 -//! returns the Gabor kernel with the specified parameters
 -CV_EXPORTS_W Mat getGaborKernel( Size ksize, double sigma, double theta, double lambd,
 -                                 double gamma, double psi=CV_PI*0.5, int ktype=CV_64F );
 -
 -//! type of morphological operation
 -enum { MORPH_ERODE=CV_MOP_ERODE, MORPH_DILATE=CV_MOP_DILATE,
 -       MORPH_OPEN=CV_MOP_OPEN, MORPH_CLOSE=CV_MOP_CLOSE,
 -       MORPH_GRADIENT=CV_MOP_GRADIENT, MORPH_TOPHAT=CV_MOP_TOPHAT,
 -       MORPH_BLACKHAT=CV_MOP_BLACKHAT };
 -
 -//! returns horizontal 1D morphological filter
 -CV_EXPORTS Ptr<BaseRowFilter> getMorphologyRowFilter(int op, int type, int ksize, int anchor=-1);
 -//! returns vertical 1D morphological filter
 -CV_EXPORTS Ptr<BaseColumnFilter> getMorphologyColumnFilter(int op, int type, int ksize, int anchor=-1);
 -//! returns 2D morphological filter
 -CV_EXPORTS Ptr<BaseFilter> getMorphologyFilter(int op, int type, InputArray kernel,
 -                                               Point anchor=Point(-1,-1));
 -
 -//! returns "magic" border value for erosion and dilation. It is automatically transformed to Scalar::all(-DBL_MAX) for dilation.
 -static inline Scalar morphologyDefaultBorderValue() { return Scalar::all(DBL_MAX); }
 -
 -//! returns morphological filter engine. Only MORPH_ERODE and MORPH_DILATE are supported.
 -CV_EXPORTS Ptr<FilterEngine> createMorphologyFilter(int op, int type, InputArray kernel,
 -                    Point anchor=Point(-1,-1), int rowBorderType=BORDER_CONSTANT,
 -                    int columnBorderType=-1,
 -                    const Scalar& borderValue=morphologyDefaultBorderValue());
 -
 -//! shape of the structuring element
 -enum { MORPH_RECT=0, MORPH_CROSS=1, MORPH_ELLIPSE=2 };
 -//! returns structuring element of the specified shape and size
 -CV_EXPORTS_W Mat getStructuringElement(int shape, Size ksize, Point anchor=Point(-1,-1));
 -
 -template<> CV_EXPORTS void Ptr<IplConvKernel>::delete_obj();
 -
 -//! copies 2D array to a larger destination array with extrapolation of the outer part of src using the specified border mode
 -CV_EXPORTS_W void copyMakeBorder( InputArray src, OutputArray dst,
 -                                int top, int bottom, int left, int right,
 -                                int borderType, const Scalar& value=Scalar() );
 -
 -//! smooths the image using median filter.
 -CV_EXPORTS_W void medianBlur( InputArray src, OutputArray dst, int ksize );
 -//! smooths the image using Gaussian filter.
 -CV_EXPORTS_W void GaussianBlur( InputArray src,
 -                                               OutputArray dst, Size ksize,
 -                                               double sigmaX, double sigmaY=0,
 -                                               int borderType=BORDER_DEFAULT );
 -//! smooths the image using bilateral filter
 -CV_EXPORTS_W void bilateralFilter( InputArray src, OutputArray dst, int d,
 -                                   double sigmaColor, double sigmaSpace,
 -                                   int borderType=BORDER_DEFAULT );
 -//! smooths the image using the box filter. Each pixel is processed in O(1) time
 -CV_EXPORTS_W void boxFilter( InputArray src, OutputArray dst, int ddepth,
 -                             Size ksize, Point anchor=Point(-1,-1),
 -                             bool normalize=true,
 -                             int borderType=BORDER_DEFAULT );
 -//! a synonym for normalized box filter
 -CV_EXPORTS_W void blur( InputArray src, OutputArray dst,
 -                        Size ksize, Point anchor=Point(-1,-1),
 -                        int borderType=BORDER_DEFAULT );
 -
 -//! applies non-separable 2D linear filter to the image
 -CV_EXPORTS_W void filter2D( InputArray src, OutputArray dst, int ddepth,
 -                            InputArray kernel, Point anchor=Point(-1,-1),
 -                            double delta=0, int borderType=BORDER_DEFAULT );
 -
 -//! applies separable 2D linear filter to the image
 -CV_EXPORTS_W void sepFilter2D( InputArray src, OutputArray dst, int ddepth,
 -                               InputArray kernelX, InputArray kernelY,
 -                               Point anchor=Point(-1,-1),
 -                               double delta=0, int borderType=BORDER_DEFAULT );
 -
 -//! applies generalized Sobel operator to the image
 -CV_EXPORTS_W void Sobel( InputArray src, OutputArray dst, int ddepth,
 -                         int dx, int dy, int ksize=3,
 -                         double scale=1, double delta=0,
 -                         int borderType=BORDER_DEFAULT );
 -
 -//! applies the vertical or horizontal Scharr operator to the image
 -CV_EXPORTS_W void Scharr( InputArray src, OutputArray dst, int ddepth,
 -                          int dx, int dy, double scale=1, double delta=0,
 -                          int borderType=BORDER_DEFAULT );
 -
 -//! applies Laplacian operator to the image
 -CV_EXPORTS_W void Laplacian( InputArray src, OutputArray dst, int ddepth,
 -                             int ksize=1, double scale=1, double delta=0,
 -                             int borderType=BORDER_DEFAULT );
 -
 -//! applies Canny edge detector and produces the edge map.
 -CV_EXPORTS_W void Canny( InputArray image, OutputArray edges,
 -                         double threshold1, double threshold2,
 -                         int apertureSize=3, bool L2gradient=false );
 -
 -//! computes minimum eigen value of 2x2 derivative covariation matrix at each pixel - the cornerness criteria
 -CV_EXPORTS_W void cornerMinEigenVal( InputArray src, OutputArray dst,
 -                                   int blockSize, int ksize=3,
 -                                   int borderType=BORDER_DEFAULT );
 -
 -//! computes Harris cornerness criteria at each image pixel
 -CV_EXPORTS_W void cornerHarris( InputArray src, OutputArray dst, int blockSize,
 -                                int ksize, double k,
 -                                int borderType=BORDER_DEFAULT );
 -
 -// low-level function for computing eigenvalues and eigenvectors of 2x2 matrices
 -CV_EXPORTS void eigen2x2( const float* a, float* e, int n );
 -
 -//! computes both eigenvalues and the eigenvectors of 2x2 derivative covariation matrix  at each pixel. The output is stored as 6-channel matrix.
 -CV_EXPORTS_W void cornerEigenValsAndVecs( InputArray src, OutputArray dst,
 -                                          int blockSize, int ksize,
 -                                          int borderType=BORDER_DEFAULT );
 -
 -//! computes another complex cornerness criteria at each pixel
 -CV_EXPORTS_W void preCornerDetect( InputArray src, OutputArray dst, int ksize,
 -                                   int borderType=BORDER_DEFAULT );
 -
 -//! adjusts the corner locations with sub-pixel accuracy to maximize the certain cornerness criteria
 -CV_EXPORTS_W void cornerSubPix( InputArray image, InputOutputArray corners,
 -                                Size winSize, Size zeroZone,
 -                                TermCriteria criteria );
 -
 -//! finds the strong enough corners where the cornerMinEigenVal() or cornerHarris() report the local maxima
 -CV_EXPORTS_W void goodFeaturesToTrack( InputArray image, OutputArray corners,
 -                                     int maxCorners, double qualityLevel, double minDistance,
 -                                     InputArray mask=noArray(), int blockSize=3,
 -                                     bool useHarrisDetector=false, double k=0.04 );
 -
 -//! finds lines in the black-n-white image using the standard or pyramid Hough transform
 -CV_EXPORTS_W void HoughLines( InputArray image, OutputArray lines,
 -                              double rho, double theta, int threshold,
 -                              double srn=0, double stn=0 );
 -
 -//! finds line segments in the black-n-white image using probabalistic Hough transform
 -CV_EXPORTS_W void HoughLinesP( InputArray image, OutputArray lines,
 -                               double rho, double theta, int threshold,
 -                               double minLineLength=0, double maxLineGap=0 );
 -
 -//! finds circles in the grayscale image using 2+1 gradient Hough transform
 -CV_EXPORTS_W void HoughCircles( InputArray image, OutputArray circles,
 -                               int method, double dp, double minDist,
 -                               double param1=100, double param2=100,
 -                               int minRadius=0, int maxRadius=0 );
 -
 -enum
 -{
 -    GHT_POSITION = 0,
 -    GHT_SCALE = 1,
 -    GHT_ROTATION = 2
 -};
 -
 -//! finds arbitrary template in the grayscale image using Generalized Hough Transform
 -//! Ballard, D.H. (1981). Generalizing the Hough transform to detect arbitrary shapes. Pattern Recognition 13 (2): 111-122.
 -//! Guil, N., González-Linares, J.M. and Zapata, E.L. (1999). Bidimensional shape detection using an invariant approach. Pattern Recognition 32 (6): 1025-1038.
 -class CV_EXPORTS GeneralizedHough : public Algorithm
 -{
 -public:
 -    static Ptr<GeneralizedHough> create(int method);
 -
 -    virtual ~GeneralizedHough();
 -
 -    //! set template to search
 -    void setTemplate(InputArray templ, int cannyThreshold = 100, Point templCenter = Point(-1, -1));
 -    void setTemplate(InputArray edges, InputArray dx, InputArray dy, Point templCenter = Point(-1, -1));
 -
 -    //! find template on image
 -    void detect(InputArray image, OutputArray positions, OutputArray votes = cv::noArray(), int cannyThreshold = 100);
 -    void detect(InputArray edges, InputArray dx, InputArray dy, OutputArray positions, OutputArray votes = cv::noArray());
 -
 -    void release();
 -
 -protected:
 -    virtual void setTemplateImpl(const Mat& edges, const Mat& dx, const Mat& dy, Point templCenter) = 0;
 -    virtual void detectImpl(const Mat& edges, const Mat& dx, const Mat& dy, OutputArray positions, OutputArray votes) = 0;
 -    virtual void releaseImpl() = 0;
 -
 -private:
 -    Mat edges_, dx_, dy_;
 -};
 -
 -//! erodes the image (applies the local minimum operator)
 -CV_EXPORTS_W void erode( InputArray src, OutputArray dst, InputArray 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)
 -CV_EXPORTS_W void dilate( InputArray src, OutputArray dst, InputArray 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_W void morphologyEx( InputArray src, OutputArray dst,
 -                                int op, InputArray kernel,
 -                                Point anchor=Point(-1,-1), int iterations=1,
 -                                int borderType=BORDER_CONSTANT,
 -                                const Scalar& borderValue=morphologyDefaultBorderValue() );
 -
 -//! interpolation algorithm
 -enum
 -{
 -    INTER_NEAREST=CV_INTER_NN, //!< nearest neighbor interpolation
 -    INTER_LINEAR=CV_INTER_LINEAR, //!< bilinear interpolation
 -    INTER_CUBIC=CV_INTER_CUBIC, //!< bicubic interpolation
 -    INTER_AREA=CV_INTER_AREA, //!< area-based (or super) interpolation
 -    INTER_LANCZOS4=CV_INTER_LANCZOS4, //!< Lanczos interpolation over 8x8 neighborhood
 -    INTER_MAX=7,
 -    WARP_INVERSE_MAP=CV_WARP_INVERSE_MAP
 -};
 -
 -//! resizes the image
 -CV_EXPORTS_W void resize( InputArray src, OutputArray dst,
 -                          Size dsize, double fx=0, double fy=0,
 -                          int interpolation=INTER_LINEAR );
 -
 -//! warps the image using affine transformation
 -CV_EXPORTS_W void warpAffine( InputArray src, OutputArray dst,
 -                              InputArray M, Size dsize,
 -                              int flags=INTER_LINEAR,
 -                              int borderMode=BORDER_CONSTANT,
 -                              const Scalar& borderValue=Scalar());
 -
 -//! warps the image using perspective transformation
 -CV_EXPORTS_W void warpPerspective( InputArray src, OutputArray dst,
 -                                   InputArray M, Size dsize,
 -                                   int flags=INTER_LINEAR,
 -                                   int borderMode=BORDER_CONSTANT,
 -                                   const Scalar& borderValue=Scalar());
 -
 -enum
 -{
 -    INTER_BITS=5, INTER_BITS2=INTER_BITS*2,
 -    INTER_TAB_SIZE=(1<<INTER_BITS),
 -    INTER_TAB_SIZE2=INTER_TAB_SIZE*INTER_TAB_SIZE
 -};
 -
 -//! warps the image using the precomputed maps. The maps are stored in either floating-point or integer fixed-point format
 -CV_EXPORTS_W void remap( InputArray src, OutputArray dst,
 -                         InputArray map1, InputArray map2,
 -                         int interpolation, int borderMode=BORDER_CONSTANT,
 -                         const Scalar& borderValue=Scalar());
 -
 -//! converts maps for remap from floating-point to fixed-point format or backwards
 -CV_EXPORTS_W void convertMaps( InputArray map1, InputArray map2,
 -                               OutputArray dstmap1, OutputArray dstmap2,
 -                               int dstmap1type, bool nninterpolation=false );
 -
 -//! returns 2x3 affine transformation matrix for the planar rotation.
 -CV_EXPORTS_W Mat getRotationMatrix2D( Point2f center, double angle, double scale );
 -//! returns 3x3 perspective transformation for the corresponding 4 point pairs.
 -CV_EXPORTS Mat getPerspectiveTransform( const Point2f src[], const Point2f dst[] );
 -//! returns 2x3 affine transformation for the corresponding 3 point pairs.
 -CV_EXPORTS Mat getAffineTransform( const Point2f src[], const Point2f dst[] );
 -//! computes 2x3 affine transformation matrix that is inverse to the specified 2x3 affine transformation.
 -CV_EXPORTS_W void invertAffineTransform( InputArray M, OutputArray iM );
 -
 -CV_EXPORTS_W Mat getPerspectiveTransform( InputArray src, InputArray dst );
 -CV_EXPORTS_W Mat getAffineTransform( InputArray src, InputArray dst );
 -
 -//! extracts rectangle from the image at sub-pixel location
 -CV_EXPORTS_W void getRectSubPix( InputArray image, Size patchSize,
 -                                 Point2f center, OutputArray patch, int patchType=-1 );
 -
 -//! computes the integral image
 -CV_EXPORTS_W void integral( InputArray src, OutputArray sum, int sdepth=-1 );
 -
 -//! computes the integral image and integral for the squared image
 -CV_EXPORTS_AS(integral2) void integral( InputArray src, OutputArray sum,
 -                                        OutputArray sqsum, int sdepth=-1 );
 -//! computes the integral image, integral for the squared image and the tilted integral image
 -CV_EXPORTS_AS(integral3) void integral( InputArray src, OutputArray sum,
 -                                        OutputArray sqsum, OutputArray tilted,
 -                                        int sdepth=-1 );
 -
 -//! adds image to the accumulator (dst += src). Unlike cv::add, dst and src can have different types.
 -CV_EXPORTS_W void accumulate( InputArray src, InputOutputArray dst,
 -                              InputArray mask=noArray() );
 -//! adds squared src image to the accumulator (dst += src*src).
 -CV_EXPORTS_W void accumulateSquare( InputArray src, InputOutputArray dst,
 -                                    InputArray mask=noArray() );
 -//! adds product of the 2 images to the accumulator (dst += src1*src2).
 -CV_EXPORTS_W void accumulateProduct( InputArray src1, InputArray src2,
 -                                     InputOutputArray dst, InputArray mask=noArray() );
 -//! updates the running average (dst = dst*(1-alpha) + src*alpha)
 -CV_EXPORTS_W void accumulateWeighted( InputArray src, InputOutputArray dst,
 -                                      double alpha, InputArray mask=noArray() );
 -
 -//! computes PSNR image/video quality metric
 -CV_EXPORTS_W double PSNR(InputArray src1, InputArray src2);
 -
 -CV_EXPORTS_W Point2d phaseCorrelate(InputArray src1, InputArray src2,
 -                                  InputArray window = noArray());
 -CV_EXPORTS_W Point2d phaseCorrelateRes(InputArray src1, InputArray src2,
 -                                    InputArray window, CV_OUT double* response = 0);
 -CV_EXPORTS_W void createHanningWindow(OutputArray dst, Size winSize, int type);
 -
 -//! type of the threshold operation
 -enum { THRESH_BINARY=CV_THRESH_BINARY, THRESH_BINARY_INV=CV_THRESH_BINARY_INV,
 -       THRESH_TRUNC=CV_THRESH_TRUNC, THRESH_TOZERO=CV_THRESH_TOZERO,
 -       THRESH_TOZERO_INV=CV_THRESH_TOZERO_INV, THRESH_MASK=CV_THRESH_MASK,
 -       THRESH_OTSU=CV_THRESH_OTSU };
 -
 -//! applies fixed threshold to the image
 -CV_EXPORTS_W double threshold( InputArray src, OutputArray dst,
 -                               double thresh, double maxval, int type );
 -
 -//! adaptive threshold algorithm
 -enum { ADAPTIVE_THRESH_MEAN_C=0, ADAPTIVE_THRESH_GAUSSIAN_C=1 };
 -
 -//! applies variable (adaptive) threshold to the image
 -CV_EXPORTS_W void adaptiveThreshold( InputArray src, OutputArray dst,
 -                                     double maxValue, int adaptiveMethod,
 -                                     int thresholdType, int blockSize, double C );
 -
 -//! smooths and downsamples the image
 -CV_EXPORTS_W void pyrDown( InputArray src, OutputArray dst,
 -                           const Size& dstsize=Size(), int borderType=BORDER_DEFAULT );
 -//! upsamples and smoothes the image
 -CV_EXPORTS_W void pyrUp( InputArray src, OutputArray dst,
 -                         const Size& dstsize=Size(), int borderType=BORDER_DEFAULT );
 -
 -//! builds the gaussian pyramid using pyrDown() as a basic operation
 -CV_EXPORTS void buildPyramid( InputArray src, OutputArrayOfArrays dst,
 -                              int maxlevel, int borderType=BORDER_DEFAULT );
 -
 -//! corrects lens distortion for the given camera matrix and distortion coefficients
 -CV_EXPORTS_W void undistort( InputArray src, OutputArray dst,
 -                             InputArray cameraMatrix,
 -                             InputArray distCoeffs,
 -                             InputArray newCameraMatrix=noArray() );
 -
 -//! initializes maps for cv::remap() to correct lens distortion and optionally rectify the image
 -CV_EXPORTS_W void initUndistortRectifyMap( InputArray cameraMatrix, InputArray distCoeffs,
 -                           InputArray R, InputArray newCameraMatrix,
 -                           Size size, int m1type, OutputArray map1, OutputArray map2 );
 -
 -enum
 -{
 -    PROJ_SPHERICAL_ORTHO = 0,
 -    PROJ_SPHERICAL_EQRECT = 1
 -};
 -
 -//! initializes maps for cv::remap() for wide-angle
 -CV_EXPORTS_W float initWideAngleProjMap( InputArray cameraMatrix, InputArray distCoeffs,
 -                                         Size imageSize, int destImageWidth,
 -                                         int m1type, OutputArray map1, OutputArray map2,
 -                                         int projType=PROJ_SPHERICAL_EQRECT, double alpha=0);
 -
 -//! returns the default new camera matrix (by default it is the same as cameraMatrix unless centerPricipalPoint=true)
 -CV_EXPORTS_W Mat getDefaultNewCameraMatrix( InputArray cameraMatrix, Size imgsize=Size(),
 -                                            bool centerPrincipalPoint=false );
 -
 -//! returns points' coordinates after lens distortion correction
 -CV_EXPORTS_W void undistortPoints( InputArray src, OutputArray dst,
 -                                   InputArray cameraMatrix, InputArray distCoeffs,
 -                                   InputArray R=noArray(), InputArray P=noArray());
 -
 -template<> CV_EXPORTS void Ptr<CvHistogram>::delete_obj();
 -
 -//! computes the joint dense histogram for a set of images.
 -CV_EXPORTS void calcHist( const Mat* images, int nimages,
 -                          const int* channels, InputArray mask,
 -                          OutputArray hist, int dims, const int* histSize,
 -                          const float** ranges, bool uniform=true, bool accumulate=false );
 -
 -//! computes the joint sparse histogram for a set of images.
 -CV_EXPORTS void calcHist( const Mat* images, int nimages,
 -                          const int* channels, InputArray mask,
 -                          SparseMat& hist, int dims,
 -                          const int* histSize, const float** ranges,
 -                          bool uniform=true, bool accumulate=false );
 -
 -CV_EXPORTS_W void calcHist( InputArrayOfArrays images,
 -                            const vector<int>& channels,
 -                            InputArray mask, OutputArray hist,
 -                            const vector<int>& histSize,
 -                            const vector<float>& ranges,
 -                            bool accumulate=false );
 -
 -//! computes back projection for the set of images
 -CV_EXPORTS void calcBackProject( const Mat* images, int nimages,
 -                                 const int* channels, InputArray hist,
 -                                 OutputArray backProject, const float** ranges,
 -                                 double scale=1, bool uniform=true );
 -
 -//! computes back projection for the set of images
 -CV_EXPORTS void calcBackProject( const Mat* images, int nimages,
 -                                 const int* channels, const SparseMat& hist,
 -                                 OutputArray backProject, const float** ranges,
 -                                 double scale=1, bool uniform=true );
 -
 -CV_EXPORTS_W void calcBackProject( InputArrayOfArrays images, const vector<int>& channels,
 -                                   InputArray hist, OutputArray dst,
 -                                   const vector<float>& ranges,
 -                                   double scale );
 -
 -/*CV_EXPORTS void calcBackProjectPatch( const Mat* images, int nimages, const int* channels,
 -                                      InputArray hist, OutputArray dst, Size patchSize,
 -                                      int method, double factor=1 );
 -
 -CV_EXPORTS_W void calcBackProjectPatch( InputArrayOfArrays images, const vector<int>& channels,
 -                                        InputArray hist, OutputArray dst, Size patchSize,
 -                                        int method, double factor=1 );*/
 -
 -//! compares two histograms stored in dense arrays
 -CV_EXPORTS_W double compareHist( InputArray H1, InputArray H2, int method );
 -
 -//! compares two histograms stored in sparse arrays
 -CV_EXPORTS double compareHist( const SparseMat& H1, const SparseMat& H2, int method );
 -
 -//! normalizes the grayscale image brightness and contrast by normalizing its histogram
 -CV_EXPORTS_W void equalizeHist( InputArray src, OutputArray dst );
 -
 -class CV_EXPORTS CLAHE : public Algorithm
 -{
 -public:
 -    virtual void apply(InputArray src, OutputArray dst) = 0;
 -
 -    virtual void setClipLimit(double clipLimit) = 0;
 -    virtual double getClipLimit() const = 0;
 -
 -    virtual void setTilesGridSize(Size tileGridSize) = 0;
 -    virtual Size getTilesGridSize() const = 0;
 -
 -    virtual void collectGarbage() = 0;
 -};
 -CV_EXPORTS Ptr<CLAHE> createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8));
 -
 -CV_EXPORTS float EMD( InputArray signature1, InputArray signature2,
 -                      int distType, InputArray cost=noArray(),
 -                      float* lowerBound=0, OutputArray flow=noArray() );
 -
 -//! segments the image using watershed algorithm
 -CV_EXPORTS_W void watershed( InputArray image, InputOutputArray markers );
 -
 -//! filters image using meanshift algorithm
 -CV_EXPORTS_W void pyrMeanShiftFiltering( InputArray src, OutputArray dst,
 -                                         double sp, double sr, int maxLevel=1,
 -                                         TermCriteria termcrit=TermCriteria(
 -                                            TermCriteria::MAX_ITER+TermCriteria::EPS,5,1) );
 -
 -//! class of the pixel in GrabCut algorithm
 -enum
 -{
 -    GC_BGD    = 0,  //!< background
 -    GC_FGD    = 1,  //!< foreground
 -    GC_PR_BGD = 2,  //!< most probably background
 -    GC_PR_FGD = 3   //!< most probably foreground
 -};
 -
 -//! GrabCut algorithm flags
 -enum
 -{
 -    GC_INIT_WITH_RECT  = 0,
 -    GC_INIT_WITH_MASK  = 1,
 -    GC_EVAL            = 2
 -};
 -
 -//! segments the image using GrabCut algorithm
 -CV_EXPORTS_W void grabCut( InputArray img, InputOutputArray mask, Rect rect,
 -                           InputOutputArray bgdModel, InputOutputArray fgdModel,
 -                           int iterCount, int mode = GC_EVAL );
 -
 -enum
 -{
 -    DIST_LABEL_CCOMP = 0,
 -    DIST_LABEL_PIXEL = 1
 -};
 -
 -//! builds the discrete Voronoi diagram
 -CV_EXPORTS_AS(distanceTransformWithLabels) void distanceTransform( InputArray src, OutputArray dst,
 -                                     OutputArray labels, int distanceType, int maskSize,
 -                                     int labelType=DIST_LABEL_CCOMP );
 -
 -//! computes the distance transform map
 -CV_EXPORTS_W void distanceTransform( InputArray src, OutputArray dst,
 -                                     int distanceType, int maskSize );
 -
 -enum { FLOODFILL_FIXED_RANGE = 1 << 16, FLOODFILL_MASK_ONLY = 1 << 17 };
 -
 -//! fills the semi-uniform image region starting from the specified seed point
 -CV_EXPORTS int floodFill( InputOutputArray image,
 -                          Point seedPoint, Scalar newVal, CV_OUT Rect* rect=0,
 -                          Scalar loDiff=Scalar(), Scalar upDiff=Scalar(),
 -                          int flags=4 );
 -
 -//! fills the semi-uniform image region and/or the mask starting from the specified seed point
 -CV_EXPORTS_W int floodFill( InputOutputArray image, InputOutputArray mask,
 -                            Point seedPoint, Scalar newVal, CV_OUT Rect* rect=0,
 -                            Scalar loDiff=Scalar(), Scalar upDiff=Scalar(),
 -                            int flags=4 );
 -
 -
 -enum
 -{
 -    COLOR_BGR2BGRA    =0,
 -    COLOR_RGB2RGBA    =COLOR_BGR2BGRA,
 -
 -    COLOR_BGRA2BGR    =1,
 -    COLOR_RGBA2RGB    =COLOR_BGRA2BGR,
 -
 -    COLOR_BGR2RGBA    =2,
 -    COLOR_RGB2BGRA    =COLOR_BGR2RGBA,
 -
 -    COLOR_RGBA2BGR    =3,
 -    COLOR_BGRA2RGB    =COLOR_RGBA2BGR,
 -
 -    COLOR_BGR2RGB     =4,
 -    COLOR_RGB2BGR     =COLOR_BGR2RGB,
 -
 -    COLOR_BGRA2RGBA   =5,
 -    COLOR_RGBA2BGRA   =COLOR_BGRA2RGBA,
 -
 -    COLOR_BGR2GRAY    =6,
 -    COLOR_RGB2GRAY    =7,
 -    COLOR_GRAY2BGR    =8,
 -    COLOR_GRAY2RGB    =COLOR_GRAY2BGR,
 -    COLOR_GRAY2BGRA   =9,
 -    COLOR_GRAY2RGBA   =COLOR_GRAY2BGRA,
 -    COLOR_BGRA2GRAY   =10,
 -    COLOR_RGBA2GRAY   =11,
 -
 -    COLOR_BGR2BGR565  =12,
 -    COLOR_RGB2BGR565  =13,
 -    COLOR_BGR5652BGR  =14,
 -    COLOR_BGR5652RGB  =15,
 -    COLOR_BGRA2BGR565 =16,
 -    COLOR_RGBA2BGR565 =17,
 -    COLOR_BGR5652BGRA =18,
 -    COLOR_BGR5652RGBA =19,
 -
 -    COLOR_GRAY2BGR565 =20,
 -    COLOR_BGR5652GRAY =21,
 -
 -    COLOR_BGR2BGR555  =22,
 -    COLOR_RGB2BGR555  =23,
 -    COLOR_BGR5552BGR  =24,
 -    COLOR_BGR5552RGB  =25,
 -    COLOR_BGRA2BGR555 =26,
 -    COLOR_RGBA2BGR555 =27,
 -    COLOR_BGR5552BGRA =28,
 -    COLOR_BGR5552RGBA =29,
 -
 -    COLOR_GRAY2BGR555 =30,
 -    COLOR_BGR5552GRAY =31,
 -
 -    COLOR_BGR2XYZ     =32,
 -    COLOR_RGB2XYZ     =33,
 -    COLOR_XYZ2BGR     =34,
 -    COLOR_XYZ2RGB     =35,
 -
 -    COLOR_BGR2YCrCb   =36,
 -    COLOR_RGB2YCrCb   =37,
 -    COLOR_YCrCb2BGR   =38,
 -    COLOR_YCrCb2RGB   =39,
 -
 -    COLOR_BGR2HSV     =40,
 -    COLOR_RGB2HSV     =41,
 -
 -    COLOR_BGR2Lab     =44,
 -    COLOR_RGB2Lab     =45,
 -
 -    COLOR_BayerBG2BGR =46,
 -    COLOR_BayerGB2BGR =47,
 -    COLOR_BayerRG2BGR =48,
 -    COLOR_BayerGR2BGR =49,
 -
 -    COLOR_BayerBG2RGB =COLOR_BayerRG2BGR,
 -    COLOR_BayerGB2RGB =COLOR_BayerGR2BGR,
 -    COLOR_BayerRG2RGB =COLOR_BayerBG2BGR,
 -    COLOR_BayerGR2RGB =COLOR_BayerGB2BGR,
 -
 -    COLOR_BGR2Luv     =50,
 -    COLOR_RGB2Luv     =51,
 -    COLOR_BGR2HLS     =52,
 -    COLOR_RGB2HLS     =53,
 -
 -    COLOR_HSV2BGR     =54,
 -    COLOR_HSV2RGB     =55,
 -
 -    COLOR_Lab2BGR     =56,
 -    COLOR_Lab2RGB     =57,
 -    COLOR_Luv2BGR     =58,
 -    COLOR_Luv2RGB     =59,
 -    COLOR_HLS2BGR     =60,
 -    COLOR_HLS2RGB     =61,
 -
 -    COLOR_BayerBG2BGR_VNG =62,
 -    COLOR_BayerGB2BGR_VNG =63,
 -    COLOR_BayerRG2BGR_VNG =64,
 -    COLOR_BayerGR2BGR_VNG =65,
 -
 -    COLOR_BayerBG2RGB_VNG =COLOR_BayerRG2BGR_VNG,
 -    COLOR_BayerGB2RGB_VNG =COLOR_BayerGR2BGR_VNG,
 -    COLOR_BayerRG2RGB_VNG =COLOR_BayerBG2BGR_VNG,
 -    COLOR_BayerGR2RGB_VNG =COLOR_BayerGB2BGR_VNG,
 -
 -    COLOR_BGR2HSV_FULL = 66,
 -    COLOR_RGB2HSV_FULL = 67,
 -    COLOR_BGR2HLS_FULL = 68,
 -    COLOR_RGB2HLS_FULL = 69,
 -
 -    COLOR_HSV2BGR_FULL = 70,
 -    COLOR_HSV2RGB_FULL = 71,
 -    COLOR_HLS2BGR_FULL = 72,
 -    COLOR_HLS2RGB_FULL = 73,
 -
 -    COLOR_LBGR2Lab     = 74,
 -    COLOR_LRGB2Lab     = 75,
 -    COLOR_LBGR2Luv     = 76,
 -    COLOR_LRGB2Luv     = 77,
 -
 -    COLOR_Lab2LBGR     = 78,
 -    COLOR_Lab2LRGB     = 79,
 -    COLOR_Luv2LBGR     = 80,
 -    COLOR_Luv2LRGB     = 81,
 -
 -    COLOR_BGR2YUV      = 82,
 -    COLOR_RGB2YUV      = 83,
 -    COLOR_YUV2BGR      = 84,
 -    COLOR_YUV2RGB      = 85,
 -
 -    COLOR_BayerBG2GRAY = 86,
 -    COLOR_BayerGB2GRAY = 87,
 -    COLOR_BayerRG2GRAY = 88,
 -    COLOR_BayerGR2GRAY = 89,
 -
 -    //YUV 4:2:0 formats family
 -    COLOR_YUV2RGB_NV12 = 90,
 -    COLOR_YUV2BGR_NV12 = 91,
 -    COLOR_YUV2RGB_NV21 = 92,
 -    COLOR_YUV2BGR_NV21 = 93,
 -    COLOR_YUV420sp2RGB = COLOR_YUV2RGB_NV21,
 -    COLOR_YUV420sp2BGR = COLOR_YUV2BGR_NV21,
 -
 -    COLOR_YUV2RGBA_NV12 = 94,
 -    COLOR_YUV2BGRA_NV12 = 95,
 -    COLOR_YUV2RGBA_NV21 = 96,
 -    COLOR_YUV2BGRA_NV21 = 97,
 -    COLOR_YUV420sp2RGBA = COLOR_YUV2RGBA_NV21,
 -    COLOR_YUV420sp2BGRA = COLOR_YUV2BGRA_NV21,
 -
 -    COLOR_YUV2RGB_YV12 = 98,
 -    COLOR_YUV2BGR_YV12 = 99,
 -    COLOR_YUV2RGB_IYUV = 100,
 -    COLOR_YUV2BGR_IYUV = 101,
 -    COLOR_YUV2RGB_I420 = COLOR_YUV2RGB_IYUV,
 -    COLOR_YUV2BGR_I420 = COLOR_YUV2BGR_IYUV,
 -    COLOR_YUV420p2RGB = COLOR_YUV2RGB_YV12,
 -    COLOR_YUV420p2BGR = COLOR_YUV2BGR_YV12,
 -
 -    COLOR_YUV2RGBA_YV12 = 102,
 -    COLOR_YUV2BGRA_YV12 = 103,
 -    COLOR_YUV2RGBA_IYUV = 104,
 -    COLOR_YUV2BGRA_IYUV = 105,
 -    COLOR_YUV2RGBA_I420 = COLOR_YUV2RGBA_IYUV,
 -    COLOR_YUV2BGRA_I420 = COLOR_YUV2BGRA_IYUV,
 -    COLOR_YUV420p2RGBA = COLOR_YUV2RGBA_YV12,
 -    COLOR_YUV420p2BGRA = COLOR_YUV2BGRA_YV12,
 -
 -    COLOR_YUV2GRAY_420 = 106,
 -    COLOR_YUV2GRAY_NV21 = COLOR_YUV2GRAY_420,
 -    COLOR_YUV2GRAY_NV12 = COLOR_YUV2GRAY_420,
 -    COLOR_YUV2GRAY_YV12 = COLOR_YUV2GRAY_420,
 -    COLOR_YUV2GRAY_IYUV = COLOR_YUV2GRAY_420,
 -    COLOR_YUV2GRAY_I420 = COLOR_YUV2GRAY_420,
 -    COLOR_YUV420sp2GRAY = COLOR_YUV2GRAY_420,
 -    COLOR_YUV420p2GRAY = COLOR_YUV2GRAY_420,
 -
 -    //YUV 4:2:2 formats family
 -    COLOR_YUV2RGB_UYVY = 107,
 -    COLOR_YUV2BGR_UYVY = 108,
 -    //COLOR_YUV2RGB_VYUY = 109,
 -    //COLOR_YUV2BGR_VYUY = 110,
 -    COLOR_YUV2RGB_Y422 = COLOR_YUV2RGB_UYVY,
 -    COLOR_YUV2BGR_Y422 = COLOR_YUV2BGR_UYVY,
 -    COLOR_YUV2RGB_UYNV = COLOR_YUV2RGB_UYVY,
 -    COLOR_YUV2BGR_UYNV = COLOR_YUV2BGR_UYVY,
 -
 -    COLOR_YUV2RGBA_UYVY = 111,
 -    COLOR_YUV2BGRA_UYVY = 112,
 -    //COLOR_YUV2RGBA_VYUY = 113,
 -    //COLOR_YUV2BGRA_VYUY = 114,
 -    COLOR_YUV2RGBA_Y422 = COLOR_YUV2RGBA_UYVY,
 -    COLOR_YUV2BGRA_Y422 = COLOR_YUV2BGRA_UYVY,
 -    COLOR_YUV2RGBA_UYNV = COLOR_YUV2RGBA_UYVY,
 -    COLOR_YUV2BGRA_UYNV = COLOR_YUV2BGRA_UYVY,
 -
 -    COLOR_YUV2RGB_YUY2 = 115,
 -    COLOR_YUV2BGR_YUY2 = 116,
 -    COLOR_YUV2RGB_YVYU = 117,
 -    COLOR_YUV2BGR_YVYU = 118,
 -    COLOR_YUV2RGB_YUYV = COLOR_YUV2RGB_YUY2,
 -    COLOR_YUV2BGR_YUYV = COLOR_YUV2BGR_YUY2,
 -    COLOR_YUV2RGB_YUNV = COLOR_YUV2RGB_YUY2,
 -    COLOR_YUV2BGR_YUNV = COLOR_YUV2BGR_YUY2,
 -
 -    COLOR_YUV2RGBA_YUY2 = 119,
 -    COLOR_YUV2BGRA_YUY2 = 120,
 -    COLOR_YUV2RGBA_YVYU = 121,
 -    COLOR_YUV2BGRA_YVYU = 122,
 -    COLOR_YUV2RGBA_YUYV = COLOR_YUV2RGBA_YUY2,
 -    COLOR_YUV2BGRA_YUYV = COLOR_YUV2BGRA_YUY2,
 -    COLOR_YUV2RGBA_YUNV = COLOR_YUV2RGBA_YUY2,
 -    COLOR_YUV2BGRA_YUNV = COLOR_YUV2BGRA_YUY2,
 -
 -    COLOR_YUV2GRAY_UYVY = 123,
 -    COLOR_YUV2GRAY_YUY2 = 124,
 -    //COLOR_YUV2GRAY_VYUY = COLOR_YUV2GRAY_UYVY,
 -    COLOR_YUV2GRAY_Y422 = COLOR_YUV2GRAY_UYVY,
 -    COLOR_YUV2GRAY_UYNV = COLOR_YUV2GRAY_UYVY,
 -    COLOR_YUV2GRAY_YVYU = COLOR_YUV2GRAY_YUY2,
 -    COLOR_YUV2GRAY_YUYV = COLOR_YUV2GRAY_YUY2,
 -    COLOR_YUV2GRAY_YUNV = COLOR_YUV2GRAY_YUY2,
 -
 -    // alpha premultiplication
 -    COLOR_RGBA2mRGBA = 125,
 -    COLOR_mRGBA2RGBA = 126,
 -
 -    COLOR_RGB2YUV_I420 = 127,
 -    COLOR_BGR2YUV_I420 = 128,
 -    COLOR_RGB2YUV_IYUV = COLOR_RGB2YUV_I420,
 -    COLOR_BGR2YUV_IYUV = COLOR_BGR2YUV_I420,
 -
 -    COLOR_RGBA2YUV_I420 = 129,
 -    COLOR_BGRA2YUV_I420 = 130,
 -    COLOR_RGBA2YUV_IYUV = COLOR_RGBA2YUV_I420,
 -    COLOR_BGRA2YUV_IYUV = COLOR_BGRA2YUV_I420,
 -    COLOR_RGB2YUV_YV12  = 131,
 -    COLOR_BGR2YUV_YV12  = 132,
 -    COLOR_RGBA2YUV_YV12 = 133,
 -    COLOR_BGRA2YUV_YV12 = 134,
 -
 -    COLOR_COLORCVT_MAX  = 135
 -};
 -
 -
 -//! converts image from one color space to another
 -CV_EXPORTS_W void cvtColor( InputArray src, OutputArray dst, int code, int dstCn=0 );
 -
 -//! raster image moments
 -class CV_EXPORTS_W_MAP Moments
 -{
 -public:
 -    //! the default constructor
 -    Moments();
 -    //! the full constructor
 -    Moments(double m00, double m10, double m01, double m20, double m11,
 -            double m02, double m30, double m21, double m12, double m03 );
 -    //! the conversion from CvMoments
 -    Moments( const CvMoments& moments );
 -    //! the conversion to CvMoments
 -    operator CvMoments() const;
 -
 -    //! spatial moments
 -    CV_PROP_RW double  m00, m10, m01, m20, m11, m02, m30, m21, m12, m03;
 -    //! central moments
 -    CV_PROP_RW double  mu20, mu11, mu02, mu30, mu21, mu12, mu03;
 -    //! central normalized moments
 -    CV_PROP_RW double  nu20, nu11, nu02, nu30, nu21, nu12, nu03;
 -};
 -
 -//! computes moments of the rasterized shape or a vector of points
 -CV_EXPORTS_W Moments moments( InputArray array, bool binaryImage=false );
 -
 -//! computes 7 Hu invariants from the moments
 -CV_EXPORTS void HuMoments( const Moments& moments, double hu[7] );
 -CV_EXPORTS_W void HuMoments( const Moments& m, CV_OUT OutputArray hu );
 -
 -//! type of the template matching operation
 -enum { TM_SQDIFF=0, TM_SQDIFF_NORMED=1, TM_CCORR=2, TM_CCORR_NORMED=3, TM_CCOEFF=4, TM_CCOEFF_NORMED=5 };
 -
 -//! computes the proximity map for the raster template and the image where the template is searched for
 -CV_EXPORTS_W void matchTemplate( InputArray image, InputArray templ,
 -                                 OutputArray result, int method );
 -
 -//! mode of the contour retrieval algorithm
 -enum
 -{
 -    RETR_EXTERNAL=CV_RETR_EXTERNAL, //!< retrieve only the most external (top-level) contours
 -    RETR_LIST=CV_RETR_LIST, //!< retrieve all the contours without any hierarchical information
 -    RETR_CCOMP=CV_RETR_CCOMP, //!< retrieve the connected components (that can possibly be nested)
 -    RETR_TREE=CV_RETR_TREE, //!< retrieve all the contours and the whole hierarchy
 -    RETR_FLOODFILL=CV_RETR_FLOODFILL
 -};
 -
 -//! the contour approximation algorithm
 -enum
 -{
 -    CHAIN_APPROX_NONE=CV_CHAIN_APPROX_NONE,
 -    CHAIN_APPROX_SIMPLE=CV_CHAIN_APPROX_SIMPLE,
 -    CHAIN_APPROX_TC89_L1=CV_CHAIN_APPROX_TC89_L1,
 -    CHAIN_APPROX_TC89_KCOS=CV_CHAIN_APPROX_TC89_KCOS
 -};
 -
 -//! retrieves contours and the hierarchical information from black-n-white image.
 -CV_EXPORTS_W void findContours( InputOutputArray image, OutputArrayOfArrays contours,
 -                              OutputArray hierarchy, int mode,
 -                              int method, Point offset=Point());
 -
 -//! retrieves contours from black-n-white image.
 -CV_EXPORTS void findContours( InputOutputArray image, OutputArrayOfArrays contours,
 -                              int mode, int method, Point offset=Point());
 -
 -//! draws contours in the image
 -CV_EXPORTS_W void drawContours( InputOutputArray image, InputArrayOfArrays contours,
 -                              int contourIdx, const Scalar& color,
 -                              int thickness=1, int lineType=8,
 -                              InputArray hierarchy=noArray(),
 -                              int maxLevel=INT_MAX, Point offset=Point() );
 -
 -//! approximates contour or a curve using Douglas-Peucker algorithm
 -CV_EXPORTS_W void approxPolyDP( InputArray curve,
 -                                OutputArray approxCurve,
 -                                double epsilon, bool closed );
 -
 -//! computes the contour perimeter (closed=true) or a curve length
 -CV_EXPORTS_W double arcLength( InputArray curve, bool closed );
 -//! computes the bounding rectangle for a contour
 -CV_EXPORTS_W Rect boundingRect( InputArray points );
 -//! computes the contour area
 -CV_EXPORTS_W double contourArea( InputArray contour, bool oriented=false );
 -//! computes the minimal rotated rectangle for a set of points
 -CV_EXPORTS_W RotatedRect minAreaRect( InputArray points );
 -//! computes the minimal enclosing circle for a set of points
 -CV_EXPORTS_W void minEnclosingCircle( InputArray points,
 -                                      CV_OUT Point2f& center, CV_OUT float& radius );
 -//! matches two contours using one of the available algorithms
 -CV_EXPORTS_W double matchShapes( InputArray contour1, InputArray contour2,
 -                                 int method, double parameter );
 -//! computes convex hull for a set of 2D points.
 -CV_EXPORTS_W void convexHull( InputArray points, OutputArray hull,
 -                              bool clockwise=false, bool returnPoints=true );
 -//! computes the contour convexity defects
 -CV_EXPORTS_W void convexityDefects( InputArray contour, InputArray convexhull, OutputArray convexityDefects );
 -
 -//! returns true if the contour is convex. Does not support contours with self-intersection
 -CV_EXPORTS_W bool isContourConvex( InputArray contour );
 -
 -//! finds intersection of two convex polygons
 -CV_EXPORTS_W float intersectConvexConvex( InputArray _p1, InputArray _p2,
 -                                          OutputArray _p12, bool handleNested=true );
 -
 -//! fits ellipse to the set of 2D points
 -CV_EXPORTS_W RotatedRect fitEllipse( InputArray points );
 -
 -//! fits line to the set of 2D points using M-estimator algorithm
 -CV_EXPORTS_W void fitLine( InputArray points, OutputArray line, int distType,
 -                           double param, double reps, double aeps );
 -//! checks if the point is inside the contour. Optionally computes the signed distance from the point to the contour boundary
 -CV_EXPORTS_W double pointPolygonTest( InputArray contour, Point2f pt, bool measureDist );
 -
 -
 -class CV_EXPORTS_W Subdiv2D
 -{
 -public:
 -    enum
 -    {
 -        PTLOC_ERROR = -2,
 -        PTLOC_OUTSIDE_RECT = -1,
 -        PTLOC_INSIDE = 0,
 -        PTLOC_VERTEX = 1,
 -        PTLOC_ON_EDGE = 2
 -    };
 -
 -    enum
 -    {
 -        NEXT_AROUND_ORG   = 0x00,
 -        NEXT_AROUND_DST   = 0x22,
 -        PREV_AROUND_ORG   = 0x11,
 -        PREV_AROUND_DST   = 0x33,
 -        NEXT_AROUND_LEFT  = 0x13,
 -        NEXT_AROUND_RIGHT = 0x31,
 -        PREV_AROUND_LEFT  = 0x20,
 -        PREV_AROUND_RIGHT = 0x02
 -    };
 -
 -    CV_WRAP Subdiv2D();
 -    CV_WRAP Subdiv2D(Rect rect);
 -    CV_WRAP void initDelaunay(Rect rect);
 -
 -    CV_WRAP int insert(Point2f pt);
 -    CV_WRAP void insert(const vector<Point2f>& ptvec);
 -    CV_WRAP int locate(Point2f pt, CV_OUT int& edge, CV_OUT int& vertex);
 -
 -    CV_WRAP int findNearest(Point2f pt, CV_OUT Point2f* nearestPt=0);
 -    CV_WRAP void getEdgeList(CV_OUT vector<Vec4f>& edgeList) const;
 -    CV_WRAP void getTriangleList(CV_OUT vector<Vec6f>& triangleList) const;
 -    CV_WRAP void getVoronoiFacetList(const vector<int>& idx, CV_OUT vector<vector<Point2f> >& facetList,
 -                                     CV_OUT vector<Point2f>& facetCenters);
 -
 -    CV_WRAP Point2f getVertex(int vertex, CV_OUT int* firstEdge=0) const;
 -
 -    CV_WRAP int getEdge( int edge, int nextEdgeType ) const;
 -    CV_WRAP int nextEdge(int edge) const;
 -    CV_WRAP int rotateEdge(int edge, int rotate) const;
 -    CV_WRAP int symEdge(int edge) const;
 -    CV_WRAP int edgeOrg(int edge, CV_OUT Point2f* orgpt=0) const;
 -    CV_WRAP int edgeDst(int edge, CV_OUT Point2f* dstpt=0) const;
 -
 -protected:
 -    int newEdge();
 -    void deleteEdge(int edge);
 -    int newPoint(Point2f pt, bool isvirtual, int firstEdge=0);
 -    void deletePoint(int vtx);
 -    void setEdgePoints( int edge, int orgPt, int dstPt );
 -    void splice( int edgeA, int edgeB );
 -    int connectEdges( int edgeA, int edgeB );
 -    void swapEdges( int edge );
 -    int isRightOf(Point2f pt, int edge) const;
 -    void calcVoronoi();
 -    void clearVoronoi();
 -    void checkSubdiv() const;
 -
 -    struct CV_EXPORTS Vertex
 -    {
 -        Vertex();
 -        Vertex(Point2f pt, bool _isvirtual, int _firstEdge=0);
 -        bool isvirtual() const;
 -        bool isfree() const;
 -        int firstEdge;
 -        int type;
 -        Point2f pt;
 -    };
 -    struct CV_EXPORTS QuadEdge
 -    {
 -        QuadEdge();
 -        QuadEdge(int edgeidx);
 -        bool isfree() const;
 -        int next[4];
 -        int pt[4];
 -    };
 -
 -    vector<Vertex> vtx;
 -    vector<QuadEdge> qedges;
 -    int freeQEdge;
 -    int freePoint;
 -    bool validGeometry;
 -
 -    int recentEdge;
 -    Point2f topLeft;
 -    Point2f bottomRight;
 -};
 -
 -}
 -
 -#endif /* __cplusplus */
 -
 +#ifdef __OPENCV_BUILD
 +#error this is a compatibility header which should not be used inside the OpenCV library
  #endif
  
- #include "opencv2/imgproc.hpp"
 -/* End of file. */
++#include "opencv2/imgproc.hpp"
Simple merge
@@@ -260,8 -261,8 +260,8 @@@ class CV_EXPORTS_AS(DescriptorExtractor
  public:
  #if 0
      //DO NOT REMOVE! The block is required for sources parser
-     CV_WRAP void compute( const Mat& image, std::vector<KeyPoint>& keypoints, Mat& descriptors ) const;
-     CV_WRAP void compute( const std::vector<Mat>& images, std::vector<std::vector<KeyPoint> >& keypoints, CV_OUT std::vector<Mat>& descriptors ) const;
 -    CV_WRAP void compute( const Mat& image, CV_IN_OUT vector<KeyPoint>& keypoints, Mat& descriptors ) const;
 -    CV_WRAP void compute( const vector<Mat>& images, CV_IN_OUT vector<vector<KeyPoint> >& keypoints, CV_OUT vector<Mat>& descriptors ) const;
++    CV_WRAP void compute( const Mat& image, CV_IN_OUT std::vector<KeyPoint>& keypoints, Mat& descriptors ) const;
++    CV_WRAP void compute( const std::vector<Mat>& images, CV_IN_OUT std::vector<std::vector<KeyPoint> >& keypoints, CV_OUT std::vector<Mat>& descriptors ) const;
      CV_WRAP virtual int descriptorSize() const;
      CV_WRAP virtual int descriptorType() const;
  
Simple merge
Simple merge
Simple merge
@@@ -9,11 -9,12 +9,12 @@@
  #ifndef __OPENCV_PERF_PRECOMP_HPP__
  #define __OPENCV_PERF_PRECOMP_HPP__
  
 -#include "opencv2/ts/ts.hpp"
 +#include "opencv2/ts.hpp"
 +#include "opencv2/nonfree.hpp"
 +#include "opencv2/highgui.hpp"
  
 -#include "opencv2/nonfree/nonfree.hpp"
 -#include "opencv2/highgui/highgui.hpp"
  #include "opencv2/opencv_modules.hpp"
  #ifdef HAVE_OPENCV_OCL
  #  include "opencv2/nonfree/ocl.hpp"
  #endif
@@@ -1158,10 -1202,9 +1202,9 @@@ __kerne
          sdyabs[tid] = fabs(sdy[tid]); // |dy| array
      }
      barrier(CLK_LOCAL_MEM_FENCE);
-     if (tid < 25)
-     {
          reduce_sum25(sdx, sdy, sdxabs, sdyabs, tid);
-     }
 - 
++
      barrier(CLK_LOCAL_MEM_FENCE);
      if (tid < 25)
      {
@@@ -1274,6 -1322,103 +1322,103 @@@ __kerne
          }
      }
  }
 -    if (tid < 32) 
+ void reduce_sum128(volatile __local  float* smem, int tid)
+ {
+ #ifndef WAVE_SIZE
+ #define WAVE_SIZE 1
+ #endif
+     if (tid < 64)
+     {
+         smem[tid] += smem[tid + 64];
+ #if WAVE_SIZE < 64
+     }
+     barrier(CLK_LOCAL_MEM_FENCE);
 -    if (tid < 16) 
++    if (tid < 32)
+     {
+ #endif
+         smem[tid] += smem[tid + 32];
+ #if WAVE_SIZE < 32
+     }
+     barrier(CLK_LOCAL_MEM_FENCE);
 -    if (tid < 16) 
++    if (tid < 16)
+     {
+ #endif
+         smem[tid] += smem[tid + 16];
+ #if WAVE_SIZE < 16
+     }
+     barrier(CLK_LOCAL_MEM_FENCE);
+     if (tid < 8)
+     {
+ #endif
+         smem[tid] += smem[tid + 8];
+ #if WAVE_SIZE < 8
+     }
+     barrier(CLK_LOCAL_MEM_FENCE);
+     if (tid < 4)
+     {
+ #endif
+         smem[tid] += smem[tid + 4];
+ #if WAVE_SIZE < 4
+     }
+     barrier(CLK_LOCAL_MEM_FENCE);
+     if (tid < 2)
+     {
+ #endif
+         smem[tid] += smem[tid + 2];
+ #if WAVE_SIZE < 2
+     }
+     barrier(CLK_LOCAL_MEM_FENCE);
+     if (tid < 1)
+     {
+ #endif
+         smem[tid] += smem[tid + 1];
+     }
+ }
+ void reduce_sum64(volatile __local  float* smem, int tid)
+ {
+ #ifndef WAVE_SIZE
+ #define WAVE_SIZE 1
+ #endif
+     if (tid < 32)
+     {
+         smem[tid] += smem[tid + 32];
+ #if WAVE_SIZE < 32
+     }
+     barrier(CLK_LOCAL_MEM_FENCE);
++    if (tid < 16)
+     {
+ #endif
+         smem[tid] += smem[tid + 16];
+ #if WAVE_SIZE < 16
+     }
+     barrier(CLK_LOCAL_MEM_FENCE);
+     if (tid < 8)
+     {
+ #endif
+         smem[tid] += smem[tid + 8];
+ #if WAVE_SIZE < 8
+     }
+     barrier(CLK_LOCAL_MEM_FENCE);
+     if (tid < 4)
+     {
+ #endif
+         smem[tid] += smem[tid + 4];
+ #if WAVE_SIZE < 4
+     }
+     barrier(CLK_LOCAL_MEM_FENCE);
+     if (tid < 2)
+     {
+ #endif
+         smem[tid] += smem[tid + 2];
+ #if WAVE_SIZE < 2
+     }
+     barrier(CLK_LOCAL_MEM_FENCE);
+     if (tid < 1)
+     {
+ #endif
+         smem[tid] += smem[tid + 1];
+     }
+ }
  
  __kernel
      void normalize_descriptors128(__global float * descriptors, int descriptors_step)
@@@ -56,19 -58,29 +57,29 @@@ namespace c
          ///////////////////////////OpenCL kernel strings///////////////////////////
          extern const char *surf;
  
-         const char* noImage2dOption = "-D DISABLE_IMAGE2D";
+         const char noImage2dOption [] = "-D DISABLE_IMAGE2D";
  
 -        static char SURF_OPTIONS [1024] = ""; 
++        static char SURF_OPTIONS [1024] = "";
+         static bool USE_IMAGE2d = false;
 -        static void openCLExecuteKernelSURF(Context *clCxt , const char **source, string kernelName, size_t globalThreads[3],
 -            size_t localThreads[3],  vector< pair<size_t, const void *> > &args, int channels, int depth)
 +        static void openCLExecuteKernelSURF(Context *clCxt , const char **source, String kernelName, size_t globalThreads[3],
-             size_t localThreads[3], std::vector< std::pair<size_t, const void *> > &args, int channels, int depth)
++            size_t localThreads[3],  std::vector< std::pair<size_t, const void *> > &args, int channels, int depth)
          {
-             if(support_image2d())
+             char * pSURF_OPTIONS = SURF_OPTIONS;
+             static bool OPTION_INIT = false;
+             if(!OPTION_INIT)
              {
-                 openCLExecuteKernel(clCxt, source, kernelName, globalThreads, localThreads, args, channels, depth);
-             }
-             else
-             {
-                 openCLExecuteKernel(clCxt, source, kernelName, globalThreads, localThreads, args, channels, depth, noImage2dOption);
+                 if( !USE_IMAGE2d )
+                 {
+                     strcat(pSURF_OPTIONS, noImage2dOption);
+                     pSURF_OPTIONS += strlen(noImage2dOption);
+                 }
+                 size_t wave_size = 0;
+                 queryDeviceInfo(WAVEFRONT_SIZE, &wave_size);
+                 std::sprintf(pSURF_OPTIONS, " -D WAVE_SIZE=%d", static_cast<int>(wave_size));
+                 OPTION_INIT = true;
              }
+             openCLExecuteKernel(clCxt, source, kernelName, globalThreads, localThreads, args, channels, depth, SURF_OPTIONS);
          }
      }
  }
Simple merge
@@@ -73,24 -76,24 +75,24 @@@ void matchUnrolledCached(const oclMat &
  
      if(globalSize[0] != 0)
      {
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&query.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&train.data ));
 -        //args.push_back( make_pair( sizeof(cl_mem), (void *)&mask.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&trainIdx.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&distance.data ));
 -        args.push_back( make_pair( smemSize, (void *)NULL));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&block_size ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&m_size ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.rows ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.cols ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&train.rows ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&train.cols ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.step ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&distType ));
 -
 -        std::string kernelName = "BruteForceMatch_UnrollMatch";
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&query.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&train.data ));
 +        //args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mask.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&trainIdx.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&distance.data ));
 +        args.push_back( std::make_pair( smemSize, (void *)NULL));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&block_size ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&m_size ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.rows ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&train.rows ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&train.cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.step ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&distType ));
 +
 +        String kernelName = "BruteForceMatch_UnrollMatch";
  
-         openCLExecuteKernel(ctx, &brute_force_match, kernelName, globalSize, localSize, args, -1, -1);
+         openCLExecuteKernel(ctx, &brute_force_match, kernelName, globalSize, localSize, args, -1, query.depth());
      }
  }
  
@@@ -113,23 -117,23 +116,23 @@@ void match(const oclMat &query, const o
  
      if(globalSize[0] != 0)
      {
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&query.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&train.data ));
 -        //args.push_back( make_pair( sizeof(cl_mem), (void *)&mask.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&trainIdx.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&distance.data ));
 -        args.push_back( make_pair( smemSize, (void *)NULL));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&block_size ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.rows ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.cols ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&train.rows ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&train.cols ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.step ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&distType ));
 -
 -        std::string kernelName = "BruteForceMatch_Match";
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&query.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&train.data ));
 +        //args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mask.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&trainIdx.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&distance.data ));
 +        args.push_back( std::make_pair( smemSize, (void *)NULL));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&block_size ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.rows ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&train.rows ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&train.cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.step ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&distType ));
 +
 +        String kernelName = "BruteForceMatch_Match";
  
-         openCLExecuteKernel(ctx, &brute_force_match, kernelName, globalSize, localSize, args, -1, -1);
+         openCLExecuteKernel(ctx, &brute_force_match, kernelName, globalSize, localSize, args, -1, query.depth());
      }
  }
  
@@@ -154,28 -159,28 +158,28 @@@ void matchUnrolledCached(const oclMat &
  
      if(globalSize[0] != 0)
      {
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&query.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&train.data ));
 -        args.push_back( make_pair( sizeof(cl_float), (void *)&maxDistance ));
 -        //args.push_back( make_pair( sizeof(cl_mem), (void *)&mask.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&trainIdx.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&distance.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&nMatches.data ));
 -        args.push_back( make_pair( smemSize, (void *)NULL));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&block_size ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&m_size ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.rows ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.cols ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&train.rows ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&train.cols ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&trainIdx.cols ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.step ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&trainIdx.step ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&distType ));
 -
 -        std::string kernelName = "BruteForceMatch_RadiusUnrollMatch";
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&query.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&train.data ));
 +        args.push_back( std::make_pair( sizeof(cl_float), (void *)&maxDistance ));
 +        //args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mask.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&trainIdx.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&distance.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&nMatches.data ));
 +        args.push_back( std::make_pair( smemSize, (void *)NULL));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&block_size ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&m_size ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.rows ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&train.rows ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&train.cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&trainIdx.cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.step ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&trainIdx.step ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&distType ));
 +
 +        String kernelName = "BruteForceMatch_RadiusUnrollMatch";
  
-         openCLExecuteKernel(ctx, &brute_force_match, kernelName, globalSize, localSize, args, -1, -1);
+         openCLExecuteKernel(ctx, &brute_force_match, kernelName, globalSize, localSize, args, -1, query.depth());
      }
  }
  
@@@ -193,29 -199,27 +198,27 @@@ void radius_match(const oclMat &query, 
  
      if(globalSize[0] != 0)
      {
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&query.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&train.data ));
 -        args.push_back( make_pair( sizeof(cl_float), (void *)&maxDistance ));
 -        //args.push_back( make_pair( sizeof(cl_mem), (void *)&mask.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&trainIdx.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&distance.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&nMatches.data ));
 -        args.push_back( make_pair( smemSize, (void *)NULL));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&block_size ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.rows ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.cols ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&train.rows ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&train.cols ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&trainIdx.cols ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.step ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&trainIdx.step ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&distType ));
 -
 -        std::string kernelName = "BruteForceMatch_RadiusMatch";
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&query.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&train.data ));
 +        args.push_back( std::make_pair( sizeof(cl_float), (void *)&maxDistance ));
 +        //args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mask.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&trainIdx.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&distance.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&nMatches.data ));
 +        args.push_back( std::make_pair( smemSize, (void *)NULL));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&block_size ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.rows ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&train.rows ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&train.cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&trainIdx.cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.step ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&trainIdx.step ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&distType ));
 +
 +        String kernelName = "BruteForceMatch_RadiusMatch";
  
-         openCLExecuteKernel(ctx, &brute_force_match, kernelName, globalSize, localSize, args, -1, -1);
-         //float *dis = (float *)clEnqueueMapBuffer(ctx->impl->clCmdQueue, (cl_mem)distance.data, CL_TRUE, CL_MAP_READ, 0, 8, 0, NULL, NULL, NULL);
-         //printf("%f, %f\n", dis[0], dis[1]);
+         openCLExecuteKernel(ctx, &brute_force_match, kernelName, globalSize, localSize, args, -1, query.depth());
      }
  }
  
@@@ -483,24 -296,24 +295,24 @@@ void knn_matchUnrolledCached(const oclM
  
      if(globalSize[0] != 0)
      {
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&query.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&train.data ));
 -        //args.push_back( make_pair( sizeof(cl_mem), (void *)&mask.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&trainIdx.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&distance.data ));
 -        args.push_back( make_pair( smemSize, (void *)NULL));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&block_size ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&m_size ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.rows ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.cols ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&train.rows ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&train.cols ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.step ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&distType ));
 -
 -        std::string kernelName = "BruteForceMatch_knnUnrollMatch";
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&query.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&train.data ));
 +        //args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mask.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&trainIdx.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&distance.data ));
 +        args.push_back( std::make_pair( smemSize, (void *)NULL));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&block_size ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&m_size ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.rows ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&train.rows ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&train.cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.step ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&distType ));
 +
 +        String kernelName = "BruteForceMatch_knnUnrollMatch";
  
-         openCLExecuteKernel(ctx, &brute_force_match, kernelName, globalSize, localSize, args, -1, -1);
+         openCLExecuteKernel(ctx, &brute_force_match, kernelName, globalSize, localSize, args, -1, query.depth());
      }
  }
  
@@@ -517,23 -330,23 +329,23 @@@ void knn_match(const oclMat &query, con
  
      if(globalSize[0] != 0)
      {
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&query.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&train.data ));
 -        //args.push_back( make_pair( sizeof(cl_mem), (void *)&mask.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&trainIdx.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&distance.data ));
 -        args.push_back( make_pair( smemSize, (void *)NULL));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&block_size ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.rows ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.cols ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&train.rows ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&train.cols ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.step ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&distType ));
 -
 -        std::string kernelName = "BruteForceMatch_knnMatch";
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&query.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&train.data ));
 +        //args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mask.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&trainIdx.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&distance.data ));
 +        args.push_back( std::make_pair( smemSize, (void *)NULL));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&block_size ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.rows ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&train.rows ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&train.cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.step ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&distType ));
 +
 +        String kernelName = "BruteForceMatch_knnMatch";
  
-         openCLExecuteKernel(ctx, &brute_force_match, kernelName, globalSize, localSize, args, -1, -1);
+         openCLExecuteKernel(ctx, &brute_force_match, kernelName, globalSize, localSize, args, -1, query.depth());
      }
  }
  
@@@ -550,23 -363,23 +362,23 @@@ void calcDistanceUnrolled(const oclMat 
  
      if(globalSize[0] != 0)
      {
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&query.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&train.data ));
 -        //args.push_back( make_pair( sizeof(cl_mem), (void *)&mask.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&allDist.data ));
 -        args.push_back( make_pair( smemSize, (void *)NULL));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&block_size ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&m_size ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.rows ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.cols ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&train.rows ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&train.cols ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.step ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&distType ));
 -
 -        std::string kernelName = "BruteForceMatch_calcDistanceUnrolled";
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&query.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&train.data ));
 +        //args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mask.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&allDist.data ));
 +        args.push_back( std::make_pair( smemSize, (void *)NULL));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&block_size ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&m_size ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.rows ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&train.rows ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&train.cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.step ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&distType ));
 +
 +        String kernelName = "BruteForceMatch_calcDistanceUnrolled";
  
-         openCLExecuteKernel(ctx, &brute_force_match, kernelName, globalSize, localSize, args, -1, -1);
+         openCLExecuteKernel(ctx, &brute_force_match, kernelName, globalSize, localSize, args, -1, query.depth());
      }
  }
  
@@@ -582,22 -395,22 +394,22 @@@ void calcDistance(const oclMat &query, 
  
      if(globalSize[0] != 0)
      {
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&query.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&train.data ));
 -        //args.push_back( make_pair( sizeof(cl_mem), (void *)&mask.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&allDist.data ));
 -        args.push_back( make_pair( smemSize, (void *)NULL));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&block_size ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.rows ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.cols ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&train.rows ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&train.cols ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&query.step ));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&distType ));
 -
 -        std::string kernelName = "BruteForceMatch_calcDistance";
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&query.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&train.data ));
 +        //args.push_back( std::make_pair( sizeof(cl_mem), (void *)&mask.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&allDist.data ));
 +        args.push_back( std::make_pair( smemSize, (void *)NULL));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&block_size ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.rows ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&train.rows ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&train.cols ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.step ));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&distType ));
 +
 +        String kernelName = "BruteForceMatch_calcDistance";
  
-         openCLExecuteKernel(ctx, &brute_force_match, kernelName, globalSize, localSize, args, -1, -1);
+         openCLExecuteKernel(ctx, &brute_force_match, kernelName, globalSize, localSize, args, -1, query.depth());
      }
  }
  
@@@ -674,18 -461,18 +460,18 @@@ void findKnnMatch(int k, const oclMat &
  
      for (int i = 0; i < k; ++i)
      {
 -        vector< pair<size_t, const void *> > args;
 +        std::vector< std::pair<size_t, const void *> > args;
  
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&allDist.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&trainIdx.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&distance.data ));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&i));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&block_size ));
 -        //args.push_back( make_pair( sizeof(cl_int), (void *)&train.rows ));
 -        //args.push_back( make_pair( sizeof(cl_int), (void *)&train.cols ));
 -        //args.push_back( make_pair( sizeof(cl_int), (void *)&query.step ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&allDist.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&trainIdx.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&distance.data ));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&i));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&block_size ));
 +        //args.push_back( std::make_pair( sizeof(cl_int), (void *)&train.rows ));
 +        //args.push_back( std::make_pair( sizeof(cl_int), (void *)&train.cols ));
 +        //args.push_back( std::make_pair( sizeof(cl_int), (void *)&query.step ));
  
-         openCLExecuteKernel(ctx, &brute_force_match, kernelName, globalSize, localSize, args, -1, -1);
+         openCLExecuteKernel(ctx, &brute_force_match, kernelName, globalSize, localSize, args, trainIdx.depth(), -1);
      }
  }
  
@@@ -928,41 -531,31 +530,31 @@@ void cv::ocl::BruteForceMatcher_OCL_bas
  {
      if (query.empty() || train.empty())
          return;
 -    
 +
-     typedef void (*caller_t)(const oclMat & query, const oclMat & train, const oclMat & mask,
-                              const oclMat & trainIdx, const oclMat & distance);
+     // match1 doesn't support signed char type, match2 only support float, hamming support uchar, ushort and int
+     int callType = query.depth();
+     char cvFuncName[] = "singleMatch";
+     if (callType != 5)
+         CV_ERROR(CV_UNSUPPORTED_FORMAT_ERR, "BruteForceMatch OpenCL only support float type query!\n");
  
-     static const caller_t callers[3][6] =
+     if ((distType == 0 && callType == 1 ) || (distType == 1 && callType != 5) || (distType == 2 && (callType != 0
+         || callType != 2 || callType != 4)))
      {
-         {
-             ocl_matchL1_gpu<unsigned char>, 0/*ocl_matchL1_gpu<signed char>*/,
-             ocl_matchL1_gpu<unsigned short>, ocl_matchL1_gpu<short>,
-             ocl_matchL1_gpu<int>, ocl_matchL1_gpu<float>
-         },
-         {
-             0/*ocl_matchL2_gpu<unsigned char>*/, 0/*ocl_matchL2_gpu<signed char>*/,
-             0/*ocl_matchL2_gpu<unsigned short>*/, 0/*ocl_matchL2_gpu<short>*/,
-             0/*ocl_matchL2_gpu<int>*/, ocl_matchL2_gpu<float>
-         },
-         {
-             ocl_matchHamming_gpu<unsigned char>, 0/*ocl_matchHamming_gpu<signed char>*/,
-             ocl_matchHamming_gpu<unsigned short>, 0/*ocl_matchHamming_gpu<short>*/,
-             ocl_matchHamming_gpu<int>, 0/*ocl_matchHamming_gpu<float>*/
-         }
-     };
+         CV_ERROR(CV_UNSUPPORTED_DEPTH_ERR, "BruteForceMatch OpenCL only support float type query!\n");
+     }
  
      CV_Assert(query.channels() == 1 && query.depth() < CV_64F);
      CV_Assert(train.cols == query.cols && train.type() == query.type());
  
-     const int nQuery = query.rows;
-     trainIdx.create(1, nQuery, CV_32S);
-     distance.create(1, nQuery, CV_32F);
+     trainIdx.create(1, query.rows, CV_32S);
+     distance.create(1, query.rows, CV_32F);
  
-     caller_t func = callers[distType][query.depth()];
-     func(query, train, mask, trainIdx, distance);
+     matchDispatcher(query, train, mask, trainIdx, distance, distType);
+ exit:
+     return;
  }
  
 -void cv::ocl::BruteForceMatcher_OCL_base::matchDownload(const oclMat &trainIdx, const oclMat &distance, vector<DMatch> &matches)
 +void cv::ocl::BruteForceMatcher_OCL_base::matchDownload(const oclMat &trainIdx, const oclMat &distance, std::vector<DMatch> &matches)
  {
      if (trainIdx.empty() || distance.empty())
          return;
@@@ -1085,19 -668,16 +667,16 @@@ void cv::ocl::BruteForceMatcher_OCL_bas
  
      CV_Assert(query.channels() == 1 && query.depth() < CV_64F);
  
-     const int nQuery = query.rows;
-     trainIdx.create(1, nQuery, CV_32S);
-     imgIdx.create(1, nQuery, CV_32S);
-     distance.create(1, nQuery, CV_32F);
-     caller_t func = callers[distType][query.depth()];
-     CV_Assert(func != 0);
+     trainIdx.create(1, query.rows, CV_32S);
+     imgIdx.create(1, query.rows, CV_32S);
+     distance.create(1, query.rows, CV_32F);
  
-     func(query, trainCollection, masks, trainIdx, imgIdx, distance);
+     matchDispatcher(query, (const oclMat *)trainCollection.ptr(), trainCollection.cols, masks, trainIdx, imgIdx, distance, distType);
+ exit:
+     return;
  }
  
 -void cv::ocl::BruteForceMatcher_OCL_base::matchDownload(const oclMat &trainIdx, const oclMat &imgIdx, const oclMat &distance, vector<DMatch> &matches)
 +void cv::ocl::BruteForceMatcher_OCL_base::matchDownload(const oclMat &trainIdx, const oclMat &imgIdx, const oclMat &distance, std::vector<DMatch> &matches)
  {
      if (trainIdx.empty() || imgIdx.empty() || distance.empty())
          return;
@@@ -1205,13 -773,12 +772,12 @@@ void cv::ocl::BruteForceMatcher_OCL_bas
  
      trainIdx.setTo(Scalar::all(-1));
  
-     caller_t func = callers[distType][query.depth()];
-     CV_Assert(func != 0);
-     func(query, train, k, mask, trainIdx, distance, allDist);
+     kmatchDispatcher(query, train, k, mask, trainIdx, distance, allDist, distType);
+ exit:
+     return;
  }
  
 -void cv::ocl::BruteForceMatcher_OCL_base::knnMatchDownload(const oclMat &trainIdx, const oclMat &distance, vector< vector<DMatch> > &matches, bool compactResult)
 +void cv::ocl::BruteForceMatcher_OCL_base::knnMatchDownload(const oclMat &trainIdx, const oclMat &distance, std::vector< std::vector<DMatch> > &matches, bool compactResult)
  {
      if (trainIdx.empty() || distance.empty())
          return;
@@@ -1390,11 -957,9 +956,9 @@@ namespac
      };
  }
  
 -void cv::ocl::BruteForceMatcher_OCL_base::knnMatch(const oclMat &query, vector< vector<DMatch> > &matches, int k,
 -        const vector<oclMat> &masks, bool compactResult)
 +void cv::ocl::BruteForceMatcher_OCL_base::knnMatch(const oclMat &query, std::vector< std::vector<DMatch> > &matches, int k,
 +        const std::vector<oclMat> &masks, bool compactResult)
  {
      if (k == 2)
      {
          oclMat trainCollection;
@@@ -353,10 -354,10 +353,10 @@@ void canny::edgesHysteresisLocal_gpu(oc
  void canny::edgesHysteresisGlobal_gpu(oclMat &map, oclMat &st1, oclMat &st2, void *counter, int rows, int cols)
  {
      unsigned int count;
-     openCLSafeCall(clEnqueueReadBuffer((cl_command_queue)getoclCommandQueue(), (cl_mem)counter, 1, 0, sizeof(float), &count, 0, NULL, NULL));
+     openCLSafeCall(clEnqueueReadBuffer(*(cl_command_queue*)getoclCommandQueue(), (cl_mem)counter, 1, 0, sizeof(float), &count, 0, NULL, NULL));
      Context *clCxt = map.clCxt;
 -    string kernelName = "edgesHysteresisGlobal";
 -    vector< pair<size_t, const void *> > args;
 +    String kernelName = "edgesHysteresisGlobal";
 +    std::vector< std::pair<size_t, const void *> > args;
      size_t localThreads[3]  = {128, 1, 1};
  
  #define DIVUP(a, b) ((a)+(b)-1)/(b)
  
          args.clear();
          size_t globalThreads[3] = {std::min(count, 65535u) * 128, DIVUP(count, 65535), 1};
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&map.data));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&st1.data));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&st2.data));
 -        args.push_back( make_pair( sizeof(cl_mem), (void *)&counter));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&rows));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&cols));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&count));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&map.step));
 -        args.push_back( make_pair( sizeof(cl_int), (void *)&map.offset));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&map.data));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&st1.data));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&st2.data));
 +        args.push_back( std::make_pair( sizeof(cl_mem), (void *)&counter));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&rows));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&cols));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&count));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&map.step));
 +        args.push_back( std::make_pair( sizeof(cl_int), (void *)&map.offset));
  
          openCLExecuteKernel2(clCxt, &imgproc_canny, kernelName, globalThreads, localThreads, args, -1, -1, DISABLE);
-         openCLSafeCall(clEnqueueReadBuffer((cl_command_queue)getoclCommandQueue(), (cl_mem)counter, 1, 0, sizeof(int), &count, 0, NULL, NULL));
+         openCLSafeCall(clEnqueueReadBuffer(*(cl_command_queue*)getoclCommandQueue(), (cl_mem)counter, 1, 0, sizeof(int), &count, 0, NULL, NULL));
          std::swap(st1, st2);
      }
  #undef DIVUP
Simple merge
@@@ -350,6 -353,51 +350,51 @@@ namespace c
          {
              return &(Context::getContext()->impl->clCmdQueue);
          }
 -                        openCLSafeCall(clGetDeviceInfo(Context::getContext()->impl->devices[0], 
+         void queryDeviceInfo(DEVICE_INFO info_type, void* info)
+         {
+             static Info::Impl* impl = Context::getContext()->impl;
+             switch(info_type)
+             {
+             case WAVEFRONT_SIZE:
+                 {
+ #ifdef CL_DEVICE_WAVEFRONT_WIDTH_AMD
+                     try
+                     {
 -                        openCLSafeCall(clGetDeviceInfo(Context::getContext()->impl->devices[0], 
++                        openCLSafeCall(clGetDeviceInfo(Context::getContext()->impl->devices[0],
+                             CL_DEVICE_WAVEFRONT_WIDTH_AMD, sizeof(size_t), info, 0));
+                     }
+                     catch(const cv::Exception&)
+ #elif defined (CL_DEVICE_WARP_SIZE_NV)
+                     const int EXT_LEN = 4096 + 1 ;
+                     char extends_set[EXT_LEN];
+                     size_t extends_size;
+                     openCLSafeCall(clGetDeviceInfo(impl->devices[impl->devnum], CL_DEVICE_EXTENSIONS, EXT_LEN, (void *)extends_set, &extends_size));
+                     extends_set[EXT_LEN - 1] = 0;
+                     if(std::string(extends_set).find("cl_nv_device_attribute_query") != std::string::npos)
+                     {
++                        openCLSafeCall(clGetDeviceInfo(Context::getContext()->impl->devices[0],
+                             CL_DEVICE_WARP_SIZE_NV, sizeof(size_t), info, 0));
+                     }
+                     else
+ #endif
+                     {
+                         // if no way left for us to query the warp size, we can get it from kernel group info
+                         static const char * _kernel_string = "__kernel void test_func() {}";
+                         cl_kernel kernel;
+                         kernel = openCLGetKernelFromSource(Context::getContext(), &_kernel_string, "test_func");
+                         openCLSafeCall(clGetKernelWorkGroupInfo(kernel, impl->devices[impl->devnum],
+                             CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE, sizeof(size_t), info, NULL));
+                     }
+                 }
+                 break;
+             default:
+                 CV_Error(-1, "Invalid device info type");
+                 break;
+             }
+         }
          void openCLReadBuffer(Context *clCxt, cl_mem dst_buffer, void *host_buffer, size_t size)
          {
              cl_int status;
@@@ -92,21 -99,11 +98,11 @@@ namespace c
          // Evaluates optimal template's area threshold. If
          // template's area is less  than the threshold, we use naive match
          // template version, otherwise FFT-based (if available)
-         static int getTemplateThreshold(int method, int depth)
+         static bool useNaive(int , int , Size )
          {
-             switch (method)
-             {
-             case CV_TM_CCORR:
-                 if (depth == CV_32F) return 250;
-                 if (depth == CV_8U) return 300;
-                 break;
-             case CV_TM_SQDIFF:
-                 if (depth == CV_32F) return 0x7fffffff; // do naive SQDIFF for CV_32F
-                 if (depth == CV_8U) return 300;
-                 break;
-             }
-             CV_Error(CV_StsBadArg, "getTemplateThreshold: unsupported match template mode");
-             return 0;
+             // FIXME!
+             //   always use naive until convolve is imported
 -            return true; 
++            return true;
          }
  
          //////////////////////////////////////////////////////////////////////
              }
              else
              {
-                 // TODO
-                 CV_Error(CV_StsBadArg, "Not supported yet for this size template");
+                 buf.image_sqsums.resize(1);
 -                
++
+                 // TODO, add double support for ocl::integral
+                 // use CPU integral temporarily
+                 Mat sums, sqsums;
+                 cv::integral(Mat(image.reshape(1)), sums, sqsums);
+                 buf.image_sqsums[0] = sqsums;
+                 unsigned long long templ_sqsum = (unsigned long long)sqrSum(templ.reshape(1))[0];
+                 matchTemplate_CCORR(image, templ, result, buf);
+                 //port CUDA's matchTemplatePrepared_SQDIFF_8U
+                 Context *clCxt = image.clCxt;
 -                string kernelName = "matchTemplate_Prepared_SQDIFF";
 -                vector< pair<size_t, const void *> > args;
 -
 -                args.push_back( make_pair( sizeof(cl_mem), (void *)&buf.image_sqsums[0].data));
 -                args.push_back( make_pair( sizeof(cl_mem), (void *)&result.data));
 -                args.push_back( make_pair( sizeof(cl_ulong), (void *)&templ_sqsum));
 -                args.push_back( make_pair( sizeof(cl_int), (void *)&result.rows));
 -                args.push_back( make_pair( sizeof(cl_int), (void *)&result.cols));
 -                args.push_back( make_pair( sizeof(cl_int), (void *)&templ.rows));
 -                args.push_back( make_pair( sizeof(cl_int), (void *)&templ.cols));
 -                args.push_back( make_pair( sizeof(cl_int), (void *)&buf.image_sqsums[0].offset));
 -                args.push_back( make_pair( sizeof(cl_int), (void *)&buf.image_sqsums[0].step));
 -                args.push_back( make_pair( sizeof(cl_int), (void *)&result.offset));
 -                args.push_back( make_pair( sizeof(cl_int), (void *)&result.step));
++                String kernelName = "matchTemplate_Prepared_SQDIFF";
++                std::vector< std::pair<size_t, const void *> > args;
++
++                args.push_back( std::make_pair( sizeof(cl_mem), (void *)&buf.image_sqsums[0].data));
++                args.push_back( std::make_pair( sizeof(cl_mem), (void *)&result.data));
++                args.push_back( std::make_pair( sizeof(cl_ulong), (void *)&templ_sqsum));
++                args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.rows));
++                args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.cols));
++                args.push_back( std::make_pair( sizeof(cl_int), (void *)&templ.rows));
++                args.push_back( std::make_pair( sizeof(cl_int), (void *)&templ.cols));
++                args.push_back( std::make_pair( sizeof(cl_int), (void *)&buf.image_sqsums[0].offset));
++                args.push_back( std::make_pair( sizeof(cl_int), (void *)&buf.image_sqsums[0].step));
++                args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.offset));
++                args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.step));
+                 size_t globalThreads[3] = {result.cols, result.rows, 1};
+                 size_t localThreads[3]  = {16, 16, 1};
+                 const char * build_opt = image.oclchannels() == 4 ? "-D CN4" : "";
+                 openCLExecuteKernel(clCxt, &match_template, kernelName, globalThreads, localThreads, args, 1, CV_8U, build_opt);
              }
          }
  
              unsigned long long templ_sqsum = (unsigned long long)sqrSum(templ.reshape(1))[0];
  
              Context *clCxt = image.clCxt;
 -            string kernelName = "matchTemplate_Prepared_SQDIFF_NORMED";
 -            vector< pair<size_t, const void *> > args;
 -
 -            args.push_back( make_pair( sizeof(cl_mem), (void *)&buf.image_sums[0].data));
 -            args.push_back( make_pair( sizeof(cl_mem), (void *)&result.data));
 -            args.push_back( make_pair( sizeof(cl_ulong), (void *)&templ_sqsum));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.rows));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.cols));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&templ.rows));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&templ.cols));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&buf.image_sums[0].offset));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&buf.image_sums[0].step));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.offset));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.step));
 +            String kernelName = "matchTemplate_Prepared_SQDIFF_NORMED";
 +            std::vector< std::pair<size_t, const void *> > args;
 +
 +            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&buf.image_sums[0].data));
 +            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&result.data));
 +            args.push_back( std::make_pair( sizeof(cl_ulong), (void *)&templ_sqsum));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.rows));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.cols));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&templ.rows));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&templ.cols));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&buf.image_sums[0].offset));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&buf.image_sums[0].step));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.offset));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.step));
  
              size_t globalThreads[3] = {result.cols, result.rows, 1};
-             size_t localThreads[3]  = {32, 8, 1};
+             size_t localThreads[3]  = {16, 16, 1};
              openCLExecuteKernel(clCxt, &match_template, kernelName, globalThreads, localThreads, args, 1, CV_8U);
          }
  
              CV_Assert(result.rows == image.rows - templ.rows + 1 && result.cols == image.cols - templ.cols + 1);
  
              Context *clCxt = image.clCxt;
 -            string kernelName = "matchTemplate_Naive_SQDIFF";
 -
 -            vector< pair<size_t, const void *> > args;
 -
 -            args.push_back( make_pair( sizeof(cl_mem), (void *)&image.data));
 -            args.push_back( make_pair( sizeof(cl_mem), (void *)&templ.data));
 -            args.push_back( make_pair( sizeof(cl_mem), (void *)&result.data));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&image.rows));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&image.cols));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&templ.rows));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&templ.cols));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.rows));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.cols));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&image.offset));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&templ.offset));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.offset));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&image.step));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&templ.step));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.step));
 +            String kernelName = "matchTemplate_Naive_SQDIFF";
 +
 +            std::vector< std::pair<size_t, const void *> > args;
 +
 +            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&image.data));
 +            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&templ.data));
 +            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&result.data));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&image.rows));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&image.cols));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&templ.rows));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&templ.cols));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.rows));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.cols));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&image.offset));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&templ.offset));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.offset));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&image.step));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&templ.step));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.step));
  
              size_t globalThreads[3] = {result.cols, result.rows, 1};
-             size_t localThreads[3]  = {32, 8, 1};
+             size_t localThreads[3]  = {16, 16, 1};
              openCLExecuteKernel(clCxt, &match_template, kernelName, globalThreads, localThreads, args, image.oclchannels(), image.depth());
          }
  
              unsigned long long templ_sqsum = (unsigned long long)sqrSum(templ.reshape(1))[0];
  
              Context *clCxt = image.clCxt;
 -            string kernelName = "normalizeKernel";
 -            vector< pair<size_t, const void *> > args;
 -
 -            args.push_back( make_pair( sizeof(cl_mem), (void *)&buf.image_sqsums[0].data));
 -            args.push_back( make_pair( sizeof(cl_mem), (void *)&result.data));
 -            args.push_back( make_pair( sizeof(cl_ulong), (void *)&templ_sqsum));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.rows));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.cols));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&templ.rows));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&templ.cols));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&buf.image_sqsums[0].offset));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&buf.image_sqsums[0].step));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.offset));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.step));
 +            String kernelName = "normalizeKernel";
 +            std::vector< std::pair<size_t, const void *> > args;
 +
 +            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&buf.image_sqsums[0].data));
 +            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&result.data));
 +            args.push_back( std::make_pair( sizeof(cl_ulong), (void *)&templ_sqsum));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.rows));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.cols));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&templ.rows));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&templ.cols));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&buf.image_sqsums[0].offset));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&buf.image_sqsums[0].step));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.offset));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.step));
  
              size_t globalThreads[3] = {result.cols, result.rows, 1};
-             size_t localThreads[3]  = {32, 8, 1};
+             size_t localThreads[3]  = {16, 16, 1};
              openCLExecuteKernel(clCxt, &match_template, kernelName, globalThreads, localThreads, args, 1, CV_8U);
          }
  
              CV_Assert(result.rows == image.rows - templ.rows + 1 && result.cols == image.cols - templ.cols + 1);
  
              Context *clCxt = image.clCxt;
 -            string kernelName = "matchTemplate_Naive_CCORR";
 -
 -            vector< pair<size_t, const void *> > args;
 -
 -            args.push_back( make_pair( sizeof(cl_mem), (void *)&image.data));
 -            args.push_back( make_pair( sizeof(cl_mem), (void *)&templ.data));
 -            args.push_back( make_pair( sizeof(cl_mem), (void *)&result.data));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&image.rows));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&image.cols));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&templ.rows));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&templ.cols));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.rows));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.cols));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&image.offset));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&templ.offset));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.offset));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&image.step));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&templ.step));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.step));
 +            String kernelName = "matchTemplate_Naive_CCORR";
 +
 +            std::vector< std::pair<size_t, const void *> > args;
 +
 +            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&image.data));
 +            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&templ.data));
 +            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&result.data));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&image.rows));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&image.cols));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&templ.rows));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&templ.cols));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.rows));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.cols));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&image.offset));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&templ.offset));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.offset));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&image.step));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&templ.step));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.step));
  
              size_t globalThreads[3] = {result.cols, result.rows, 1};
-             size_t localThreads[3]  = {32, 8, 1};
+             size_t localThreads[3]  = {16, 16, 1};
              openCLExecuteKernel(clCxt, &match_template, kernelName, globalThreads, localThreads, args, image.oclchannels(), image.depth());
          }
          //////////////////////////////////////////////////////////////////////
  
              kernelName = "matchTemplate_Prepared_CCOFF";
              size_t globalThreads[3] = {result.cols, result.rows, 1};
-             size_t localThreads[3]  = {32, 8, 1};
+             size_t localThreads[3]  = {16, 16, 1};
  
 -            vector< pair<size_t, const void *> > args;
 -            args.push_back( make_pair( sizeof(cl_mem), (void *)&result.data) );
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&image.rows) );
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&image.cols) );
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&templ.rows) );
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&templ.cols) );
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.rows) );
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.cols) );
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.offset));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.step));
 +            std::vector< std::pair<size_t, const void *> > args;
 +            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&result.data) );
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&image.rows) );
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&image.cols) );
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&templ.rows) );
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&templ.cols) );
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.rows) );
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.cols) );
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.offset));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.step));
+             Vec4f templ_sum = Vec4f::all(0);
              // to be continued in the following section
              if(image.oclchannels() == 1)
              {
                  buf.image_sums.resize(1);
                  integral(image, buf.image_sums[0]);
  
-                 float templ_sum = 0;
-                 templ_sum = (float)sum(templ)[0] / templ.size().area();
+                 templ_sum[0] = (float)sum(templ)[0] / templ.size().area();
 -                args.push_back( make_pair( sizeof(cl_mem),  (void *)&buf.image_sums[0].data) );
 -                args.push_back( make_pair( sizeof(cl_int),  (void *)&buf.image_sums[0].offset) );
 -                args.push_back( make_pair( sizeof(cl_int),  (void *)&buf.image_sums[0].step) );
 -                args.push_back( make_pair( sizeof(cl_float), (void *)&templ_sum[0]) );
 +                args.push_back( std::make_pair( sizeof(cl_mem),  (void *)&buf.image_sums[0].data) );
 +                args.push_back( std::make_pair( sizeof(cl_int),  (void *)&buf.image_sums[0].offset) );
 +                args.push_back( std::make_pair( sizeof(cl_int),  (void *)&buf.image_sums[0].step) );
-                 args.push_back( std::make_pair( sizeof(cl_float), (void *)&templ_sum) );
++                args.push_back( std::make_pair( sizeof(cl_float), (void *)&templ_sum[0]) );
              }
              else
              {
-                 Vec4f templ_sum = Vec4f::all(0);
 -                
++
                  split(image, buf.images);
                  templ_sum = sum(templ) / templ.size().area();
                  buf.image_sums.resize(buf.images.size());
  
              kernelName = "matchTemplate_Prepared_CCOFF_NORMED";
              size_t globalThreads[3] = {result.cols, result.rows, 1};
-             size_t localThreads[3]  = {32, 8, 1};
+             size_t localThreads[3]  = {16, 16, 1};
  
 -            vector< pair<size_t, const void *> > args;
 -            args.push_back( make_pair( sizeof(cl_mem), (void *)&result.data) );
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&image.rows) );
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&image.cols) );
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&templ.rows) );
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&templ.cols) );
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.rows) );
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.cols) );
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.offset));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.step));
 -            args.push_back( make_pair( sizeof(cl_float), (void *)&scale) );
 +            std::vector< std::pair<size_t, const void *> > args;
 +            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&result.data) );
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&image.rows) );
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&image.cols) );
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&templ.rows) );
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&templ.cols) );
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.rows) );
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.cols) );
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.offset));
 +            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.step));
 +            args.push_back( std::make_pair( sizeof(cl_float), (void *)&scale) );
+             Vec4f templ_sum   = Vec4f::all(0);
+             Vec4f templ_sqsum = Vec4f::all(0);
              // to be continued in the following section
              if(image.oclchannels() == 1)
              {
                  buf.image_sums.resize(1);
                  buf.image_sqsums.resize(1);
                  integral(image, buf.image_sums[0], buf.image_sqsums[0]);
-                 float templ_sum = 0;
-                 float templ_sqsum = 0;
-                 templ_sum   = (float)sum(templ)[0];
  
-                 templ_sqsum = sqrSum(templ)[0];
+                 templ_sum[0]   = (float)sum(templ)[0];
  
-                 templ_sqsum -= scale * templ_sum * templ_sum;
-                 templ_sum   *= scale;
+                 templ_sqsum[0] = sqrSum(templ)[0];
+                 templ_sqsum[0] -= scale * templ_sum[0] * templ_sum[0];
+                 templ_sum[0]   *= scale;
  
 -                args.push_back( make_pair( sizeof(cl_mem),  (void *)&buf.image_sums[0].data) );
 -                args.push_back( make_pair( sizeof(cl_int),  (void *)&buf.image_sums[0].offset) );
 -                args.push_back( make_pair( sizeof(cl_int),  (void *)&buf.image_sums[0].step) );
 -                args.push_back( make_pair( sizeof(cl_mem),  (void *)&buf.image_sqsums[0].data) );
 -                args.push_back( make_pair( sizeof(cl_int),  (void *)&buf.image_sqsums[0].offset) );
 -                args.push_back( make_pair( sizeof(cl_int),  (void *)&buf.image_sqsums[0].step) );
 -                args.push_back( make_pair( sizeof(cl_float), (void *)&templ_sum[0]) );
 -                args.push_back( make_pair( sizeof(cl_float), (void *)&templ_sqsum[0]) );
 +                args.push_back( std::make_pair( sizeof(cl_mem),  (void *)&buf.image_sums[0].data) );
 +                args.push_back( std::make_pair( sizeof(cl_int),  (void *)&buf.image_sums[0].offset) );
 +                args.push_back( std::make_pair( sizeof(cl_int),  (void *)&buf.image_sums[0].step) );
 +                args.push_back( std::make_pair( sizeof(cl_mem),  (void *)&buf.image_sqsums[0].data) );
 +                args.push_back( std::make_pair( sizeof(cl_int),  (void *)&buf.image_sqsums[0].offset) );
 +                args.push_back( std::make_pair( sizeof(cl_int),  (void *)&buf.image_sqsums[0].step) );
-                 args.push_back( std::make_pair( sizeof(cl_float), (void *)&templ_sum) );
-                 args.push_back( std::make_pair( sizeof(cl_float), (void *)&templ_sqsum) );
++                args.push_back( std::make_pair( sizeof(cl_float), (void *)&templ_sum[0]) );
++                args.push_back( std::make_pair( sizeof(cl_float), (void *)&templ_sqsum[0]) );
              }
              else
              {
              }
              openCLExecuteKernel(clCxt, &match_template, kernelName, globalThreads, localThreads, args, image.oclchannels(), image.depth());
          }
 -            string kernelName;
+         void extractFirstChannel_32F(const oclMat &image, oclMat &result)
+         {
+             Context *clCxt = image.clCxt;
 -            vector< pair<size_t, const void *> > args;
 -            args.push_back( make_pair( sizeof(cl_mem), (void *)&image.data) );
 -            args.push_back( make_pair( sizeof(cl_mem), (void *)&result.data) );
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.rows) );
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.cols) );
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&image.offset));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.offset));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&image.step));
 -            args.push_back( make_pair( sizeof(cl_int), (void *)&result.step));
++            String kernelName;
+             kernelName = "extractFirstChannel";
+             size_t globalThreads[3] = {result.cols, result.rows, 1};
+             size_t localThreads[3]  = {16, 16, 1};
++            std::vector< std::pair<size_t, const void *> > args;
++            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&image.data) );
++            args.push_back( std::make_pair( sizeof(cl_mem), (void *)&result.data) );
++            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.rows) );
++            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.cols) );
++            args.push_back( std::make_pair( sizeof(cl_int), (void *)&image.offset));
++            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.offset));
++            args.push_back( std::make_pair( sizeof(cl_int), (void *)&image.step));
++            args.push_back( std::make_pair( sizeof(cl_int), (void *)&result.step));
  
+             openCLExecuteKernel(clCxt, &match_template, kernelName, globalThreads, localThreads, args, -1, -1);
+         }
      }/*ocl*/
  } /*cv*/
  
@@@ -292,55 -283,39 +283,39 @@@ static void ocl_cvMoments( const void* 
      int tile_height = std::min(size.height,TILE_SIZE);
      size_t localThreads[3]  = { tile_height, 1, 1};
      size_t globalThreads[3] = { size.height, blockx, 1};
 -    vector<pair<size_t , const void *> > args,args_sum;
 -    args.push_back( make_pair( sizeof(cl_mem) , (void *)&src.data ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&src.rows ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&src.cols ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&src.step ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&tileSize.width ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&tileSize.height ));
 -    args.push_back( make_pair( sizeof(cl_mem) , (void *)&dst_m.data ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&dst_m.cols ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&dst_m.step ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&blocky ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&type ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&depth ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&cn ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&coi ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&binary ));
 -    args.push_back( make_pair( sizeof(cl_int) , (void *)&TILE_SIZE ));
 +    std::vector<std::pair<size_t , const void *> > args,args_sum;
 +    args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&src.data ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.rows ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.cols ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.step ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&tileSize.width ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&tileSize.height ));
-     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst_m00.data ));
-     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst_m10.data ));
-     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst_m01.data ));
-     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst_m20.data ));
-     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst_m11.data ));
-     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst_m02.data ));
-     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst_m30.data ));
-     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst_m21.data ));
-     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst_m12.data ));
-     args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst_m03.data ));
-     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst_m00.cols ));
-     args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst_m00.step ));
++    args.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst_m.data ));
++    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst_m.cols ));
++    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst_m.step ));
++    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&blocky ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&type ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&depth ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&cn ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&coi ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&binary ));
 +    args.push_back( std::make_pair( sizeof(cl_int) , (void *)&TILE_SIZE ));
-     openCLExecuteKernel(dst_m00.clCxt, &moments, "CvMoments", globalThreads, localThreads, args, -1, depth);
+     openCLExecuteKernel(dst_m.clCxt, &moments, "CvMoments", globalThreads, localThreads, args, -1, depth);
  
      size_t localThreadss[3]  = { 128, 1, 1};
      size_t globalThreadss[3] = { 128, 1, 1};
 -    args_sum.push_back( make_pair( sizeof(cl_int) , (void *)&src.rows ));
 -    args_sum.push_back( make_pair( sizeof(cl_int) , (void *)&src.cols ));
 -    args_sum.push_back( make_pair( sizeof(cl_int) , (void *)&tile_height ));
 -    args_sum.push_back( make_pair( sizeof(cl_int) , (void *)&tile_width ));
 -    args_sum.push_back( make_pair( sizeof(cl_int) , (void *)&TILE_SIZE ));
 -    args_sum.push_back( make_pair( sizeof(cl_mem) , (void *)&sum ));
 -    args_sum.push_back( make_pair( sizeof(cl_mem) , (void *)&dst_m.data ));
 -    args_sum.push_back( make_pair( sizeof(cl_int) , (void *)&dst_m.step ));
 +    args_sum.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.rows ));
 +    args_sum.push_back( std::make_pair( sizeof(cl_int) , (void *)&src.cols ));
 +    args_sum.push_back( std::make_pair( sizeof(cl_int) , (void *)&tile_height ));
 +    args_sum.push_back( std::make_pair( sizeof(cl_int) , (void *)&tile_width ));
 +    args_sum.push_back( std::make_pair( sizeof(cl_int) , (void *)&TILE_SIZE ));
 +    args_sum.push_back( std::make_pair( sizeof(cl_mem) , (void *)&sum ));
-     args_sum.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst_m00.data ));
-     args_sum.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst_m10.data ));
-     args_sum.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst_m01.data ));
-     args_sum.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst_m20.data ));
-     args_sum.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst_m11.data ));
-     args_sum.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst_m02.data ));
-     args_sum.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst_m30.data ));
-     args_sum.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst_m21.data ));
-     args_sum.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst_m12.data ));
-     args_sum.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst_m03.data ));
-     openCLExecuteKernel(dst_m00.clCxt, &moments, "dst_sum", globalThreadss, localThreadss, args_sum, -1, -1);
++    args_sum.push_back( std::make_pair( sizeof(cl_mem) , (void *)&dst_m.data ));
++    args_sum.push_back( std::make_pair( sizeof(cl_int) , (void *)&dst_m.step ));
+     openCLExecuteKernel(dst_m.clCxt, &moments, "dst_sum", globalThreadss, localThreadss, args_sum, -1, -1);
      double* dstsum = new double[10];
      memset(dstsum,0,10*sizeof(double));
-     openCLReadBuffer(dst_m00.clCxt,sum,(void *)dstsum,10*sizeof(double));
+     openCLReadBuffer(dst_m.clCxt,sum,(void *)dstsum,10*sizeof(double));
      mom->m00 = dstsum[0];
      mom->m10 = dstsum[1];
      mom->m01 = dstsum[2];
@@@ -915,39 -864,39 +864,39 @@@ __kernel void CvMoments_D6(__global F* 
                  mom[mt] *= s;
          }
  
-         double xm = x * mom[0], ym = y * mom[0];
+         F xm = x * mom[0], ym = y * mom[0];
  
          // accumulate moments computed in each tile
+         dst_step /= sizeof(F);
  
          // + m00 ( = m00' )
-         dst_m00[wgidy*dst_cols+wgidx] = mom[0];
+         *(dst_m + mad24(DST_ROW_00 * blocky, dst_step, mad24(wgidy, dst_cols, wgidx))) = mom[0];
  
          // + m10 ( = m10' + x*m00' )
-         dst_m10[wgidy*dst_cols+wgidx] = mom[1] + xm;
+         *(dst_m + mad24(DST_ROW_10 * blocky, dst_step, mad24(wgidy, dst_cols, wgidx))) = mom[1] + xm;
  
          // + m01 ( = m01' + y*m00' )
-         dst_m01[wgidy*dst_cols+wgidx] = mom[2] + ym;
+         *(dst_m + mad24(DST_ROW_01 * blocky, dst_step, mad24(wgidy, dst_cols, wgidx))) = mom[2] + ym;
  
          // + m20 ( = m20' + 2*x*m10' + x*x*m00' )
-         dst_m20[wgidy*dst_cols+wgidx]  = mom[3] + x * (mom[1] * 2 + xm);
+         *(dst_m + mad24(DST_ROW_20 * blocky, dst_step, mad24(wgidy, dst_cols, wgidx))) = mom[3] + x * (mom[1] * 2 + xm);
  
          // + m11 ( = m11' + x*m01' + y*m10' + x*y*m00' )
-         dst_m11[wgidy*dst_cols+wgidx]  = mom[4] + x * (mom[2] + ym) + y * mom[1];
+         *(dst_m + mad24(DST_ROW_11 * blocky, dst_step, mad24(wgidy, dst_cols, wgidx))) = mom[4] + x * (mom[2] + ym) + y * mom[1];
  
          // + m02 ( = m02' + 2*y*m01' + y*y*m00' )
-         dst_m02[wgidy*dst_cols+wgidx]  = mom[5] + y * (mom[2] * 2 + ym);
+         *(dst_m + mad24(DST_ROW_02 * blocky, dst_step, mad24(wgidy, dst_cols, wgidx))) = mom[5] + y * (mom[2] * 2 + ym);
  
          // + m30 ( = m30' + 3*x*m20' + 3*x*x*m10' + x*x*x*m00' )
-         dst_m30[wgidy*dst_cols+wgidx]  = mom[6] + x * (3. * mom[3] + x * (3. * mom[1] + xm));
+         *(dst_m + mad24(DST_ROW_30 * blocky, dst_step, mad24(wgidy, dst_cols, wgidx))) = mom[6] + x * (3. * mom[3] + x * (3. * mom[1] + xm));
  
          // + m21 ( = m21' + x*(2*m11' + 2*y*m10' + x*m01' + x*y*m00') + y*m20')
-         dst_m21[wgidy*dst_cols+wgidx]  = mom[7] + x * (2 * (mom[4] + y * mom[1]) + x * (mom[2] + ym)) + y * mom[3];
+         *(dst_m + mad24(DST_ROW_21 * blocky, dst_step, mad24(wgidy, dst_cols, wgidx))) = mom[7] + x * (2 * (mom[4] + y * mom[1]) + x * (mom[2] + ym)) + y * mom[3];
  
          // + m12 ( = m12' + y*(2*m11' + 2*x*m01' + y*m10' + x*y*m00') + x*m02')
-         dst_m12[wgidy*dst_cols+wgidx]  = mom[8] + y * (2 * (mom[4] + x * mom[2]) + y * (mom[1] + xm)) + x * mom[5];
+         *(dst_m + mad24(DST_ROW_12 * blocky, dst_step, mad24(wgidy, dst_cols, wgidx))) = mom[8] + y * (2 * (mom[4] + x * mom[2]) + y * (mom[1] + xm)) + x * mom[5];
  
          // + m03 ( = m03' + 3*y*m02' + 3*y*y*m01' + y*y*y*m00' )
-         dst_m03[wgidy*dst_cols+wgidx]  = mom[9] + y * (3. * mom[5] + y * (3. * mom[2] + ym));
+         *(dst_m + mad24(DST_ROW_03 * blocky, dst_step, mad24(wgidy, dst_cols, wgidx))) = mom[9] + y * (3. * mom[5] + y * (3. * mom[2] + ym));
      }
 -}
 +}
- //#endif
Simple merge
Simple merge
@@@ -39,9 -39,9 +39,8 @@@
  // the use of this software, even if advised of the possibility of such damage.
  //
  //M*/
  #include "precomp.hpp"
  
 -using namespace std;
  using namespace cv;
  using namespace cv::gpu;
  using namespace cv::superres;
Simple merge
Simple merge
Simple merge
@@@ -80,6 -80,35 +80,35 @@@ foreach(m ${OPENCV_MODULE_${the_module}
    endforeach()
  endforeach()
  
 -      
+ macro(ios_include_3party_libs)
+   foreach(l ${ARGN})
+     add_dependencies(${the_module} ${l})
+     string(REGEX REPLACE "<MODULE_NAME>" "${l}" objpath1 "${CMAKE_BINARY_DIR}/3rdparty/${l}/${objpath0}")
+     file(GLOB sources ${CMAKE_SOURCE_DIR}/3rdparty/${l}/*.c)
+     foreach(srcname ${sources})
+       if(IS_ABSOLUTE "${srcname}")
+         file(RELATIVE_PATH srcname "${CMAKE_SOURCE_DIR}/3rdparty/${l}" "${srcname}")
+       endif()
+       string(REPLACE ".." "__" srcname "${srcname}")
+       get_filename_component(srcname_we ${srcname} NAME_WE)
+       string(REGEX REPLACE <SRC_NAME_WE> "${srcname_we}" objpath2 "${objpath1}")
+       string(REGEX REPLACE <RELATIVE_SRC_NAME> "${srcname}" objpath3 "${objpath2}")
 -  endforeach() 
++
+       list(APPEND objlist "\"${objpath3}\"")
+     endforeach() # (srcname ${sources})
 -endif() 
++  endforeach()
+ endmacro()
+ if(IOS AND WITH_PNG)
+   ios_include_3party_libs(zlib libpng)
 -endif() 
++endif()
+ if(IOS AND WITH_JPEG)
+   ios_include_3party_libs(libjpeg)
++endif()
  string(REPLACE ";" " " objlist "${objlist}")
  
  if(have_cfg)
Simple merge