Merge remote-tracking branch 'origin/2.4'
authorRoman Donchenko <roman.donchenko@itseez.com>
Tue, 6 Aug 2013 09:56:49 +0000 (13:56 +0400)
committerRoman Donchenko <roman.donchenko@itseez.com>
Tue, 6 Aug 2013 09:56:49 +0000 (13:56 +0400)
Conflicts:
3rdparty/ffmpeg/ffmpeg_version.cmake
cmake/OpenCVFindLibsGrfmt.cmake
cmake/templates/cvconfig.h.cmake
modules/bioinspired/doc/retina/index.rst
modules/calib3d/doc/camera_calibration_and_3d_reconstruction.rst
modules/calib3d/src/precomp.hpp
modules/contrib/src/inputoutput.cpp
modules/contrib/src/precomp.hpp
modules/core/include/opencv2/core/internal.hpp
modules/core/include/opencv2/core/types_c.h
modules/core/src/drawing.cpp
modules/core/src/precomp.hpp
modules/core/src/system.cpp
modules/features2d/doc/common_interfaces_of_descriptor_matchers.rst
modules/features2d/doc/common_interfaces_of_feature_detectors.rst
modules/features2d/include/opencv2/features2d/features2d.hpp
modules/features2d/src/precomp.hpp
modules/flann/src/precomp.hpp
modules/gpu/doc/camera_calibration_and_3d_reconstruction.rst
modules/gpu/doc/image_filtering.rst
modules/gpu/doc/image_processing.rst
modules/gpu/doc/video.rst
modules/gpu/perf/perf_imgproc.cpp
modules/gpu/perf4au/main.cpp
modules/gpu/src/imgproc.cpp
modules/gpu/src/precomp.hpp
modules/gpu/test/test_imgproc.cpp
modules/highgui/CMakeLists.txt
modules/highgui/test/test_precomp.hpp
modules/imgproc/doc/structural_analysis_and_shape_descriptors.rst
modules/imgproc/src/precomp.hpp
modules/java/generator/src/cpp/Mat.cpp
modules/legacy/src/precomp.hpp
modules/ml/doc/k_nearest_neighbors.rst
modules/ml/src/precomp.hpp
modules/nonfree/doc/feature_detection.rst
modules/nonfree/src/precomp.hpp
modules/objdetect/include/opencv2/objdetect/objdetect.hpp
modules/objdetect/src/cascadedetect.cpp
modules/objdetect/src/hog.cpp
modules/objdetect/src/precomp.hpp
modules/objdetect/test/test_latentsvmdetector.cpp
modules/ocl/src/hog.cpp
modules/ocl/src/opencl/objdetect_hog.cl
modules/ocl/src/precomp.hpp
modules/photo/src/precomp.hpp
modules/stitching/src/precomp.hpp
modules/superres/perf/perf_precomp.hpp
modules/superres/src/optical_flow.cpp
modules/superres/src/precomp.hpp
modules/superres/test/test_precomp.hpp
modules/ts/include/opencv2/ts.hpp
modules/video/src/precomp.hpp
modules/videostab/src/precomp.hpp
modules/world/src/precomp.hpp

82 files changed:
1  2 
.gitignore
3rdparty/ffmpeg/ffmpeg_version.cmake
CMakeLists.txt
cmake/OpenCVFindLibsGrfmt.cmake
cmake/OpenCVFindLibsVideo.cmake
cmake/OpenCVModule.cmake
cmake/templates/cvconfig.h.cmake
doc/tutorials/introduction/windows_install/windows_install.rst
modules/bioinspired/doc/retina/index.rst
modules/calib3d/doc/camera_calibration_and_3d_reconstruction.rst
modules/contrib/doc/facerec/facerec_api.rst
modules/contrib/src/inputoutput.cpp
modules/core/CMakeLists.txt
modules/core/doc/basic_structures.rst
modules/core/doc/clustering.rst
modules/core/doc/core.rst
modules/core/doc/drawing_functions.rst
modules/core/doc/operations_on_arrays.rst
modules/core/doc/xml_yaml_persistence.rst
modules/core/include/opencv2/core/cvdef.h
modules/core/src/alloc.cpp
modules/core/src/drawing.cpp
modules/core/src/persistence.cpp
modules/core/src/rand.cpp
modules/core/src/system.cpp
modules/features2d/doc/common_interfaces_of_descriptor_extractors.rst
modules/features2d/doc/common_interfaces_of_descriptor_matchers.rst
modules/features2d/doc/common_interfaces_of_feature_detectors.rst
modules/features2d/doc/feature_detection_and_description.rst
modules/features2d/doc/object_categorization.rst
modules/flann/include/opencv2/flann/dist.h
modules/flann/src/precomp.hpp
modules/gpu/doc/object_detection.rst
modules/gpu/perf4au/main.cpp
modules/gpubgsegm/doc/background_segmentation.rst
modules/gpucodec/doc/videodec.rst
modules/gpucodec/doc/videoenc.rst
modules/gpufilters/doc/filtering.rst
modules/gpuimgproc/doc/color.rst
modules/gpuimgproc/doc/hough.rst
modules/gpuimgproc/src/cuda/hist.cu
modules/gpuimgproc/src/histogram.cpp
modules/gpuimgproc/test/test_histogram.cpp
modules/gpuoptflow/doc/optflow.rst
modules/gpustereo/doc/stereo.rst
modules/highgui/CMakeLists.txt
modules/highgui/doc/reading_and_writing_images_and_video.rst
modules/highgui/doc/user_interface.rst
modules/highgui/src/grfmt_jpeg2000.cpp
modules/highgui/src/grfmt_png.cpp
modules/imgproc/doc/feature_detection.rst
modules/imgproc/doc/filtering.rst
modules/imgproc/doc/geometric_transformations.rst
modules/imgproc/doc/histograms.rst
modules/imgproc/doc/miscellaneous_transformations.rst
modules/imgproc/doc/object_detection.rst
modules/imgproc/doc/structural_analysis_and_shape_descriptors.rst
modules/imgproc/perf/perf_cvt_color.cpp
modules/imgproc/perf/perf_resize.cpp
modules/imgproc/src/color.cpp
modules/java/android_test/src/org/opencv/test/core/CoreTest.java
modules/java/generator/src/cpp/Mat.cpp
modules/ml/doc/k_nearest_neighbors.rst
modules/ml/doc/support_vector_machines.rst
modules/ml/src/precomp.hpp
modules/nonfree/doc/feature_detection.rst
modules/objdetect/doc/cascade_classification.rst
modules/objdetect/include/opencv2/objdetect.hpp
modules/objdetect/src/cascadedetect.cpp
modules/objdetect/src/hog.cpp
modules/ocl/doc/image_processing.rst
modules/ocl/doc/object_detection.rst
modules/ocl/src/hog.cpp
modules/ocl/src/opencl/objdetect_hog.cl
modules/photo/doc/inpainting.rst
modules/stitching/doc/high_level.rst
modules/superres/include/opencv2/superres/optical_flow.hpp
modules/superres/perf/perf_superres_ocl.cpp
modules/superres/src/optical_flow.cpp
modules/ts/include/opencv2/ts.hpp
modules/video/doc/motion_analysis_and_object_tracking.rst
modules/videostab/src/clp.hpp

diff --cc .gitignore
Simple merge
@@@ -1,5 -1,3 +1,4 @@@
- set(NEW_FFMPEG 1)
 +set(HAVE_FFMPEG 1)
  set(HAVE_FFMPEG_CODEC 1)
  set(HAVE_FFMPEG_FORMAT 1)
  set(HAVE_FFMPEG_UTIL 1)
diff --cc CMakeLists.txt
Simple merge
@@@ -73,55 -75,20 +75,56 @@@ if(WITH_JPEG
    else()
      include(FindJPEG)
    endif()
- endif()
  
if(WITH_JPEG AND NOT JPEG_FOUND)
-   ocv_clear_vars(JPEG_LIBRARY JPEG_LIBRARIES JPEG_INCLUDE_DIR)
  if(NOT JPEG_FOUND)
+     ocv_clear_vars(JPEG_LIBRARY JPEG_LIBRARIES JPEG_INCLUDE_DIR)
  
-   set(JPEG_LIBRARY libjpeg)
-   set(JPEG_LIBRARIES ${JPEG_LIBRARY})
-   add_subdirectory("${OpenCV_SOURCE_DIR}/3rdparty/libjpeg")
-   set(JPEG_INCLUDE_DIR "${${JPEG_LIBRARY}_SOURCE_DIR}")
- endif()
+     set(JPEG_LIBRARY libjpeg)
+     set(JPEG_LIBRARIES ${JPEG_LIBRARY})
+     add_subdirectory("${OpenCV_SOURCE_DIR}/3rdparty/libjpeg")
+     set(JPEG_INCLUDE_DIR "${${JPEG_LIBRARY}_SOURCE_DIR}")
  endif()
  
- ocv_parse_header("${JPEG_INCLUDE_DIR}/jpeglib.h" JPEG_VERSION_LINES JPEG_LIB_VERSION)
+   ocv_parse_header("${JPEG_INCLUDE_DIR}/jpeglib.h" JPEG_VERSION_LINES JPEG_LIB_VERSION)
+   set(HAVE_JPEG YES)
+ endif()
  
 +# --- libwebp (optional) ---
 +
 +if(WITH_WEBP)
 +  if(BUILD_WEBP)
 +    ocv_clear_vars(WEBP_FOUND WEBP_LIBRARY WEBP_LIBRARIES WEBP_INCLUDE_DIR)
 +  else()
 +    include(cmake/OpenCVFindWebP.cmake)
 +  endif()
 +endif()
 +
 +# --- Add libwebp to 3rdparty/libwebp and compile it if not available ---
 +if(WITH_WEBP AND NOT WEBP_FOUND)
 +
 +  set(WEBP_LIBRARY libwebp)
 +  set(WEBP_LIBRARIES ${WEBP_LIBRARY})
 +
 +  add_subdirectory("${OpenCV_SOURCE_DIR}/3rdparty/libwebp")
 +  set(WEBP_INCLUDE_DIR "${${WEBP_LIBRARY}_SOURCE_DIR}")
 +endif()
 +
 +if(NOT WEBP_VERSION AND WEBP_INCLUDE_DIR)
 +  ocv_clear_vars(ENC_MAJ_VERSION ENC_MIN_VERSION ENC_REV_VERSION)
 +  if(EXISTS "${WEBP_INCLUDE_DIR}/enc/vp8enci.h")
 +    ocv_parse_header("${WEBP_INCLUDE_DIR}/enc/vp8enci.h" WEBP_VERSION_LINES ENC_MAJ_VERSION ENC_MIN_VERSION ENC_REV_VERSION)
 +    set(WEBP_VERSION "${ENC_MAJ_VERSION}.${ENC_MIN_VERSION}.${ENC_REV_VERSION}")
 +  elseif(EXISTS "${WEBP_INCLUDE_DIR}/webp/encode.h")
 +    file(STRINGS "${WEBP_INCLUDE_DIR}/webp/encode.h" WEBP_ENCODER_ABI_VERSION REGEX "#define[ \t]+WEBP_ENCODER_ABI_VERSION[ \t]+([x0-9a-f]+)" )
 +    if(WEBP_ENCODER_ABI_VERSION MATCHES "#define[ \t]+WEBP_ENCODER_ABI_VERSION[ \t]+([x0-9a-f]+)")
 +        set(WEBP_ENCODER_ABI_VERSION "${CMAKE_MATCH_1}")
 +        set(WEBP_VERSION "encoder: ${WEBP_ENCODER_ABI_VERSION}")
 +    else()
 +      unset(WEBP_ENCODER_ABI_VERSION)
 +    endif()
 +  endif()
 +endif()
 +
  # --- libjasper (optional, should be searched after libjpeg) ---
  if(WITH_JASPER)
    if(BUILD_JASPER)
Simple merge
Simple merge
  /* Carbon windowing environment */
  #cmakedefine HAVE_CARBON
  
+ /* AMD's Basic Linear Algebra Subprograms Library*/
+ #cmakedefine HAVE_CLAMDBLAS
+ /* AMD's OpenCL Fast Fourier Transform Library*/
+ #cmakedefine HAVE_CLAMDFFT
++/* Clp support */
++#cmakedefine HAVE_CLP
++
+ /* Cocoa API */
+ #cmakedefine HAVE_COCOA
+ /* C= */
+ #cmakedefine HAVE_CSTRIPES
+ /* NVidia Cuda Basic Linear Algebra Subprograms (BLAS) API*/
+ #cmakedefine HAVE_CUBLAS
+ /* NVidia Cuda Runtime API*/
+ #cmakedefine HAVE_CUDA
+ /* NVidia Cuda Fast Fourier Transform (FFT) API*/
+ #cmakedefine HAVE_CUFFT
  /* IEEE1394 capturing support */
  #cmakedefine HAVE_DC1394
  
  /* IEEE1394 capturing support - libdc1394 v2.x */
  #cmakedefine HAVE_DC1394_2
  
- /* ffmpeg in Gentoo */
- #cmakedefine HAVE_GENTOO_FFMPEG
+ /* DirectShow Video Capture library */
+ #cmakedefine HAVE_DSHOW
  
- /* FFMpeg video library */
- #cmakedefine  HAVE_FFMPEG
+ /* Eigen Matrix & Linear Algebra Library */
+ #cmakedefine HAVE_EIGEN
  
- /* FFMpeg version flag */
- #cmakedefine  NEW_FFMPEG
+ /* FFMpeg video library */
+ #cmakedefine HAVE_FFMPEG
  
  /* ffmpeg's libswscale */
- #cmakedefine  HAVE_FFMPEG_SWSCALE
+ #cmakedefine HAVE_FFMPEG_SWSCALE
+ /* ffmpeg in Gentoo */
+ #cmakedefine HAVE_GENTOO_FFMPEG
  
  /* GStreamer multimedia framework */
- #cmakedefine  HAVE_GSTREAMER
+ #cmakedefine HAVE_GSTREAMER
  
  /* GTK+ 2.0 Thread support */
- #cmakedefine  HAVE_GTHREAD
- /* Win32 UI */
- #cmakedefine HAVE_WIN32UI
+ #cmakedefine HAVE_GTHREAD
  
 -/* Windows Runtime support */
 -#cmakedefine HAVE_WINRT
 -
 -/* Win32 UI */
 -#cmakedefine HAVE_WIN32UI
 -
  /* GTK+ 2.x toolkit */
- #cmakedefine  HAVE_GTK
- /* OpenEXR codec */
- #cmakedefine  HAVE_ILMIMF
+ #cmakedefine HAVE_GTK
  
 -/* Apple ImageIO Framework */
 -#cmakedefine HAVE_IMAGEIO
 +/* Define to 1 if you have the <inttypes.h> header file. */
- #cmakedefine  HAVE_INTTYPES_H 1
++#cmakedefine HAVE_INTTYPES_H 1
+ /* Intel Integrated Performance Primitives */
+ #cmakedefine HAVE_IPP
  
  /* JPEG-2000 codec */
- #cmakedefine  HAVE_JASPER
+ #cmakedefine HAVE_JASPER
  
  /* IJG JPEG codec */
- #cmakedefine  HAVE_JPEG
- /* Define to 1 if you have the `dl' library (-ldl). */
- #cmakedefine  HAVE_LIBDL 1
- /* Define to 1 if you have the `gomp' library (-lgomp). */
- #cmakedefine  HAVE_LIBGOMP 1
- /* Define to 1 if you have the `m' library (-lm). */
- #cmakedefine  HAVE_LIBM 1
+ #cmakedefine HAVE_JPEG
  
  /* libpng/png.h needs to be included */
- #cmakedefine  HAVE_LIBPNG_PNG_H
+ #cmakedefine HAVE_LIBPNG_PNG_H
  
- /* Define to 1 if you have the `pthread' library (-lpthread). */
- #cmakedefine  HAVE_LIBPTHREAD 1
- /* Define to 1 if you have the `lrint' function. */
- #cmakedefine  HAVE_LRINT 1
- /* PNG codec */
- #cmakedefine  HAVE_PNG
- /* Define to 1 if you have the `png_get_valid' function. */
- #cmakedefine  HAVE_PNG_GET_VALID 1
- /* png.h needs to be included */
- #cmakedefine  HAVE_PNG_H
- /* Define to 1 if you have the `png_set_tRNS_to_alpha' function. */
- #cmakedefine  HAVE_PNG_SET_TRNS_TO_ALPHA 1
- /* QuickTime video libraries */
- #cmakedefine  HAVE_QUICKTIME
+ /* V4L/V4L2 capturing support via libv4l */
+ #cmakedefine HAVE_LIBV4L
  
- /* AVFoundation video libraries */
- #cmakedefine  HAVE_AVFOUNDATION
+ /* Microsoft Media Foundation Capture library */
+ #cmakedefine HAVE_MSMF
  
- /* TIFF codec */
- #cmakedefine  HAVE_TIFF
+ /* NVidia Video Decoding API*/
+ #cmakedefine HAVE_NVCUVID
  
- /* Unicap video capture library */
- #cmakedefine  HAVE_UNICAP
+ /* OpenCL Support */
+ #cmakedefine HAVE_OPENCL
  
- /* Define to 1 if you have the <unistd.h> header file. */
- #cmakedefine  HAVE_UNISTD_H 1
+ /* OpenEXR codec */
+ #cmakedefine HAVE_OPENEXR
  
- /* Xine video library */
- #cmakedefine  HAVE_XINE
+ /* OpenGL support*/
+ #cmakedefine HAVE_OPENGL
  
  /* OpenNI library */
- #cmakedefine  HAVE_OPENNI
- /* LZ77 compression/decompression library (used for PNG) */
- #cmakedefine  HAVE_ZLIB
- /* Intel Integrated Performance Primitives */
- #cmakedefine  HAVE_IPP
- /* OpenCV compiled as static or dynamic libs */
- #cmakedefine  BUILD_SHARED_LIBS
- /* Name of package */
- #define  PACKAGE "${PACKAGE}"
+ #cmakedefine HAVE_OPENNI
  
- /* Define to the address where bug reports for this package should be sent. */
- #define  PACKAGE_BUGREPORT "${PACKAGE_BUGREPORT}"
- /* Define to the full name of this package. */
- #define  PACKAGE_NAME "${PACKAGE_NAME}"
- /* Define to the full name and version of this package. */
- #define  PACKAGE_STRING "${PACKAGE_STRING}"
- /* Define to the one symbol short name of this package. */
- #define  PACKAGE_TARNAME "${PACKAGE_TARNAME}"
- /* Define to the version of this package. */
- #define  PACKAGE_VERSION "${PACKAGE_VERSION}"
+ /* PNG codec */
+ #cmakedefine HAVE_PNG
  
- /* If using the C implementation of alloca, define if you know the
-    direction of stack growth for your system; otherwise it will be
-    automatically deduced at runtime.
-     STACK_DIRECTION > 0 => grows toward higher addresses
-     STACK_DIRECTION < 0 => grows toward lower addresses
-     STACK_DIRECTION = 0 => direction of growth unknown */
- #cmakedefine  STACK_DIRECTION
+ /* Qt support */
+ #cmakedefine HAVE_QT
  
- /* Version number of package */
- #define  VERSION "${PACKAGE_VERSION}"
+ /* Qt OpenGL support */
+ #cmakedefine HAVE_QT_OPENGL
  
- /* Define to 1 if your processor stores words with the most significant byte
-    first (like Motorola and SPARC, unlike Intel and VAX). */
- #cmakedefine  WORDS_BIGENDIAN
+ /* QuickTime video libraries */
+ #cmakedefine HAVE_QUICKTIME
  
  /* Intel Threading Building Blocks */
- #cmakedefine  HAVE_TBB
- /* C= */
- #cmakedefine  HAVE_CSTRIPES
- /* Eigen Matrix & Linear Algebra Library */
- #cmakedefine  HAVE_EIGEN
- /* NVidia Cuda Runtime API*/
- #cmakedefine HAVE_CUDA
- /* NVidia Cuda Fast Fourier Transform (FFT) API*/
- #cmakedefine HAVE_CUFFT
- /* NVidia Cuda Basic Linear Algebra Subprograms (BLAS) API*/
- #cmakedefine HAVE_CUBLAS
+ #cmakedefine HAVE_TBB
  
- /* NVidia Video Decoding API*/
- #cmakedefine HAVE_NVCUVID
- /* Compile for 'real' NVIDIA GPU architectures */
- #define CUDA_ARCH_BIN "${OPENCV_CUDA_ARCH_BIN}"
- /* Compile for 'virtual' NVIDIA PTX architectures */
- #define CUDA_ARCH_PTX "${OPENCV_CUDA_ARCH_PTX}"
- /* NVIDIA GPU features are used */
- #define CUDA_ARCH_FEATURES "${OPENCV_CUDA_ARCH_FEATURES}"
- /* Create PTX or BIN for 1.0 compute capability */
- #cmakedefine CUDA_ARCH_BIN_OR_PTX_10
+ /* TIFF codec */
+ #cmakedefine HAVE_TIFF
  
- /* OpenCL Support */
- #cmakedefine HAVE_OPENCL
+ /* Unicap video capture library */
+ #cmakedefine HAVE_UNICAP
  
- /* AMD's OpenCL Fast Fourier Transform Library*/
- #cmakedefine HAVE_CLAMDFFT
+ /* Video for Windows support */
+ #cmakedefine HAVE_VFW
  
- /* AMD's Basic Linear Algebra Subprograms Library*/
- #cmakedefine HAVE_CLAMDBLAS
+ /* V4L2 capturing support in videoio.h */
+ #cmakedefine HAVE_VIDEOIO
  
- /* DirectShow Video Capture library */
- #cmakedefine HAVE_DSHOW
+ /* Win32 UI */
+ #cmakedefine HAVE_WIN32UI
  
- /* Microsoft Media Foundation Capture library */
- #cmakedefine HAVE_MSMF
++/* Windows Runtime support */
++#cmakedefine HAVE_WINRT
 +
  /* XIMEA camera support */
  #cmakedefine HAVE_XIMEA
  
index 608a935,0000000..9c1ae57
mode 100644,000000..100644
--- /dev/null
@@@ -1,487 -1,0 +1,493 @@@
 +Retina : a Bio mimetic human retina model
 +*****************************************
 +
 +.. highlight:: cpp
 +
 +Retina
 +======
 +.. ocv:class:: Retina : public Algorithm
 +
 +**Note** : do not forget that the retina model is included in the following namespace : *cv::bioinspired*.
 +
 +Introduction
 +++++++++++++
 +
 +Class which provides the main controls to the Gipsa/Listic labs human  retina model. This is a non separable spatio-temporal filter modelling the two main retina information channels :
 +
 +* foveal vision for detailled color vision : the parvocellular pathway.
 +
 +* peripheral vision for sensitive transient signals detection (motion and events) : the magnocellular pathway.
 +
 +From a general point of view, this filter whitens the image spectrum and corrects luminance thanks to local adaptation. An other important property is its hability to filter out spatio-temporal noise while enhancing details.
 +This model originates from Jeanny Herault work [Herault2010]_. It has been involved in Alexandre Benoit phd and his current research [Benoit2010]_, [Strat2013]_ (he currently maintains this module within OpenCV). It includes the work of other Jeanny's phd student such as [Chaix2007]_ and the log polar transformations of Barthelemy Durette described in Jeanny's book.
 +
 +**NOTES :**
 +
 +* For ease of use in computer vision applications, the two retina channels are applied homogeneously on all the input images. This does not follow the real retina topology but this can still be done using the log sampling capabilities proposed within the class.
 +
 +* Extend the retina description and code use in the tutorial/contrib section for complementary explanations.
 +
 +Preliminary illustration
 +++++++++++++++++++++++++
 +
 +As a preliminary presentation, let's start with a visual example. We propose to apply the filter on a low quality color jpeg image with backlight problems. Here is the considered input... *"Well, my eyes were able to see more that this strange black shadow..."*
 +
 +.. image:: images/retinaInput.jpg
 +   :alt: a low quality color jpeg image with backlight problems.
 +   :align: center
 +
 +Below, the retina foveal model applied on the entire image with default parameters. Here contours are enforced, halo effects are voluntary visible with this configuration. See parameters discussion below and increase horizontalCellsGain near 1 to remove them.
 +
 +.. image:: images/retinaOutput_default.jpg
 +   :alt: the retina foveal model applied on the entire image with default parameters. Here contours are enforced, luminance is corrected and halo effects are voluntary visible with this configuration, increase horizontalCellsGain near 1 to remove them.
 +   :align: center
 +
 +Below, a second retina foveal model output applied on the entire image with a parameters setup focused on naturalness perception. *"Hey, i now recognize my cat, looking at the mountains at the end of the day !"*. Here contours are enforced, luminance is corrected but halos are avoided with this configuration. The backlight effect is corrected and highlight details are still preserved. Then, even on a low quality jpeg image, if some luminance information remains, the retina is able to reconstruct a proper visual signal. Such configuration is also usefull for High Dynamic Range (*HDR*) images compression to 8bit images as discussed in [benoit2010]_ and in the demonstration codes discussed below.
 +As shown at the end of the page, parameters change from defaults are :
 +
 +* horizontalCellsGain=0.3
 +
 +* photoreceptorsLocalAdaptationSensitivity=ganglioncellsSensitivity=0.89.
 +
 +.. image:: images/retinaOutput_realistic.jpg
 +   :alt: the retina foveal model applied on the entire image with 'naturalness' parameters. Here contours are enforced but are avoided with this configuration, horizontalCellsGain is 0.3 and photoreceptorsLocalAdaptationSensitivity=ganglioncellsSensitivity=0.89.
 +   :align: center
 +
 +As observed in this preliminary demo, the retina can be settled up with various parameters, by default, as shown on the figure above, the retina strongly reduces mean luminance energy and enforces all details of the visual scene. Luminance energy and halo effects can be modulated (exagerated to cancelled as shown on the two examples). In order to use your own parameters, you can use at least one time the *write(String fs)* method which will write a proper XML file with all default parameters. Then, tweak it on your own and reload them at any time using method *setup(String fs)*. These methods update a *Retina::RetinaParameters* member structure that is described hereafter. XML parameters file samples are shown at the end of the page.
 +
 +Here is an overview of the abstract Retina interface, allocate one instance with the *createRetina* functions.::
 +
 +  namespace cv{namespace bioinspired{
 +
 +  class Retina : public Algorithm
 +  {
 +  public:
 +    // parameters setup instance
 +    struct RetinaParameters; // this class is detailled later
 +
 +    // main method for input frame processing (all use method, can also perform High Dynamic Range tone mapping)
 +    void run (InputArray inputImage);
 +
 +    // specific method aiming at correcting luminance only (faster High Dynamic Range tone mapping)
 +    void applyFastToneMapping(InputArray inputImage, OutputArray outputToneMappedImage)
 +
 +    // output buffers retreival methods
 +    // -> foveal color vision details channel with luminance and noise correction
 +    void getParvo (OutputArray retinaOutput_parvo);
 +    void getParvoRAW (OutputArray retinaOutput_parvo);// retreive original output buffers without any normalisation
 +    const Mat getParvoRAW () const;// retreive original output buffers without any normalisation
 +    // -> peripheral monochrome motion and events (transient information) channel
 +    void getMagno (OutputArray retinaOutput_magno);
 +    void getMagnoRAW (OutputArray retinaOutput_magno); // retreive original output buffers without any normalisation
 +    const Mat getMagnoRAW () const;// retreive original output buffers without any normalisation
 +
 +    // reset retina buffers... equivalent to closing your eyes for some seconds
 +    void clearBuffers ();
 +
 +    // retreive input and output buffers sizes
 +    Size getInputSize ();
 +    Size getOutputSize ();
 +
 +    // setup methods with specific parameters specification of global xml config file loading/write
 +    void setup (String retinaParameterFile="", const bool applyDefaultSetupOnFailure=true);
 +    void setup (FileStorage &fs, const bool applyDefaultSetupOnFailure=true);
 +    void setup (RetinaParameters newParameters);
 +    struct Retina::RetinaParameters getParameters ();
 +    const String printSetup ();
 +    virtual void write (String fs) const;
 +    virtual void write (FileStorage &fs) const;
 +    void setupOPLandIPLParvoChannel (const bool colorMode=true, const bool normaliseOutput=true, const float photoreceptorsLocalAdaptationSensitivity=0.7, const float photoreceptorsTemporalConstant=0.5, const float photoreceptorsSpatialConstant=0.53, const float horizontalCellsGain=0, const float HcellsTemporalConstant=1, const float HcellsSpatialConstant=7, const float ganglionCellsSensitivity=0.7);
 +    void setupIPLMagnoChannel (const bool normaliseOutput=true, const float parasolCells_beta=0, const float parasolCells_tau=0, const float parasolCells_k=7, const float amacrinCellsTemporalCutFrequency=1.2, const float V0CompressionParameter=0.95, const float localAdaptintegration_tau=0, const float localAdaptintegration_k=7);
 +    void setColorSaturation (const bool saturateColors=true, const float colorSaturationValue=4.0);
 +    void activateMovingContoursProcessing (const bool activate);
 +    void activateContoursProcessing (const bool activate);
 +  };
 +
 +    // Allocators
 +    cv::Ptr<Retina> createRetina (Size inputSize);
 +    cv::Ptr<Retina> createRetina (Size inputSize, const bool colorMode, RETINA_COLORSAMPLINGMETHOD colorSamplingMethod=RETINA_COLOR_BAYER, const bool useRetinaLogSampling=false, const double reductionFactor=1.0, const double samplingStrenght=10.0);
 +    }} // cv and bioinspired namespaces end
 +
++.. Sample code::
++
++   * : An example on retina tone mapping can be found at opencv_source_code/samples/cpp/OpenEXRimages_HighDynamicRange_Retina_toneMapping.cpp
++   * : An example on retina tone mapping on video input can be found at opencv_source_code/samples/cpp/OpenEXRimages_HighDynamicRange_Retina_toneMapping.cpp
++   * : A complete example illustrating the retina interface can be found at opencv_source_code/samples/cpp/retinaDemo.cpp
++
 +Description
 ++++++++++++
 +
 +Class which allows the `Gipsa <http://www.gipsa-lab.inpg.fr>`_ (preliminary work) / `Listic <http://www.listic.univ-savoie.fr>`_ (code maintainer and user) labs retina model to be used. This class allows human retina spatio-temporal image processing to be applied on still images, images sequences and video sequences. Briefly, here are the main human retina model properties:
 +
 +* spectral whithening (mid-frequency details enhancement)
 +
 +* high frequency spatio-temporal noise reduction (temporal noise and high frequency spatial noise are minimized)
 +
 +* low frequency luminance reduction (luminance range compression) : high luminance regions do not hide details in darker regions anymore
 +
 +* local logarithmic luminance compression allows details to be enhanced even in low light conditions
 +
 +Use : this model can be used basically for spatio-temporal video effects but also in the aim of :
 +
 +* performing texture analysis with enhanced signal to noise ratio and enhanced details robust against input images luminance ranges (check out the parvocellular retina channel output, by using the provided **getParvo** methods)
 +
 +* performing motion analysis also taking benefit of the previously cited properties  (check out the magnocellular retina channel output, by using the provided **getMagno** methods)
 +
 +* general image/video sequence description using either one or both channels. An example of the use of Retina in a Bag of Words approach is given in [Strat2013]_.
 +
 +Literature
 +==========
 +For more information, refer to the following papers :
 +
 +* Model description :
 +
 +.. [Benoit2010] Benoit A., Caplier A., Durette B., Herault, J., "Using Human Visual System Modeling For Bio-Inspired Low Level Image Processing", Elsevier, Computer Vision and Image Understanding 114 (2010), pp. 758-773. DOI <http://dx.doi.org/10.1016/j.cviu.2010.01.011>
 +
 +* Model use in a Bag of Words approach :
 +
 +.. [Strat2013] Strat S., Benoit A., Lambert P., "Retina enhanced SIFT descriptors for video indexing", CBMI2013, Veszprém, Hungary, 2013.
 +
 +* Please have a look at the reference work of Jeanny Herault that you can read in his book :
 +
 +.. [Herault2010] Vision: Images, Signals and Neural Networks: Models of Neural Processing in Visual Perception (Progress in Neural Processing),By: Jeanny Herault, ISBN: 9814273686. WAPI (Tower ID): 113266891.
 +
 +This retina filter code includes the research contributions of phd/research collegues from which code has been redrawn by the author :
 +
 +* take a look at the *retinacolor.hpp* module to discover Brice Chaix de Lavarene phD color mosaicing/demosaicing and his reference paper:
 +
 +.. [Chaix2007] B. Chaix de Lavarene, D. Alleysson, B. Durette, J. Herault (2007). "Efficient demosaicing through recursive filtering", IEEE International Conference on Image Processing ICIP 2007
 +
 +* take a look at *imagelogpolprojection.hpp* to discover retina spatial log sampling which originates from Barthelemy Durette phd with Jeanny Herault. A Retina / V1 cortex projection is also proposed and originates from Jeanny's discussions. More informations in the above cited Jeanny Heraults's book.
 +
 +* Meylan&al work on HDR tone mapping that is implemented as a specific method within the model :
 +
 +.. [Meylan2007] L. Meylan , D. Alleysson, S. Susstrunk, "A Model of Retinal Local Adaptation for the Tone Mapping of Color Filter Array Images", Journal of Optical Society of America, A, Vol. 24, N 9, September, 1st, 2007, pp. 2807-2816
 +
 +Demos and experiments !
 +=======================
 +
 +**NOTE : Complementary to the following examples, have a look at the Retina tutorial in the tutorial/contrib section for complementary explanations.**
 +
 +Take a look at the provided C++ examples provided with OpenCV :
 +
 +* **samples/cpp/retinademo.cpp** shows how to use the retina module for details enhancement (Parvo channel output) and transient maps observation (Magno channel output). You can play with images, video sequences and webcam video.
 +    Typical uses are (provided your OpenCV installation is situated in folder *OpenCVReleaseFolder*)
 +
 +    * image processing : **OpenCVReleaseFolder/bin/retinademo -image myPicture.jpg**
 +
 +    * video processing : **OpenCVReleaseFolder/bin/retinademo -video myMovie.avi**
 +
 +    * webcam processing: **OpenCVReleaseFolder/bin/retinademo -video**
 +
 +   **Note :** This demo generates the file *RetinaDefaultParameters.xml* which contains the default parameters of the retina. Then, rename this as *RetinaSpecificParameters.xml*, adjust the parameters the way you want and reload the program to check the effect.
 +
 +
 +* **samples/cpp/OpenEXRimages_HighDynamicRange_Retina_toneMapping.cpp** shows how to use the retina to perform High Dynamic Range (HDR) luminance compression
 +
 +   Then, take a HDR image using bracketing with your camera and generate an OpenEXR image and then process it using the demo.
 +
 +   Typical use, supposing that you have the OpenEXR image such as *memorial.exr* (present in the samples/cpp/ folder)
 +
 +   **OpenCVReleaseFolder/bin/OpenEXRimages_HighDynamicRange_Retina_toneMapping memorial.exr [optionnal: 'fast']**
 +
 +      Note that some sliders are made available to allow you to play with luminance compression.
 +
 +      If not using the 'fast' option, then, tone mapping is performed using the full retina model [Benoit2010]_. It includes spectral whitening that allows luminance energy to be reduced. When using the 'fast' option, then, a simpler method is used, it is an adaptation of the algorithm presented in [Meylan2007]_. This method gives also good results and is faster to process but it sometimes requires some more parameters adjustement.
 +
 +
 +Methods description
 +===================
 +
 +Here are detailled the main methods to control the retina model
 +
 +Ptr<Retina>::createRetina
 ++++++++++++++++++++++++++
 +
 +.. ocv:function:: Ptr<cv::bioinspired::Retina> createRetina(Size inputSize)
 +.. ocv:function:: Ptr<cv::bioinspired::Retina> createRetina(Size inputSize, const bool colorMode, cv::bioinspired::RETINA_COLORSAMPLINGMETHOD colorSamplingMethod = cv::bioinspired::RETINA_COLOR_BAYER, const bool useRetinaLogSampling = false, const double reductionFactor = 1.0, const double samplingStrenght = 10.0 )
 +
 +    Constructors from standardized interfaces : retreive a smart pointer to a Retina instance
 +
 +    :param inputSize: the input frame size
 +    :param colorMode: the chosen processing mode : with or without color processing
 +    :param colorSamplingMethod: specifies which kind of color sampling will be used :
 +
 +        * cv::bioinspired::RETINA_COLOR_RANDOM: each pixel position is either R, G or B in a random choice
 +
 +        * cv::bioinspired::RETINA_COLOR_DIAGONAL: color sampling is RGBRGBRGB..., line 2 BRGBRGBRG..., line 3, GBRGBRGBR...
 +
 +        * cv::bioinspired::RETINA_COLOR_BAYER: standard bayer sampling
 +
 +    :param useRetinaLogSampling: activate retina log sampling, if true, the 2 following parameters can be used
 +    :param reductionFactor: only usefull if param useRetinaLogSampling=true, specifies the reduction factor of the output frame (as the center (fovea) is high resolution and corners can be underscaled, then a reduction of the output is allowed without precision leak
 +    :param samplingStrenght: only usefull if param useRetinaLogSampling=true, specifies the strenght of the log scale that is applied
 +
 +Retina::activateContoursProcessing
 +++++++++++++++++++++++++++++++++++
 +
 +.. ocv:function:: void Retina::activateContoursProcessing(const bool activate)
 +
 +    Activate/desactivate the Parvocellular pathway processing (contours information extraction), by default, it is activated
 +
 +    :param activate: true if Parvocellular (contours information extraction) output should be activated, false if not... if activated, the Parvocellular output can be retrieved using the **getParvo** methods
 +
 +Retina::activateMovingContoursProcessing
 +++++++++++++++++++++++++++++++++++++++++
 +
 +.. ocv:function:: void Retina::activateMovingContoursProcessing(const bool activate)
 +
 +    Activate/desactivate the Magnocellular pathway processing (motion information extraction), by default, it is activated
 +
 +    :param activate: true if Magnocellular output should be activated, false if not... if activated, the Magnocellular output can be retrieved using the **getMagno** methods
 +
 +Retina::clearBuffers
 +++++++++++++++++++++
 +
 +.. ocv:function:: void Retina::clearBuffers()
 +
 +    Clears all retina buffers (equivalent to opening the eyes after a long period of eye close ;o) whatchout the temporal transition occuring just after this method call.
 +
 +Retina::getParvo
 +++++++++++++++++
 +
 +.. ocv:function:: void Retina::getParvo( OutputArray retinaOutput_parvo )
 +.. ocv:function:: void Retina::getParvoRAW( OutputArray retinaOutput_parvo )
 +.. ocv:function:: const Mat Retina::getParvoRAW() const
 +
 +    Accessor of the details channel of the retina (models foveal vision). Warning, getParvoRAW methods return buffers that are not rescaled within range [0;255] while the non RAW method allows a normalized matrix to be retrieved.
 +
 +    :param retinaOutput_parvo: the output buffer (reallocated if necessary), format can be :
 +
 +        * a Mat, this output is rescaled for standard 8bits image processing use in OpenCV
 +
 +        * RAW methods actually return a 1D matrix (encoding is R1, R2, ... Rn, G1, G2, ..., Gn, B1, B2, ...Bn), this output is the original retina filter model output, without any quantification or rescaling.
 +
 +Retina::getMagno
 +++++++++++++++++
 +
 +.. ocv:function:: void Retina::getMagno( OutputArray retinaOutput_magno )
 +.. ocv:function:: void Retina::getMagnoRAW( OutputArray retinaOutput_magno )
 +.. ocv:function:: const Mat Retina::getMagnoRAW() const
 +
 +    Accessor of the motion channel of the retina (models peripheral vision). Warning, getMagnoRAW methods return buffers that are not rescaled within range [0;255] while the non RAW method allows a normalized matrix to be retrieved.
 +
 +    :param retinaOutput_magno: the output buffer (reallocated if necessary), format can be :
 +
 +        * a Mat, this output is rescaled for standard 8bits image processing use in OpenCV
 +
 +        * RAW methods actually return a 1D matrix (encoding is M1, M2,... Mn), this output is the original retina filter model output, without any quantification or rescaling.
 +
 +Retina::getInputSize
 +++++++++++++++++++++
 +
 +.. ocv:function:: Size Retina::getInputSize()
 +
 +    Retreive retina input buffer size
 +
 +    :return: the retina input buffer size
 +
 +Retina::getOutputSize
 ++++++++++++++++++++++
 +
 +.. ocv:function:: Size Retina::getOutputSize()
 +
 +    Retreive retina output buffer size that can be different from the input if a spatial log transformation is applied
 +
 +    :return: the retina output buffer size
 +
 +Retina::printSetup
 +++++++++++++++++++
 +
 +.. ocv:function:: const String Retina::printSetup()
 +
 +    Outputs a string showing the used parameters setup
 +
 +    :return: a string which contains formated parameters information
 +
 +Retina::run
 ++++++++++++
 +
 +.. ocv:function:: void Retina::run(InputArray inputImage)
 +
 +    Method which allows retina to be applied on an input image, after run, encapsulated retina module is ready to deliver its outputs using dedicated acccessors, see getParvo and getMagno methods
 +
 +    :param inputImage: the input Mat image to be processed, can be gray level or BGR coded in any format (from 8bit to 16bits)
 +
 +Retina::applyFastToneMapping
 +++++++++++++++++++++++++++++
 +
 +.. ocv:function:: void Retina::applyFastToneMapping(InputArray inputImage, OutputArray outputToneMappedImage)
 +
 +    Method which processes an image in the aim to correct its luminance : correct backlight problems, enhance details in shadows. This method is designed to perform High Dynamic Range image tone mapping (compress >8bit/pixel images to 8bit/pixel). This is a simplified version of the Retina Parvocellular model (simplified version of the run/getParvo methods call) since it does not include the spatio-temporal filter modelling the Outer Plexiform Layer of the retina that performs spectral whitening and many other stuff. However, it works great for tone mapping and in a faster way.
 +
 +    Check the demos and experiments section to see examples and the way to perform tone mapping using the original retina model and the method.
 +
 +    :param inputImage: the input image to process (should be coded in float format : CV_32F, CV_32FC1, CV_32F_C3, CV_32F_C4, the 4th channel won't be considered).
 +    :param outputToneMappedImage: the output 8bit/channel tone mapped image (CV_8U or CV_8UC3 format).
 +
 +Retina::setColorSaturation
 +++++++++++++++++++++++++++
 +
 +.. ocv:function:: void Retina::setColorSaturation(const bool saturateColors = true, const float colorSaturationValue = 4.0 )
 +
 +    Activate color saturation as the final step of the color demultiplexing process -> this saturation is a sigmoide function applied to each channel of the demultiplexed image.
 +
 +    :param saturateColors: boolean that activates color saturation (if true) or desactivate (if false)
 +    :param colorSaturationValue: the saturation factor : a simple factor applied on the chrominance buffers
 +
 +
 +Retina::setup
 ++++++++++++++
 +
 +.. ocv:function:: void Retina::setup(String retinaParameterFile = "", const bool applyDefaultSetupOnFailure = true )
 +.. ocv:function:: void Retina::setup(FileStorage & fs, const bool applyDefaultSetupOnFailure = true )
 +.. ocv:function:: void Retina::setup(RetinaParameters newParameters)
 +
 +    Try to open an XML retina parameters file to adjust current retina instance setup => if the xml file does not exist, then default setup is applied => warning, Exceptions are thrown if read XML file is not valid
 +
 +    :param retinaParameterFile: the parameters filename
 +    :param applyDefaultSetupOnFailure: set to true if an error must be thrown on error
 +    :param fs: the open Filestorage which contains retina parameters
 +    :param newParameters: a parameters structures updated with the new target configuration. You can retreive the current parameers structure using method *Retina::RetinaParameters Retina::getParameters()* and update it before running method *setup*.
 +
 +Retina::write
 ++++++++++++++
 +
 +.. ocv:function:: void Retina::write( String fs ) const
 +.. ocv:function:: void Retina::write( FileStorage& fs ) const
 +
 +    Write xml/yml formated parameters information
 +
 +    :param fs: the filename of the xml file that will be open and writen with formatted parameters information
 +
 +Retina::setupIPLMagnoChannel
 +++++++++++++++++++++++++++++
 +
 +.. ocv:function:: void Retina::setupIPLMagnoChannel(const bool normaliseOutput = true, const float parasolCells_beta = 0, const float parasolCells_tau = 0, const float parasolCells_k = 7, const float amacrinCellsTemporalCutFrequency = 1.2, const float V0CompressionParameter = 0.95, const float localAdaptintegration_tau = 0, const float localAdaptintegration_k = 7 )
 +
 +    Set parameters values for the Inner Plexiform Layer (IPL) magnocellular channel this channel processes signals output from OPL processing stage in peripheral vision, it allows motion information enhancement. It is decorrelated from the details channel. See reference papers for more details.
 +
 +    :param normaliseOutput: specifies if (true) output is rescaled between 0 and 255 of not (false)
 +    :param parasolCells_beta: the low pass filter gain used for local contrast adaptation at the IPL level of the retina (for ganglion cells local adaptation), typical value is 0
 +    :param parasolCells_tau: the low pass filter time constant used for local contrast adaptation at the IPL level of the retina (for ganglion cells local adaptation), unit is frame, typical value is 0 (immediate response)
 +    :param parasolCells_k: the low pass filter spatial constant used for local contrast adaptation at the IPL level of the retina (for ganglion cells local adaptation), unit is pixels, typical value is 5
 +    :param amacrinCellsTemporalCutFrequency: the time constant of the first order high pass fiter of the magnocellular way (motion information channel), unit is frames, typical value is 1.2
 +    :param V0CompressionParameter: the compression strengh of the ganglion cells local adaptation output, set a value between 0.6 and 1 for best results, a high value increases more the low value sensitivity... and the output saturates faster, recommended value: 0.95
 +    :param localAdaptintegration_tau: specifies the temporal constant of the low pas filter involved in the computation of the local "motion mean" for the local adaptation computation
 +    :param localAdaptintegration_k: specifies the spatial constant of the low pas filter involved in the computation of the local "motion mean" for the local adaptation computation
 +
 +Retina::setupOPLandIPLParvoChannel
 +++++++++++++++++++++++++++++++++++
 +
 +.. ocv:function:: void Retina::setupOPLandIPLParvoChannel(const bool colorMode = true, const bool normaliseOutput = true, const float photoreceptorsLocalAdaptationSensitivity = 0.7, const float photoreceptorsTemporalConstant = 0.5, const float photoreceptorsSpatialConstant = 0.53, const float horizontalCellsGain = 0, const float HcellsTemporalConstant = 1, const float HcellsSpatialConstant = 7, const float ganglionCellsSensitivity = 0.7 )
 +
 +    Setup the OPL and IPL parvo channels (see biologocal model) OPL is referred as Outer Plexiform Layer of the retina, it allows the spatio-temporal filtering which withens the spectrum and reduces spatio-temporal noise while attenuating global luminance (low frequency energy) IPL parvo is the OPL next processing stage, it refers to a part of the Inner Plexiform layer of the retina, it allows high contours sensitivity in foveal vision. See reference papers for more informations.
 +
 +    :param colorMode: specifies if (true) color is processed of not (false) to then processing gray level image
 +    :param normaliseOutput: specifies if (true) output is rescaled between 0 and 255 of not (false)
 +    :param photoreceptorsLocalAdaptationSensitivity: the photoreceptors sensitivity renage is 0-1 (more log compression effect when value increases)
 +    :param photoreceptorsTemporalConstant: the time constant of the first order low pass filter of the photoreceptors, use it to cut high temporal frequencies (noise or fast motion), unit is frames, typical value is 1 frame
 +    :param photoreceptorsSpatialConstant: the spatial constant of the first order low pass filter of the photoreceptors, use it to cut high spatial frequencies (noise or thick contours), unit is pixels, typical value is 1 pixel
 +    :param horizontalCellsGain: gain of the horizontal cells network, if 0, then the mean value of the output is zero, if the parameter is near 1, then, the luminance is not filtered and is still reachable at the output, typicall value is 0
 +    :param HcellsTemporalConstant: the time constant of the first order low pass filter of the horizontal cells, use it to cut low temporal frequencies (local luminance variations), unit is frames, typical value is 1 frame, as the photoreceptors
 +    :param HcellsSpatialConstant: the spatial constant of the first order low pass filter of the horizontal cells, use it to cut low spatial frequencies (local luminance), unit is pixels, typical value is 5 pixel, this value is also used for local contrast computing when computing the local contrast adaptation at the ganglion cells level (Inner Plexiform Layer parvocellular channel model)
 +    :param ganglionCellsSensitivity: the compression strengh of the ganglion cells local adaptation output, set a value between 0.6 and 1 for best results, a high value increases more the low value sensitivity... and the output saturates faster, recommended value: 0.7
 +
 +
 +Retina::RetinaParameters
 +========================
 +
 +.. ocv:struct:: Retina::RetinaParameters
 +
 +  This structure merges all the parameters that can be adjusted threw the **Retina::setup()**, **Retina::setupOPLandIPLParvoChannel** and **Retina::setupIPLMagnoChannel** setup methods
 +  Parameters structure for better clarity, check explenations on the comments of methods : setupOPLandIPLParvoChannel and setupIPLMagnoChannel. ::
 +
 +    class RetinaParameters{
 +        struct OPLandIplParvoParameters{ // Outer Plexiform Layer (OPL) and Inner Plexiform Layer Parvocellular (IplParvo) parameters
 +               OPLandIplParvoParameters():colorMode(true),
 +                  normaliseOutput(true), // specifies if (true) output is rescaled between 0 and 255 of not (false)
 +                  photoreceptorsLocalAdaptationSensitivity(0.7f), // the photoreceptors sensitivity renage is 0-1 (more log compression effect when value increases)
 +                  photoreceptorsTemporalConstant(0.5f),// the time constant of the first order low pass filter of the photoreceptors, use it to cut high temporal frequencies (noise or fast motion), unit is frames, typical value is 1 frame
 +                  photoreceptorsSpatialConstant(0.53f),// the spatial constant of the first order low pass filter of the photoreceptors, use it to cut high spatial frequencies (noise or thick contours), unit is pixels, typical value is 1 pixel
 +                  horizontalCellsGain(0.0f),//gain of the horizontal cells network, if 0, then the mean value of the output is zero, if the parameter is near 1, then, the luminance is not filtered and is still reachable at the output, typicall value is 0
 +                  hcellsTemporalConstant(1.f),// the time constant of the first order low pass filter of the horizontal cells, use it to cut low temporal frequencies (local luminance variations), unit is frames, typical value is 1 frame, as the photoreceptors. Reduce to 0.5 to limit retina after effects.
 +                  hcellsSpatialConstant(7.f),//the spatial constant of the first order low pass filter of the horizontal cells, use it to cut low spatial frequencies (local luminance), unit is pixels, typical value is 5 pixel, this value is also used for local contrast computing when computing the local contrast adaptation at the ganglion cells level (Inner Plexiform Layer parvocellular channel model)
 +                  ganglionCellsSensitivity(0.7f)//the compression strengh of the ganglion cells local adaptation output, set a value between 0.6 and 1 for best results, a high value increases more the low value sensitivity... and the output saturates faster, recommended value: 0.7
 +                  {};// default setup
 +               bool colorMode, normaliseOutput;
 +               float photoreceptorsLocalAdaptationSensitivity, photoreceptorsTemporalConstant, photoreceptorsSpatialConstant, horizontalCellsGain, hcellsTemporalConstant, hcellsSpatialConstant, ganglionCellsSensitivity;
 +           };
 +           struct IplMagnoParameters{ // Inner Plexiform Layer Magnocellular channel (IplMagno)
 +               IplMagnoParameters():
 +                  normaliseOutput(true), //specifies if (true) output is rescaled between 0 and 255 of not (false)
 +                  parasolCells_beta(0.f), // the low pass filter gain used for local contrast adaptation at the IPL level of the retina (for ganglion cells local adaptation), typical value is 0
 +                  parasolCells_tau(0.f), //the low pass filter time constant used for local contrast adaptation at the IPL level of the retina (for ganglion cells local adaptation), unit is frame, typical value is 0 (immediate response)
 +                  parasolCells_k(7.f), //the low pass filter spatial constant used for local contrast adaptation at the IPL level of the retina (for ganglion cells local adaptation), unit is pixels, typical value is 5
 +                  amacrinCellsTemporalCutFrequency(1.2f), //the time constant of the first order high pass fiter of the magnocellular way (motion information channel), unit is frames, typical value is 1.2
 +                  V0CompressionParameter(0.95f), the compression strengh of the ganglion cells local adaptation output, set a value between 0.6 and 1 for best results, a high value increases more the low value sensitivity... and the output saturates faster, recommended value: 0.95
 +                  localAdaptintegration_tau(0.f), // specifies the temporal constant of the low pas filter involved in the computation of the local "motion mean" for the local adaptation computation
 +                  localAdaptintegration_k(7.f) // specifies the spatial constant of the low pas filter involved in the computation of the local "motion mean" for the local adaptation computation
 +                  {};// default setup
 +               bool normaliseOutput;
 +               float parasolCells_beta, parasolCells_tau, parasolCells_k, amacrinCellsTemporalCutFrequency, V0CompressionParameter, localAdaptintegration_tau, localAdaptintegration_k;
 +           };
 +            struct OPLandIplParvoParameters OPLandIplParvo;
 +            struct IplMagnoParameters IplMagno;
 +    };
 +
 +Retina parameters files examples
 +++++++++++++++++++++++++++++++++
 +
 +Here is the default configuration file of the retina module. It gives results such as the first retina output shown on the top of this page.
 +
 +.. code-block:: cpp
 +
 +    <?xml version="1.0"?>
 +    <opencv_storage>
 +    <OPLandIPLparvo>
 +        <colorMode>1</colorMode>
 +        <normaliseOutput>1</normaliseOutput>
 +        <photoreceptorsLocalAdaptationSensitivity>7.5e-01</photoreceptorsLocalAdaptationSensitivity>
 +        <photoreceptorsTemporalConstant>9.0e-01</photoreceptorsTemporalConstant>
 +        <photoreceptorsSpatialConstant>5.3e-01</photoreceptorsSpatialConstant>
 +        <horizontalCellsGain>0.01</horizontalCellsGain>
 +        <hcellsTemporalConstant>0.5</hcellsTemporalConstant>
 +        <hcellsSpatialConstant>7.</hcellsSpatialConstant>
 +        <ganglionCellsSensitivity>7.5e-01</ganglionCellsSensitivity></OPLandIPLparvo>
 +    <IPLmagno>
 +        <normaliseOutput>1</normaliseOutput>
 +        <parasolCells_beta>0.</parasolCells_beta>
 +        <parasolCells_tau>0.</parasolCells_tau>
 +        <parasolCells_k>7.</parasolCells_k>
 +        <amacrinCellsTemporalCutFrequency>2.0e+00</amacrinCellsTemporalCutFrequency>
 +        <V0CompressionParameter>9.5e-01</V0CompressionParameter>
 +        <localAdaptintegration_tau>0.</localAdaptintegration_tau>
 +        <localAdaptintegration_k>7.</localAdaptintegration_k></IPLmagno>
 +    </opencv_storage>
 +
 +Here is the 'realistic" setup used to obtain the second retina output shown on the top of this page.
 +
 +.. code-block:: cpp
 +
 +    <?xml version="1.0"?>
 +    <opencv_storage>
 +    <OPLandIPLparvo>
 +      <colorMode>1</colorMode>
 +      <normaliseOutput>1</normaliseOutput>
 +      <photoreceptorsLocalAdaptationSensitivity>8.9e-01</photoreceptorsLocalAdaptationSensitivity>
 +      <photoreceptorsTemporalConstant>9.0e-01</photoreceptorsTemporalConstant>
 +      <photoreceptorsSpatialConstant>5.3e-01</photoreceptorsSpatialConstant>
 +      <horizontalCellsGain>0.3</horizontalCellsGain>
 +      <hcellsTemporalConstant>0.5</hcellsTemporalConstant>
 +      <hcellsSpatialConstant>7.</hcellsSpatialConstant>
 +      <ganglionCellsSensitivity>8.9e-01</ganglionCellsSensitivity></OPLandIPLparvo>
 +    <IPLmagno>
 +      <normaliseOutput>1</normaliseOutput>
 +      <parasolCells_beta>0.</parasolCells_beta>
 +      <parasolCells_tau>0.</parasolCells_tau>
 +      <parasolCells_k>7.</parasolCells_k>
 +      <amacrinCellsTemporalCutFrequency>2.0e+00</amacrinCellsTemporalCutFrequency>
 +      <V0CompressionParameter>9.5e-01</V0CompressionParameter>
 +      <localAdaptintegration_tau>0.</localAdaptintegration_tau>
 +      <localAdaptintegration_k>7.</localAdaptintegration_k></IPLmagno>
 +    </opencv_storage>
@@@ -1141,47 -1053,96 +1155,50 @@@ used in the global 3D geometry optimiza
  :ocv:func:`solvePnP` .
  
  
 +StereoMatcher
 +-------------
 +.. ocv:class:: StereoMatcher : public Algorithm
  
 -StereoBM
 ---------
 -.. ocv:class:: StereoBM
 -
 -Class for computing stereo correspondence using the block matching algorithm. ::
 -
 -    // Block matching stereo correspondence algorithm class StereoBM
 -    {
 -        enum { NORMALIZED_RESPONSE = CV_STEREO_BM_NORMALIZED_RESPONSE,
 -            BASIC_PRESET=CV_STEREO_BM_BASIC,
 -            FISH_EYE_PRESET=CV_STEREO_BM_FISH_EYE,
 -            NARROW_PRESET=CV_STEREO_BM_NARROW };
 -
 -        StereoBM();
 -        // the preset is one of ..._PRESET above.
 -        // ndisparities is the size of disparity range,
 -        // in which the optimal disparity at each pixel is searched for.
 -        // SADWindowSize is the size of averaging window used to match pixel blocks
 -        //    (larger values mean better robustness to noise, but yield blurry disparity maps)
 -        StereoBM(int preset, int ndisparities=0, int SADWindowSize=21);
 -        // separate initialization function
 -        void init(int preset, int ndisparities=0, int SADWindowSize=21);
 -        // computes the disparity for the two rectified 8-bit single-channel images.
 -        // the disparity will be 16-bit signed (fixed-point) or 32-bit floating-point image of the same size as left.
 -        void operator()( InputArray left, InputArray right, OutputArray disparity, int disptype=CV_16S );
 -
 -        Ptr<CvStereoBMState> state;
 -    };
 -
 -The class is a C++ wrapper for the associated functions. In particular, :ocv:funcx:`StereoBM::operator()` is the wrapper for
 -:ocv:cfunc:`cvFindStereoCorrespondenceBM`.
 -
 -.. Sample code:
 -
 -   * : OCL : An example for using the stereoBM matching algorithm can be found at opencv_source_code/samples/ocl/stereo_match.cpp   
 -
 -StereoBM::StereoBM
 -------------------
 -The constructors.
 -
 -.. ocv:function:: StereoBM::StereoBM()
 -.. ocv:function:: StereoBM::StereoBM(int preset, int ndisparities=0, int SADWindowSize=21)
 -
 -.. ocv:pyfunction:: cv2.StereoBM([preset[, ndisparities[, SADWindowSize]]]) -> <StereoBM object>
 -
 -.. ocv:cfunction:: CvStereoBMState* cvCreateStereoBMState( int preset=CV_STEREO_BM_BASIC, int numberOfDisparities=0 )
 -
 -.. ocv:pyoldfunction:: cv.CreateStereoBMState(preset=CV_STEREO_BM_BASIC, numberOfDisparities=0)-> CvStereoBMState
 -
 -    :param preset: specifies the whole set of algorithm parameters, one of:
 -
 -            * BASIC_PRESET - parameters suitable for general cameras
 -            * FISH_EYE_PRESET - parameters suitable for wide-angle cameras
 -            * NARROW_PRESET - parameters suitable for narrow-angle cameras
 +The base class for stereo correspondence algorithms.
  
 -        After constructing the class, you can override any parameters set by the preset.
 +StereoMatcher::compute
 +-----------------------
 +Computes disparity map for the specified stereo pair
  
 -    :param ndisparities: the disparity search range. For each pixel algorithm will find the best disparity from 0 (default minimum disparity) to ``ndisparities``. The search range can then be shifted by changing the minimum disparity.
 +.. ocv:function:: void StereoMatcher::compute( InputArray left, InputArray right, OutputArray disparity )
  
 -    :param SADWindowSize: the linear size of the blocks compared by the algorithm. The size should be odd (as the block is centered at the current pixel). Larger block size implies smoother, though less accurate disparity map. Smaller block size gives more detailed disparity map, but there is higher chance for algorithm to find a wrong correspondence.
 +.. ocv:pyfunction:: cv2.StereoBM.compute(left, right[, disparity]) -> disparity
  
 -The constructors initialize ``StereoBM`` state. You can then call ``StereoBM::operator()`` to compute disparity for a specific stereo pair.
 +    :param left: Left 8-bit single-channel image.
  
 -.. note:: In the C API you need to deallocate ``CvStereoBM`` state when it is not needed anymore using ``cvReleaseStereoBMState(&stereobm)``.
 +    :param right: Right image of the same size and the same type as the left one.
  
 -StereoBM::operator()
 ------------------------
 -Computes disparity using the BM algorithm for a rectified stereo pair.
 +    :param disparity: Output disparity map. It has the same size as the input images. Some algorithms, like StereoBM or StereoSGBM compute 16-bit fixed-point disparity map (where each disparity value has 4 fractional bits), whereas other algorithms output 32-bit floating-point disparity map.
  
 -.. ocv:function:: void StereoBM::operator()( InputArray left, InputArray right, OutputArray disparity, int disptype=CV_16S )
  
 -.. ocv:pyfunction:: cv2.StereoBM.compute(left, right[, disparity[, disptype]]) -> disparity
 +StereoBM
 +--------
 +.. ocv:class:: StereoBM : public StereoMatcher
  
 -.. ocv:cfunction:: void cvFindStereoCorrespondenceBM( const CvArr* left, const CvArr* right, CvArr* disparity, CvStereoBMState* state )
 +Class for computing stereo correspondence using the block matching algorithm, introduced and contributed to OpenCV by K. Konolige.
  
 -.. ocv:pyoldfunction:: cv.FindStereoCorrespondenceBM(left, right, disparity, state)-> None
++.. Sample code:
 -    :param left: Left 8-bit single-channel image.
++   * : OCL : An example for using the stereoBM matching algorithm can be found at opencv_source_code/samples/ocl/stereo_match.cpp   
  
 -    :param right: Right image of the same size and the same type as the left one.
 +createStereoBM
 +------------------
 +Creates StereoBM object
  
 -    :param disparity: Output disparity map. It has the same size as the input images. When ``disptype==CV_16S``, the map is a 16-bit signed single-channel image, containing disparity values scaled by 16. To get the true disparity values from such fixed-point representation, you will need to divide each  ``disp`` element by 16. If ``disptype==CV_32F``, the disparity map will already contain the real disparity values on output.
 +.. ocv:function:: Ptr<StereoBM> createStereoBM(int numDisparities=0, int blockSize=21)
  
 -    :param disptype: Type of the output disparity map, ``CV_16S`` (default) or ``CV_32F``.
 +.. ocv:pyfunction:: cv2.createStereoBM([numDisparities[, blockSize]]) -> retval
  
 -    :param state: The pre-initialized ``CvStereoBMState`` structure in the case of the old API.
 +    :param numDisparities: the disparity search range. For each pixel algorithm will find the best disparity from 0 (default minimum disparity) to ``numDisparities``. The search range can then be shifted by changing the minimum disparity.
  
 -The method executes the BM algorithm on a rectified stereo pair. See the ``stereo_match.cpp`` OpenCV sample on how to prepare images and call the method. Note that the method is not constant, thus you should not use the same ``StereoBM`` instance from within different threads simultaneously. The function is parallelized with the TBB library.
 +    :param blockSize: the linear size of the blocks compared by the algorithm. The size should be odd (as the block is centered at the current pixel). Larger block size implies smoother, though less accurate disparity map. Smaller block size gives more detailed disparity map, but there is higher chance for algorithm to find a wrong correspondence.
  
 +The function create ``StereoBM`` object. You can then call ``StereoBM::compute()`` to compute disparity for a specific stereo pair.
  
  
  StereoSGBM
@@@ -1197,16 -1186,21 +1214,19 @@@ The class implements the modified H. Hi
  
   * Mutual information cost function is not implemented. Instead, a simpler Birchfield-Tomasi sub-pixel metric from [BT98]_ is used. Though, the color images are supported as well.
  
-  * Some pre- and post- processing steps from K. Konolige algorithm ``StereoBM``  are included, for example: pre-filtering (``StereoBM::PREFILTER_XSOBEL`` type) and post-filtering (uniqueness check, quadratic interpolation and speckle filtering).
+  * Some pre- and post- processing steps from K. Konolige algorithm :ocv:funcx:`StereoBM::operator()`  are included, for example: pre-filtering (``CV_STEREO_BM_XSOBEL`` type) and post-filtering (uniqueness check, quadratic interpolation and speckle filtering).
+ .. Sample code::
  
+    * : PYTHON : An example illustrating the use of the StereoSGBM matching algorithm can be found at opencv_source_code/samples/python2/stereo_match.py
  
 -StereoSGBM::StereoSGBM
 +createStereoSGBM
  --------------------------
 -.. ocv:function:: StereoSGBM::StereoSGBM()
 -
 -.. ocv:function:: StereoSGBM::StereoSGBM( int minDisparity, int numDisparities, int SADWindowSize, int P1=0, int P2=0, int disp12MaxDiff=0, int preFilterCap=0, int uniquenessRatio=0, int speckleWindowSize=0, int speckleRange=0, bool fullDP=false)
 +Creates StereoSGBM object
  
 -.. ocv:pyfunction:: cv2.StereoSGBM([minDisparity, numDisparities, SADWindowSize[, P1[, P2[, disp12MaxDiff[, preFilterCap[, uniquenessRatio[, speckleWindowSize[, speckleRange[, fullDP]]]]]]]]]) -> <StereoSGBM object>
 +.. ocv:function:: Ptr<StereoSGBM> createStereoSGBM( int minDisparity, int numDisparities, int blockSize, int P1=0, int P2=0, int disp12MaxDiff=0, int preFilterCap=0, int uniquenessRatio=0, int speckleWindowSize=0, int speckleRange=0, int mode=StereoSGBM::MODE_SGBM)
  
 -    Initializes ``StereoSGBM`` and sets parameters to custom values.??
 +.. ocv:pyfunction:: cv2.createStereoSGBM(minDisparity, numDisparities, blockSize[, P1[, P2[, disp12MaxDiff[, preFilterCap[, uniquenessRatio[, speckleWindowSize[, speckleRange[, mode]]]]]]]]) -> retval
  
      :param minDisparity: Minimum possible disparity value. Normally, it is zero but sometimes rectification algorithms can shift images, so this parameter needs to be adjusted accordingly.
  
@@@ -1,5 -1,6 +1,5 @@@
--
 -#include "opencv2/contrib/contrib.hpp"
 -#include <cvconfig.h>
 +#include "opencv2/contrib.hpp"
++#include "cvconfig.h"
  
  #if defined(WIN32) || defined(_WIN32)
      #include <windows.h>
  
  namespace cv
  {
 -    std::vector<std::string> Directory::GetListFiles(  const std::string& path, const std::string & exten, bool addPath )
 +    std::vector<String> Directory::GetListFiles(  const String& path, const String & exten, bool addPath )
      {
 -        std::vector<std::string> list;
 +        std::vector<String> list;
          list.clear();
 -        std::string path_f = path + "/" + exten;
 +        String path_f = path + "/" + exten;
          #ifdef WIN32
-             WIN32_FIND_DATA FindFileData;
-             HANDLE hFind;
+         #ifdef HAVE_WINRT
+             WIN32_FIND_DATAW FindFileData;
+         #else
+             WIN32_FIND_DATAA FindFileData;
+         #endif
+         HANDLE hFind;
  
-             hFind = FindFirstFile((LPCSTR)path_f.c_str(), &FindFileData);
+         #ifdef HAVE_WINRT
+             size_t size = mbstowcs(NULL, path_f.c_str(), path_f.size());
+             Ptr<wchar_t> wpath = new wchar_t[size+1];
+             wpath[size] = 0;
+             mbstowcs(wpath, path_f.c_str(), path_f.size());
+             hFind = FindFirstFileExW(wpath, FindExInfoStandard, &FindFileData, FindExSearchNameMatch, NULL, 0);
+         #else
+             hFind = FindFirstFileA((LPCSTR)path_f.c_str(), &FindFileData);
+         #endif
              if (hFind == INVALID_HANDLE_VALUE)
              {
                  return list;
          return list;
      }
  
 -    std::vector<std::string> Directory::GetListFolders( const std::string& path, const std::string & exten, bool addPath )
 +    std::vector<String> Directory::GetListFolders( const String& path, const String & exten, bool addPath )
      {
 -        std::vector<std::string> list;
 -        std::string path_f = path + "/" + exten;
 +        std::vector<String> list;
 +        String path_f = path + "/" + exten;
          list.clear();
          #ifdef WIN32
-             WIN32_FIND_DATA FindFileData;
+         #ifdef HAVE_WINRT
+             WIN32_FIND_DATAW FindFileData;
+         #else
+             WIN32_FIND_DATAA FindFileData;
+         #endif
              HANDLE hFind;
  
-             hFind = FindFirstFile((LPCSTR)path_f.c_str(), &FindFileData);
+         #ifdef HAVE_WINRT
+             size_t size = mbstowcs(NULL, path_f.c_str(), path_f.size());
+             Ptr<wchar_t> wpath = new wchar_t[size+1];
+             wpath[size] = 0;
+             mbstowcs(wpath, path_f.c_str(), path_f.size());
+             hFind = FindFirstFileExW(wpath, FindExInfoStandard, &FindFileData, FindExSearchNameMatch, NULL, 0);
+         #else
+             hFind = FindFirstFileA((LPCSTR)path_f.c_str(), &FindFileData);
+         #endif
              if (hFind == INVALID_HANDLE_VALUE)
              {
                  return list;
@@@ -2,7 -2,12 +2,11 @@@ set(the_description "The Core Functiona
  ocv_add_module(core ${ZLIB_LIBRARIES})
  ocv_module_include_directories(${ZLIB_INCLUDE_DIR})
  
+ if (HAVE_WINRT)
+     set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /ZW /GS /Gm- /AI\"${WINDOWS_SDK_PATH}/References/CommonConfiguration/Neutral\" /AI\"${VISUAL_STUDIO_PATH}/vcpackages\"")
+ endif()
  if(HAVE_CUDA)
 -  ocv_include_directories("${OpenCV_SOURCE_DIR}/modules/gpu/include")
    ocv_warnings_disable(CMAKE_CXX_FLAGS -Wundef)
  endif()
  
Simple merge
Simple merge
Simple merge
@@@ -475,87 -494,6 +479,93 @@@ Draws several polygonal curves
  The function ``polylines`` draws one or more polygonal curves.
  
  
 +drawContours
 +----------------
 +Draws contours outlines or filled contours.
 +
 +.. ocv:function:: void drawContours( InputOutputArray image, InputArrayOfArrays contours, int contourIdx, const Scalar& color, int thickness=1, int lineType=LINE_8, InputArray hierarchy=noArray(), int maxLevel=INT_MAX, Point offset=Point() )
 +
 +.. ocv:pyfunction:: cv2.drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset]]]]]) -> image
 +
 +.. ocv:cfunction:: void cvDrawContours( CvArr * img, CvSeq* contour, CvScalar external_color, CvScalar hole_color, int max_level, int thickness=1, int line_type=8, CvPoint offset=cvPoint(0,0) )
 +
 +    :param image: Destination image.
 +
 +    :param contours: All the input contours. Each contour is stored as a point vector.
 +
 +    :param contourIdx: Parameter indicating a contour to draw. If it is negative, all the contours are drawn.
 +
 +    :param color: Color of the contours.
 +
 +    :param thickness: Thickness of lines the contours are drawn with. If it is negative (for example,  ``thickness=CV_FILLED`` ), the contour interiors are
 +        drawn.
 +
 +    :param lineType: Line connectivity. See  :ocv:func:`line`  for details.
 +
 +    :param hierarchy: Optional information about hierarchy. It is only needed if you want to draw only some of the  contours (see  ``maxLevel`` ).
 +
 +    :param maxLevel: Maximal level for drawn contours. If it is 0, only
 +        the specified contour is drawn. If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This parameter is only taken into account when there is  ``hierarchy``  available.
 +
 +    :param offset: Optional contour shift parameter. Shift all the drawn contours by the specified  :math:`\texttt{offset}=(dx,dy)` .
 +
 +    :param contour: Pointer to the first contour.
 +
 +    :param external_color: Color of external contours.
 +
 +    :param hole_color: Color of internal contours (holes).
 +
 +The function draws contour outlines in the image if
 +:math:`\texttt{thickness} \ge 0` or fills the area bounded by the contours if
 +:math:`\texttt{thickness}<0` . The example below shows how to retrieve connected components from the binary image and label them: ::
 +
 +    #include "opencv2/imgproc.hpp"
 +    #include "opencv2/highgui.hpp"
 +
 +    using namespace cv;
 +    using namespace std;
 +
 +    int main( int argc, char** argv )
 +    {
 +        Mat src;
 +        // the first command-line parameter must be a filename of the binary
 +        // (black-n-white) image
 +        if( argc != 2 || !(src=imread(argv[1], 0)).data)
 +            return -1;
 +
 +        Mat dst = Mat::zeros(src.rows, src.cols, CV_8UC3);
 +
 +        src = src > 1;
 +        namedWindow( "Source", 1 );
 +        imshow( "Source", src );
 +
 +        vector<vector<Point> > contours;
 +        vector<Vec4i> hierarchy;
 +
 +        findContours( src, contours, hierarchy,
 +            RETR_CCOMP, CHAIN_APPROX_SIMPLE );
 +
 +        // iterate through all the top-level contours,
 +        // draw each connected component with its own random color
 +        int idx = 0;
 +        for( ; idx >= 0; idx = hierarchy[idx][0] )
 +        {
 +            Scalar color( rand()&255, rand()&255, rand()&255 );
 +            drawContours( dst, contours, idx, color, FILLED, 8, hierarchy );
 +        }
 +
 +        namedWindow( "Components", 1 );
 +        imshow( "Components", dst );
 +        waitKey(0);
 +    }
 +
++.. Sample code::
++
++   * : An example using the drawContour functionality can be found at opencv_source_code/samples/cpp/contours2.cpp
++   * : An example using drawContours to clean up a background segmentation result at opencv_source_code/samples/cpp/segment_objects.cpp
++
++   * : PYTHON : An example using the drawContour functionality can be found at opencv_source/samples/python2/contours.py
 +
  
  putText
  -----------
@@@ -592,4 -531,4 +602,3 @@@ The function ``putText`` renders the sp
  Symbols that cannot be rendered using the specified font are
  replaced by question marks. See
  :ocv:func:`getTextSize` for a text rendering code example.
--
index bfc8c9c,0000000..5a70d38
mode 100644,000000..100644
--- /dev/null
@@@ -1,466 -1,0 +1,471 @@@
- #ifdef __ARM_NEON__
 +/*M///////////////////////////////////////////////////////////////////////////////////////
 +//
 +//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
 +//
 +//  By downloading, copying, installing or using the software you agree to this license.
 +//  If you do not agree to this license, do not download, install,
 +//  copy or use the software.
 +//
 +//
 +//                          License Agreement
 +//                For Open Source Computer Vision Library
 +//
 +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
 +// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
 +// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
 +// Third party copyrights are property of their respective owners.
 +//
 +// Redistribution and use in source and binary forms, with or without modification,
 +// are permitted provided that the following conditions are met:
 +//
 +//   * Redistribution's of source code must retain the above copyright notice,
 +//     this list of conditions and the following disclaimer.
 +//
 +//   * Redistribution's in binary form must reproduce the above copyright notice,
 +//     this list of conditions and the following disclaimer in the documentation
 +//     and/or other materials provided with the distribution.
 +//
 +//   * The name of the copyright holders may not be used to endorse or promote products
 +//     derived from this software without specific prior written permission.
 +//
 +// This software is provided by the copyright holders and contributors "as is" and
 +// any express or implied warranties, including, but not limited to, the implied
 +// warranties of merchantability and fitness for a particular purpose are disclaimed.
 +// In no event shall the Intel Corporation or contributors be liable for any direct,
 +// indirect, incidental, special, exemplary, or consequential damages
 +// (including, but not limited to, procurement of substitute goods or services;
 +// loss of use, data, or profits; or business interruption) however caused
 +// and on any theory of liability, whether in contract, strict liability,
 +// or tort (including negligence or otherwise) arising in any way out of
 +// the use of this software, even if advised of the possibility of such damage.
 +//
 +//M*/
 +
 +#ifndef __OPENCV_CORE_CVDEF_H__
 +#define __OPENCV_CORE_CVDEF_H__
 +
 +#if !defined _CRT_SECURE_NO_DEPRECATE && defined _MSC_VER && _MSC_VER > 1300
 +#  define _CRT_SECURE_NO_DEPRECATE /* to avoid multiple Visual Studio warnings */
 +#endif
 +
 +// undef problematic defines sometimes defined by system headers (windows.h in particular)
 +#undef small
 +#undef min
 +#undef max
 +#undef abs
 +#undef Complex
 +
 +#if defined __ICL
 +#  define CV_ICC   __ICL
 +#elif defined __ICC
 +#  define CV_ICC   __ICC
 +#elif defined __ECL
 +#  define CV_ICC   __ECL
 +#elif defined __ECC
 +#  define CV_ICC   __ECC
 +#elif defined __INTEL_COMPILER
 +#  define CV_ICC   __INTEL_COMPILER
 +#endif
 +
 +#if defined CV_ICC && !defined CV_ENABLE_UNROLLED
 +#  define CV_ENABLE_UNROLLED 0
 +#else
 +#  define CV_ENABLE_UNROLLED 1
 +#endif
 +
 +#if (defined WIN32 || defined _WIN32 || defined WINCE || defined __CYGWIN__) && defined CVAPI_EXPORTS
 +#  define CV_EXPORTS __declspec(dllexport)
 +#elif defined __GNUC__ && __GNUC__ >= 4
 +#  define CV_EXPORTS __attribute__ ((visibility ("default")))
 +#else
 +#  define CV_EXPORTS
 +#endif
 +
 +#ifndef CV_INLINE
 +#  if defined __cplusplus
 +#    define CV_INLINE static inline
 +#  elif defined _MSC_VER
 +#    define CV_INLINE __inline
 +#  else
 +#    define CV_INLINE static
 +#  endif
 +#endif
 +
 +#ifndef CV_EXTERN_C
 +#  ifdef __cplusplus
 +#    define CV_EXTERN_C extern "C"
 +#  else
 +#    define CV_EXTERN_C
 +#  endif
 +#endif
 +
 +/* CPU features and intrinsics support */
 +#define CV_CPU_NONE    0
 +#define CV_CPU_MMX     1
 +#define CV_CPU_SSE     2
 +#define CV_CPU_SSE2    3
 +#define CV_CPU_SSE3    4
 +#define CV_CPU_SSSE3   5
 +#define CV_CPU_SSE4_1  6
 +#define CV_CPU_SSE4_2  7
 +#define CV_CPU_POPCNT  8
 +#define CV_CPU_AVX    10
 +#define CV_CPU_NEON   11
 +#define CV_HARDWARE_MAX_FEATURE 255
 +
 +// do not include SSE/AVX/NEON headers for NVCC compiler
 +#ifndef __CUDACC__
 +
 +#if defined __SSE2__ || defined _M_X64  || (defined _M_IX86_FP && _M_IX86_FP >= 2)
 +#  include <emmintrin.h>
 +#  define CV_SSE 1
 +#  define CV_SSE2 1
 +#  if defined __SSE3__ || (defined _MSC_VER && _MSC_VER >= 1500)
 +#    include <pmmintrin.h>
 +#    define CV_SSE3 1
 +#  endif
 +#  if defined __SSSE3__  || (defined _MSC_VER && _MSC_VER >= 1500)
 +#    include <tmmintrin.h>
 +#    define CV_SSSE3 1
 +#  endif
 +#  if defined __SSE4_1__ || (defined _MSC_VER && _MSC_VER >= 1500)
 +#    include <smmintrin.h>
 +#    define CV_SSE4_1 1
 +#  endif
 +#  if defined __SSE4_2__ || (defined _MSC_VER && _MSC_VER >= 1500)
 +#    include <nmmintrin.h>
 +#    define CV_SSE4_2 1
 +#  endif
 +#  if defined __AVX__ || (defined _MSC_FULL_VER && _MSC_FULL_VER >= 160040219)
 +// MS Visual Studio 2010 (2012?) has no macro pre-defined to identify the use of /arch:AVX
 +// See: http://connect.microsoft.com/VisualStudio/feedback/details/605858/arch-avx-should-define-a-predefined-macro-in-x64-and-set-a-unique-value-for-m-ix86-fp-in-win32
 +#    include <immintrin.h>
 +#    define CV_AVX 1
 +#    if defined(_XCR_XFEATURE_ENABLED_MASK)
 +#      define __xgetbv() _xgetbv(_XCR_XFEATURE_ENABLED_MASK)
 +#    else
 +#      define __xgetbv() 0
 +#    endif
 +#  endif
 +#endif
 +
- #elif defined HAVE_LRINT || defined CV_ICC || defined __GNUC__
++#if (defined WIN32 || defined _WIN32) && defined(_M_ARM)
++# include <Intrin.h>
++# include "arm_neon.h"
++# define CV_NEON 1
++# define CPU_HAS_NEON_FEATURE (true)
++#elif defined(__ARM_NEON__)
 +#  include <arm_neon.h>
 +#  define CV_NEON 1
 +#endif
 +
 +#endif // __CUDACC__
 +
 +#ifndef CV_SSE
 +#  define CV_SSE 0
 +#endif
 +#ifndef CV_SSE2
 +#  define CV_SSE2 0
 +#endif
 +#ifndef CV_SSE3
 +#  define CV_SSE3 0
 +#endif
 +#ifndef CV_SSSE3
 +#  define CV_SSSE3 0
 +#endif
 +#ifndef CV_SSE4_1
 +#  define CV_SSE4_1 0
 +#endif
 +#ifndef CV_SSE4_2
 +#  define CV_SSE4_2 0
 +#endif
 +#ifndef CV_AVX
 +#  define CV_AVX 0
 +#endif
 +#ifndef CV_NEON
 +#  define CV_NEON 0
 +#endif
 +
 +/* primitive types */
 +/*
 +  schar  - signed 1 byte integer
 +  uchar  - unsigned 1 byte integer
 +  short  - signed 2 byte integer
 +  ushort - unsigned 2 byte integer
 +  int    - signed 4 byte integer
 +  uint   - unsigned 4 byte integer
 +  int64  - signed 8 byte integer
 +  uint64 - unsigned 8 byte integer
 +*/
 +
 +#if !defined _MSC_VER && !defined __BORLANDC__
 +#  if defined __cplusplus && __cplusplus >= 201103L
 +#    include <cstdint>
 +#  else
 +#    include <stdint.h>
 +#  endif
 +#else
 +   typedef unsigned uint;
 +#endif
 +
 +typedef signed char schar;
 +
 +#ifndef __IPL_H__
 +   typedef unsigned char uchar;
 +   typedef unsigned short ushort;
 +#endif
 +
 +#if defined _MSC_VER || defined __BORLANDC__
 +   typedef __int64 int64;
 +   typedef unsigned __int64 uint64;
 +#  define CV_BIG_INT(n)   n##I64
 +#  define CV_BIG_UINT(n)  n##UI64
 +#else
 +   typedef int64_t int64;
 +   typedef uint64_t uint64;
 +#  define CV_BIG_INT(n)   n##LL
 +#  define CV_BIG_UINT(n)  n##ULL
 +#endif
 +
 +/* special informative macros for wrapper generators */
 +#define CV_EXPORTS_W CV_EXPORTS
 +#define CV_EXPORTS_W_SIMPLE CV_EXPORTS
 +#define CV_EXPORTS_AS(synonym) CV_EXPORTS
 +#define CV_EXPORTS_W_MAP CV_EXPORTS
 +#define CV_IN_OUT
 +#define CV_OUT
 +#define CV_PROP
 +#define CV_PROP_RW
 +#define CV_WRAP
 +#define CV_WRAP_AS(synonym)
 +
 +/* fundamental constants */
 +#define CV_PI   3.1415926535897932384626433832795
 +#define CV_LOG2 0.69314718055994530941723212145818
 +
 +/****************************************************************************************\
 +*                                  Matrix type (Mat)                                     *
 +\****************************************************************************************/
 +
 +#define CV_CN_MAX     512
 +#define CV_CN_SHIFT   3
 +#define CV_DEPTH_MAX  (1 << CV_CN_SHIFT)
 +
 +#define CV_8U   0
 +#define CV_8S   1
 +#define CV_16U  2
 +#define CV_16S  3
 +#define CV_32S  4
 +#define CV_32F  5
 +#define CV_64F  6
 +#define CV_USRTYPE1 7
 +
 +#define CV_MAT_DEPTH_MASK       (CV_DEPTH_MAX - 1)
 +#define CV_MAT_DEPTH(flags)     ((flags) & CV_MAT_DEPTH_MASK)
 +
 +#define CV_MAKETYPE(depth,cn) (CV_MAT_DEPTH(depth) + (((cn)-1) << CV_CN_SHIFT))
 +#define CV_MAKE_TYPE CV_MAKETYPE
 +
 +#define CV_8UC1 CV_MAKETYPE(CV_8U,1)
 +#define CV_8UC2 CV_MAKETYPE(CV_8U,2)
 +#define CV_8UC3 CV_MAKETYPE(CV_8U,3)
 +#define CV_8UC4 CV_MAKETYPE(CV_8U,4)
 +#define CV_8UC(n) CV_MAKETYPE(CV_8U,(n))
 +
 +#define CV_8SC1 CV_MAKETYPE(CV_8S,1)
 +#define CV_8SC2 CV_MAKETYPE(CV_8S,2)
 +#define CV_8SC3 CV_MAKETYPE(CV_8S,3)
 +#define CV_8SC4 CV_MAKETYPE(CV_8S,4)
 +#define CV_8SC(n) CV_MAKETYPE(CV_8S,(n))
 +
 +#define CV_16UC1 CV_MAKETYPE(CV_16U,1)
 +#define CV_16UC2 CV_MAKETYPE(CV_16U,2)
 +#define CV_16UC3 CV_MAKETYPE(CV_16U,3)
 +#define CV_16UC4 CV_MAKETYPE(CV_16U,4)
 +#define CV_16UC(n) CV_MAKETYPE(CV_16U,(n))
 +
 +#define CV_16SC1 CV_MAKETYPE(CV_16S,1)
 +#define CV_16SC2 CV_MAKETYPE(CV_16S,2)
 +#define CV_16SC3 CV_MAKETYPE(CV_16S,3)
 +#define CV_16SC4 CV_MAKETYPE(CV_16S,4)
 +#define CV_16SC(n) CV_MAKETYPE(CV_16S,(n))
 +
 +#define CV_32SC1 CV_MAKETYPE(CV_32S,1)
 +#define CV_32SC2 CV_MAKETYPE(CV_32S,2)
 +#define CV_32SC3 CV_MAKETYPE(CV_32S,3)
 +#define CV_32SC4 CV_MAKETYPE(CV_32S,4)
 +#define CV_32SC(n) CV_MAKETYPE(CV_32S,(n))
 +
 +#define CV_32FC1 CV_MAKETYPE(CV_32F,1)
 +#define CV_32FC2 CV_MAKETYPE(CV_32F,2)
 +#define CV_32FC3 CV_MAKETYPE(CV_32F,3)
 +#define CV_32FC4 CV_MAKETYPE(CV_32F,4)
 +#define CV_32FC(n) CV_MAKETYPE(CV_32F,(n))
 +
 +#define CV_64FC1 CV_MAKETYPE(CV_64F,1)
 +#define CV_64FC2 CV_MAKETYPE(CV_64F,2)
 +#define CV_64FC3 CV_MAKETYPE(CV_64F,3)
 +#define CV_64FC4 CV_MAKETYPE(CV_64F,4)
 +#define CV_64FC(n) CV_MAKETYPE(CV_64F,(n))
 +
 +#define CV_MAT_CN_MASK          ((CV_CN_MAX - 1) << CV_CN_SHIFT)
 +#define CV_MAT_CN(flags)        ((((flags) & CV_MAT_CN_MASK) >> CV_CN_SHIFT) + 1)
 +#define CV_MAT_TYPE_MASK        (CV_DEPTH_MAX*CV_CN_MAX - 1)
 +#define CV_MAT_TYPE(flags)      ((flags) & CV_MAT_TYPE_MASK)
 +#define CV_MAT_CONT_FLAG_SHIFT  14
 +#define CV_MAT_CONT_FLAG        (1 << CV_MAT_CONT_FLAG_SHIFT)
 +#define CV_IS_MAT_CONT(flags)   ((flags) & CV_MAT_CONT_FLAG)
 +#define CV_IS_CONT_MAT          CV_IS_MAT_CONT
 +#define CV_SUBMAT_FLAG_SHIFT    15
 +#define CV_SUBMAT_FLAG          (1 << CV_SUBMAT_FLAG_SHIFT)
 +#define CV_IS_SUBMAT(flags)     ((flags) & CV_MAT_SUBMAT_FLAG)
 +
 +/* Size of each channel item,
 +   0x124489 = 1000 0100 0100 0010 0010 0001 0001 ~ array of sizeof(arr_type_elem) */
 +#define CV_ELEM_SIZE1(type) \
 +    ((((sizeof(size_t)<<28)|0x8442211) >> CV_MAT_DEPTH(type)*4) & 15)
 +
 +/* 0x3a50 = 11 10 10 01 01 00 00 ~ array of log2(sizeof(arr_type_elem)) */
 +#define CV_ELEM_SIZE(type) \
 +    (CV_MAT_CN(type) << ((((sizeof(size_t)/4+1)*16384|0x3a50) >> CV_MAT_DEPTH(type)*2) & 3))
 +
 +
 +/****************************************************************************************\
 +*                                      fast math                                         *
 +\****************************************************************************************/
 +
 +#if defined __BORLANDC__
 +#  include <fastmath.h>
 +#elif defined __cplusplus
 +#  include <cmath>
 +#else
 +#  include <math.h>
 +#endif
 +
 +#ifndef MIN
 +#  define MIN(a,b)  ((a) > (b) ? (b) : (a))
 +#endif
 +
 +#ifndef MAX
 +#  define MAX(a,b)  ((a) < (b) ? (b) : (a))
 +#endif
 +
 +#ifdef HAVE_TEGRA_OPTIMIZATION
 +#  include "tegra_round.hpp"
 +#endif
 +
 +CV_INLINE int cvRound( double value )
 +{
 +#if ((defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __x86_64__ && defined __SSE2__ && !defined __APPLE__)) && !defined(__CUDACC__)
 +    __m128d t = _mm_set_sd( value );
 +    return _mm_cvtsd_si32(t);
 +#elif defined _MSC_VER && defined _M_IX86
 +    int t;
 +    __asm
 +    {
 +        fld value;
 +        fistp t;
 +    }
 +    return t;
 +#elif defined _MSC_VER && defined _M_ARM && defined HAVE_TEGRA_OPTIMIZATION
 +    TEGRA_ROUND(value);
++#elif defined CV_ICC || defined __GNUC__
 +#  ifdef HAVE_TEGRA_OPTIMIZATION
 +    TEGRA_ROUND(value);
 +#  else
 +    return (int)lrint(value);
 +#  endif
 +#else
 +    double intpart, fractpart;
 +    fractpart = modf(value, &intpart);
 +    if ((fabs(fractpart) != 0.5) || ((((int)intpart) % 2) != 0))
 +        return (int)(value + (value >= 0 ? 0.5 : -0.5));
 +    else
 +        return (int)intpart;
 +#endif
 +}
 +
 +CV_INLINE int cvFloor( double value )
 +{
 +#if (defined _MSC_VER && defined _M_X64 || (defined __GNUC__ && defined __SSE2__ && !defined __APPLE__)) && !defined(__CUDACC__)
 +    __m128d t = _mm_set_sd( value );
 +    int i = _mm_cvtsd_si32(t);
 +    return i - _mm_movemask_pd(_mm_cmplt_sd(t, _mm_cvtsi32_sd(t,i)));
 +#elif defined __GNUC__
 +    int i = (int)value;
 +    return i - (i > value);
 +#else
 +    int i = cvRound(value);
 +    float diff = (float)(value - i);
 +    return i - (diff < 0);
 +#endif
 +}
 +
 +CV_INLINE int cvCeil( double value )
 +{
 +#if (defined _MSC_VER && defined _M_X64 || (defined __GNUC__ && defined __SSE2__&& !defined __APPLE__)) && !defined(__CUDACC__)
 +    __m128d t = _mm_set_sd( value );
 +    int i = _mm_cvtsd_si32(t);
 +    return i + _mm_movemask_pd(_mm_cmplt_sd(_mm_cvtsi32_sd(t,i), t));
 +#elif defined __GNUC__
 +    int i = (int)value;
 +    return i + (i < value);
 +#else
 +    int i = cvRound(value);
 +    float diff = (float)(i - value);
 +    return i + (diff < 0);
 +#endif
 +}
 +
 +CV_INLINE int cvIsNaN( double value )
 +{
 +    union { uint64 u; double f; } ieee754;
 +    ieee754.f = value;
 +    return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) +
 +           ((unsigned)ieee754.u != 0) > 0x7ff00000;
 +}
 +
 +CV_INLINE int cvIsInf( double value )
 +{
 +    union { uint64 u; double f; } ieee754;
 +    ieee754.f = value;
 +    return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) == 0x7ff00000 &&
 +           (unsigned)ieee754.u == 0;
 +}
 +
 +/****************************************************************************************\
 +*          exchange-add operation for atomic operations on reference counters            *
 +\****************************************************************************************/
 +
 +#if defined __INTEL_COMPILER && !(defined WIN32 || defined _WIN32)
 +   // atomic increment on the linux version of the Intel(tm) compiler
 +#  define CV_XADD(addr, delta) (int)_InterlockedExchangeAdd(const_cast<void*>(reinterpret_cast<volatile void*>(addr)), delta)
 +#elif defined __GNUC__
 +#  if defined __clang__ && __clang_major__ >= 3 && !defined __ANDROID__
 +#    ifdef __ATOMIC_ACQ_REL
 +#      define CV_XADD(addr, delta) __c11_atomic_fetch_add((_Atomic(int)*)(addr), delta, __ATOMIC_ACQ_REL)
 +#    else
 +#      define CV_XADD(addr, delta) __atomic_fetch_add((_Atomic(int)*)(addr), delta, 4)
 +#    endif
 +#  else
 +#    if defined __ATOMIC_ACQ_REL && !defined __clang__
 +       // version for gcc >= 4.7
 +#      define CV_XADD(addr, delta) (int)__atomic_fetch_add((unsigned*)(addr), (unsigned)(delta), __ATOMIC_ACQ_REL)
 +#    else
 +#      define CV_XADD(addr, delta) (int)__sync_fetch_and_add((unsigned*)(addr), (unsigned)(delta))
 +#    endif
 +#  endif
 +#elif (defined WIN32 || defined _WIN32 || defined WINCE) && (!defined RC_INVOKED)
 +#  if !defined(_M_AMD64) && !defined(_M_IA64) && !defined(_M_ARM)
 +     CV_EXTERN_C __declspec(dllimport) long __stdcall InterlockedExchangeAdd(long volatile *Addend, long Value);
 +#    define CV_XADD(addr, delta) (int)InterlockedExchangeAdd((long volatile*)addr, delta)
 +#  else
 +     CV_EXTERN_C long _InterlockedExchangeAdd (long volatile *Addend, long Value);
 +#    pragma intrinsic(_InterlockedExchangeAdd)
 +#    define CV_XADD(addr, delta) (int)_InterlockedExchangeAdd((long volatile*)addr, delta)
 +#  endif
 +#else
 +   CV_INLINE CV_XADD(int* addr, int delta) { int tmp = *addr; *addr += delta; return tmp; }
 +#endif
 +
 +#endif // __OPENCV_CORE_CVDEF_H__
Simple merge
@@@ -886,14 -886,14 +886,16 @@@ void ellipse2Poly( Point center, Size a
          Point pt;
          pt.x = cvRound( cx + x * alpha - y * beta );
          pt.y = cvRound( cy + x * beta + y * alpha );
-         if( pt != prevPt )
+         if( pt != prevPt ){
              pts.push_back(pt);
+             prevPt = pt;
+         }
      }
  
 -    if( pts.size() == 1 )
 -        pts.push_back(pts[0]);
 +    // If there are no points, it's a zero-size polygon
-     if( pts.size() < 2) {
++    if( pts.size() == 1) {
 +        pts.assign(2,center);
 +    }
  }
  
  
Simple merge
Simple merge
@@@ -348,33 -375,49 +375,61 @@@ const String& getBuildInformation(
      return build_info;
  }
  
 -string format( const char* fmt, ... )
 +String format( const char* fmt, ... )
  {
 -    char buf[1 << 16];
 -    va_list args;
 -    va_start( args, fmt );
 -    vsprintf( buf, fmt, args );
 -    return string(buf);
 +    char buf[1024];
 +
 +    va_list va;
 +    va_start(va, fmt);
 +    int len = vsnprintf(buf, sizeof(buf), fmt, va);
 +    va_end(va);
 +
 +    if (len >= (int)sizeof(buf))
 +    {
 +        String s(len, '\0');
 +        va_start(va, fmt);
 +        len = vsnprintf((char*)s.c_str(), len + 1, fmt, va);
 +        va_end(va);
 +        return s;
 +    }
 +
 +    return String(buf, len);
  }
  
 -string tempfile( const char* suffix )
 +String tempfile( const char* suffix )
  {
+ #ifdef HAVE_WINRT
+     std::wstring temp_dir = L"";
+     const wchar_t* opencv_temp_dir = _wgetenv(L"OPENCV_TEMP_PATH");
+     if (opencv_temp_dir)
+         temp_dir = std::wstring(opencv_temp_dir);
+ #else
      const char *temp_dir = getenv("OPENCV_TEMP_PATH");
 -    string fname;
 +    String fname;
+ #endif
  
  #if defined WIN32 || defined _WIN32
+ #ifdef HAVE_WINRT
+     RoInitialize(RO_INIT_MULTITHREADED);
+     std::wstring temp_dir2;
+     if (temp_dir.empty())
+         temp_dir = GetTempPathWinRT();
+     std::wstring temp_file;
+     temp_file = GetTempFileNameWinRT(L"ocv");
+     if (temp_file.empty())
+         return std::string();
+     temp_file = temp_dir + std::wstring(L"\\") + temp_file;
+     DeleteFileW(temp_file.c_str());
+     size_t asize = wcstombs(NULL, temp_file.c_str(), 0);
+     Ptr<char> aname = new char[asize+1];
+     aname[asize] = 0;
+     wcstombs(aname, temp_file.c_str(), asize);
+     fname = std::string(aname);
+     RoUninitialize();
+ #else
      char temp_dir2[MAX_PATH + 1] = { 0 };
      char temp_file[MAX_PATH + 1] = { 0 };
  
@@@ -676,8 -681,131 +698,12 @@@ cvErrorFromIppStatus( int status 
      }
  }
  
 -static CvModuleInfo cxcore_info = { 0, "cxcore", CV_VERSION, 0 };
 -
 -CvModuleInfo* CvModule::first = 0, *CvModule::last = 0;
 -
 -CvModule::CvModule( CvModuleInfo* _info )
 -{
 -    cvRegisterModule( _info );
 -    info = last;
 -}
 -
 -CvModule::~CvModule(void)
 -{
 -    if( info )
 -    {
 -        CvModuleInfo* p = first;
 -        for( ; p != 0 && p->next != info; p = p->next )
 -            ;
 -
 -        if( p )
 -            p->next = info->next;
 -
 -        if( first == info )
 -            first = info->next;
 -
 -        if( last == info )
 -            last = p;
 -
 -        free( info );
 -        info = 0;
 -    }
 -}
 -
 -CV_IMPL int
 -cvRegisterModule( const CvModuleInfo* module )
 -{
 -    CV_Assert( module != 0 && module->name != 0 && module->version != 0 );
 -
 -    size_t name_len = strlen(module->name);
 -    size_t version_len = strlen(module->version);
 -
 -    CvModuleInfo* module_copy = (CvModuleInfo*)malloc( sizeof(*module_copy) +
 -                                name_len + 1 + version_len + 1 );
 -
 -    *module_copy = *module;
 -    module_copy->name = (char*)(module_copy + 1);
 -    module_copy->version = (char*)(module_copy + 1) + name_len + 1;
 -
 -    memcpy( (void*)module_copy->name, module->name, name_len + 1 );
 -    memcpy( (void*)module_copy->version, module->version, version_len + 1 );
 -    module_copy->next = 0;
 -
 -    if( CvModule::first == 0 )
 -        CvModule::first = module_copy;
 -    else
 -        CvModule::last->next = module_copy;
 -
 -    CvModule::last = module_copy;
 -
 -    return 0;
 -}
 -
 -CvModule cxcore_module( &cxcore_info );
 -
 -CV_IMPL void
 -cvGetModuleInfo( const char* name, const char **version, const char **plugin_list )
 -{
 -    static char joint_verinfo[1024]   = "";
 -    static char plugin_list_buf[1024] = "";
 -
 -    if( version )
 -        *version = 0;
 -
 -    if( plugin_list )
 -        *plugin_list = 0;
 -
 -    CvModuleInfo* module;
 -
 -    if( version )
 -    {
 -        if( name )
 -        {
 -            size_t i, name_len = strlen(name);
 -
 -            for( module = CvModule::first; module != 0; module = module->next )
 -            {
 -                if( strlen(module->name) == name_len )
 -                {
 -                    for( i = 0; i < name_len; i++ )
 -                    {
 -                        int c0 = toupper(module->name[i]), c1 = toupper(name[i]);
 -                        if( c0 != c1 )
 -                            break;
 -                    }
 -                    if( i == name_len )
 -                        break;
 -                }
 -            }
 -            if( !module )
 -                CV_Error( CV_StsObjectNotFound, "The module is not found" );
 -
 -            *version = module->version;
 -        }
 -        else
 -        {
 -            char* ptr = joint_verinfo;
 -
 -            for( module = CvModule::first; module != 0; module = module->next )
 -            {
 -                sprintf( ptr, "%s: %s%s", module->name, module->version, module->next ? ", " : "" );
 -                ptr += strlen(ptr);
 -            }
 -
 -            *version = joint_verinfo;
 -        }
 -    }
 -
 -    if( plugin_list )
 -        *plugin_list = plugin_list_buf;
 -}
  
- #if defined BUILD_SHARED_LIBS && defined CVAPI_EXPORTS && defined WIN32 && !defined WINCE
+ #if defined CVAPI_EXPORTS && defined WIN32 && !defined WINCE
+ #ifdef HAVE_WINRT
+     #pragma warning(disable:4447) // Disable warning 'main' signature found without threading model
+ #endif
  BOOL WINAPI DllMain( HINSTANCE, DWORD  fdwReason, LPVOID );
  
  BOOL WINAPI DllMain( HINSTANCE, DWORD  fdwReason, LPVOID )
@@@ -9,7 -9,41 +9,12 @@@ that are represented as vectors in a mu
  descriptor matchers inherit the
  :ocv:class:`DescriptorMatcher` interface.
  
+ .. Sample code::
+    * : An example explaining keypoint matching can be found at opencv_source_code/samples/cpp/descriptor_extractor_matcher.cpp
+    * : An example on descriptor matching evaluation can be found at opencv_source_code/samples/cpp/detector_descriptor_matcher_evaluation.cpp
+    * : An example on one to many image matching can be found at opencv_source_code/samples/cpp/matching_to_many_images.cpp
  
 -DMatch
 -------
 -.. ocv:struct:: DMatch
 -
 -Class for matching keypoint descriptors: query descriptor index,
 -train descriptor index, train image index, and distance between descriptors. ::
 -
 -    struct DMatch
 -    {
 -        DMatch() : queryIdx(-1), trainIdx(-1), imgIdx(-1),
 -                   distance(std::numeric_limits<float>::max()) {}
 -        DMatch( int _queryIdx, int _trainIdx, float _distance ) :
 -                queryIdx(_queryIdx), trainIdx(_trainIdx), imgIdx(-1),
 -                distance(_distance) {}
 -        DMatch( int _queryIdx, int _trainIdx, int _imgIdx, float _distance ) :
 -                queryIdx(_queryIdx), trainIdx(_trainIdx), imgIdx(_imgIdx),
 -                distance(_distance) {}
 -
 -        int queryIdx; // query descriptor index
 -        int trainIdx; // train descriptor index
 -        int imgIdx;   // train image index
 -
 -        float distance;
 -
 -        // less is better
 -        bool operator<( const DMatch &m ) const;
 -    };
 -
 -
  DescriptorMatcher
  -----------------
  .. ocv:class:: DescriptorMatcher : public Algorithm
@@@ -271,4 -305,4 +276,3 @@@ Flann-based descriptor matcher. This ma
      };
  
  ..
--
@@@ -8,7 -8,70 +8,10 @@@ between different algorithms solving th
  inherit the
  :ocv:class:`FeatureDetector` interface.
  
+ .. Sample code::
+    * : An example explaining keypoint detection can be found at opencv_source_code/samples/cpp/descriptor_extractor_matcher.cpp
  
 -
 -KeyPoint
 ---------
 -.. ocv:class:: KeyPoint
 -
 -  Data structure for salient point detectors.
 -
 -  .. ocv:member:: Point2f pt
 -
 -     coordinates of the keypoint
 -
 -  .. ocv:member:: float size
 -
 -     diameter of the meaningful keypoint neighborhood
 -
 -  .. ocv:member:: float angle
 -
 -     computed orientation of the keypoint (-1 if not applicable). Its possible values are in a range [0,360) degrees. It is measured relative to image coordinate system (y-axis is directed downward), ie in clockwise.
 -
 -  .. ocv:member:: float response
 -
 -     the response by which the most strong keypoints have been selected. Can be used for further sorting or subsampling
 -
 -  .. ocv:member:: int octave
 -
 -     octave (pyramid layer) from which the keypoint has been extracted
 -
 -  .. ocv:member:: int class_id
 -
 -     object id that can be used to clustered keypoints by an object they belong to
 -
 -KeyPoint::KeyPoint
 -------------------
 -The keypoint constructors
 -
 -.. ocv:function:: KeyPoint::KeyPoint()
 -
 -.. ocv:function:: KeyPoint::KeyPoint(Point2f _pt, float _size, float _angle=-1, float _response=0, int _octave=0, int _class_id=-1)
 -
 -.. ocv:function:: KeyPoint::KeyPoint(float x, float y, float _size, float _angle=-1, float _response=0, int _octave=0, int _class_id=-1)
 -
 -.. ocv:pyfunction:: cv2.KeyPoint([x, y, _size[, _angle[, _response[, _octave[, _class_id]]]]]) -> <KeyPoint object>
 -
 -    :param x: x-coordinate of the keypoint
 -
 -    :param y: y-coordinate of the keypoint
 -
 -    :param _pt: x & y coordinates of the keypoint
 -
 -    :param _size: keypoint diameter
 -
 -    :param _angle: keypoint orientation
 -
 -    :param _response: keypoint detector response on the keypoint (that is, strength of the keypoint)
 -
 -    :param _octave: pyramid octave in which the keypoint has been detected
 -
 -    :param _class_id: object id
 -
 -
  FeatureDetector
  ---------------
  .. ocv:class:: FeatureDetector : public Algorithm
@@@ -20,7 -21,5 +20,6 @@@
  #include "opencv2/flann/all_indices.h"
  #include "opencv2/flann/flann_base.hpp"
  
 -#endif
 +#include "opencv2/core/private.hpp"
  
 +#endif
Simple merge
  #include <cstdio>
  
  #include "cvconfig.h"
 -
 -#include "opencv2/ts/ts.hpp"
 +#include "opencv2/core.hpp"
 +#include "opencv2/gpuimgproc.hpp"
 +#include "opencv2/gpuoptflow.hpp"
 +#include "opencv2/highgui.hpp"
 +#include "opencv2/video.hpp"
 +#include "opencv2/legacy.hpp"
 +#include "opencv2/ts.hpp"
  #include "opencv2/ts/gpu_perf.hpp"
  
- CV_PERF_TEST_CUDA_MAIN(gpu_perf4au)
 -#include "opencv2/core/core.hpp"
 -#include "opencv2/gpu/gpu.hpp"
 -#include "opencv2/highgui/highgui.hpp"
 -#include "opencv2/video/video.hpp"
 -#include "opencv2/legacy/legacy.hpp"
 -
+ static const char * impls[] = {
+     "cuda",
+     "plain"
+ };
+ CV_PERF_TEST_MAIN_WITH_IMPLS(gpu_perf4au, impls, perf::printCudaInfo())
  
  //////////////////////////////////////////////////////////
  // HoughLinesP
index c39028c,0000000..934afdc
mode 100644,000000..100644
--- /dev/null
@@@ -1,124 -1,0 +1,127 @@@
 +Background Segmentation
 +=======================
 +
 +.. highlight:: cpp
 +
 +
 +
 +gpu::BackgroundSubtractorMOG
 +----------------------------
 +Gaussian Mixture-based Background/Foreground Segmentation Algorithm.
 +
 +.. ocv:class:: gpu::BackgroundSubtractorMOG : public cv::BackgroundSubtractorMOG
 +
 +The class discriminates between foreground and background pixels by building and maintaining a model of the background. Any pixel which does not fit this model is then deemed to be foreground. The class implements algorithm described in [MOG2001]_.
 +
 +.. seealso:: :ocv:class:`BackgroundSubtractorMOG`
 +
++.. Sample code::
++
++   * : An example on gaussian mixture based background/foreground segmantation can be found at opencv_source_code/samples/gpu/bgfg_segm.cpp
 +
 +
 +gpu::createBackgroundSubtractorMOG
 +----------------------------------
 +Creates mixture-of-gaussian background subtractor
 +
 +.. ocv:function:: Ptr<gpu::BackgroundSubtractorMOG> gpu::createBackgroundSubtractorMOG(int history=200, int nmixtures=5, double backgroundRatio=0.7, double noiseSigma=0)
 +
 +    :param history: Length of the history.
 +
 +    :param nmixtures: Number of Gaussian mixtures.
 +
 +    :param backgroundRatio: Background ratio.
 +
 +    :param noiseSigma: Noise strength (standard deviation of the brightness or each color channel). 0 means some automatic value.
 +
 +
 +
 +gpu::BackgroundSubtractorMOG2
 +-----------------------------
 +Gaussian Mixture-based Background/Foreground Segmentation Algorithm.
 +
 +.. ocv:class:: gpu::BackgroundSubtractorMOG2 : public cv::BackgroundSubtractorMOG2
 +
 +The class discriminates between foreground and background pixels by building and maintaining a model of the background. Any pixel which does not fit this model is then deemed to be foreground. The class implements algorithm described in [MOG2004]_.
 +
 +.. seealso:: :ocv:class:`BackgroundSubtractorMOG2`
 +
 +
 +
 +gpu::createBackgroundSubtractorMOG2
 +-----------------------------------
 +Creates MOG2 Background Subtractor
 +
 +.. ocv:function:: Ptr<gpu::BackgroundSubtractorMOG2> gpu::createBackgroundSubtractorMOG2( int history=500, double varThreshold=16, bool detectShadows=true )
 +
 +  :param history: Length of the history.
 +
 +  :param varThreshold: Threshold on the squared Mahalanobis distance between the pixel and the model to decide whether a pixel is well described by the background model. This parameter does not affect the background update.
 +
 +  :param detectShadows: If true, the algorithm will detect shadows and mark them. It decreases the speed a bit, so if you do not need this feature, set the parameter to false.
 +
 +
 +
 +gpu::BackgroundSubtractorGMG
 +----------------------------
 +Background/Foreground Segmentation Algorithm.
 +
 +.. ocv:class:: gpu::BackgroundSubtractorGMG : public cv::BackgroundSubtractorGMG
 +
 +The class discriminates between foreground and background pixels by building and maintaining a model of the background. Any pixel which does not fit this model is then deemed to be foreground. The class implements algorithm described in [GMG2012]_.
 +
 +
 +
 +gpu::createBackgroundSubtractorGMG
 +----------------------------------
 +Creates GMG Background Subtractor
 +
 +.. ocv:function:: Ptr<gpu::BackgroundSubtractorGMG> gpu::createBackgroundSubtractorGMG(int initializationFrames = 120, double decisionThreshold = 0.8)
 +
 +    :param initializationFrames: Number of frames of video to use to initialize histograms.
 +
 +    :param decisionThreshold: Value above which pixel is determined to be FG.
 +
 +
 +
 +gpu::BackgroundSubtractorFGD
 +----------------------------
 +
 +.. ocv:class:: gpu::BackgroundSubtractorFGD : public cv::BackgroundSubtractor
 +
 +The class discriminates between foreground and background pixels by building and maintaining a model of the background. Any pixel which does not fit this model is then deemed to be foreground. The class implements algorithm described in [FGD2003]_. ::
 +
 +    class CV_EXPORTS BackgroundSubtractorFGD : public cv::BackgroundSubtractor
 +    {
 +    public:
 +        virtual void getForegroundRegions(OutputArrayOfArrays foreground_regions) = 0;
 +    };
 +
 +.. seealso:: :ocv:class:`BackgroundSubtractor`
 +
 +
 +
 +gpu::BackgroundSubtractorFGD::getForegroundRegions
 +--------------------------------------------------
 +Returns the output foreground regions calculated by :ocv:func:`findContours`.
 +
 +.. ocv:function:: void gpu::BackgroundSubtractorFGD::getForegroundRegions(OutputArrayOfArrays foreground_regions)
 +
 +    :params foreground_regions: Output array (CPU memory).
 +
 +
 +
 +gpu::createBackgroundSubtractorFGD
 +----------------------------------
 +Creates FGD Background Subtractor
 +
 +.. ocv:function:: Ptr<gpu::BackgroundSubtractorGMG> gpu::createBackgroundSubtractorFGD(const FGDParams& params = FGDParams())
 +
 +    :param params: Algorithm's parameters. See [FGD2003]_ for explanation.
 +
 +
 +
 +.. [FGD2003] Liyuan Li, Weimin Huang, Irene Y.H. Gu, and Qi Tian. *Foreground Object Detection from Videos Containing Complex Background*. ACM MM2003 9p, 2003.
 +.. [MOG2001] P. KadewTraKuPong and R. Bowden. *An improved adaptive background mixture model for real-time tracking with shadow detection*. Proc. 2nd European Workshop on Advanced Video-Based Surveillance Systems, 2001
 +.. [MOG2004] Z. Zivkovic. *Improved adaptive Gausian mixture model for background subtraction*. International Conference Pattern Recognition, UK, August, 2004
 +.. [GMG2012] A. Godbehere, A. Matsukawa and K. Goldberg. *Visual Tracking of Human Visitors under Variable-Lighting Conditions for a Responsive Audio Art Installation*. American Control Conference, Montreal, June 2012
index e2da305,0000000..646f875
mode 100644,000000..100644
--- /dev/null
@@@ -1,153 -1,0 +1,156 @@@
 +Video Decoding
 +==============
 +
 +.. highlight:: cpp
 +
 +
 +
 +gpucodec::VideoReader
 +---------------------
 +Video reader interface.
 +
 +.. ocv:class:: gpucodec::VideoReader
 +
++.. Sample code::
++
++   * : An example on how to use the videoReader class can be found at opencv_source_code/samples/gpu/video_reader.cpp
 +
 +
 +gpucodec::VideoReader::nextFrame
 +--------------------------------
 +Grabs, decodes and returns the next video frame.
 +
 +.. ocv:function:: bool gpucodec::VideoReader::nextFrame(OutputArray frame)
 +
 +If no frames has been grabbed (there are no more frames in video file), the methods return ``false`` . The method throws :ocv:class:`Exception` if error occurs.
 +
 +
 +
 +gpucodec::VideoReader::format
 +-----------------------------
 +Returns information about video file format.
 +
 +.. ocv:function:: FormatInfo gpucodec::VideoReader::format() const
 +
 +
 +
 +gpucodec::Codec
 +---------------
 +Video codecs supported by :ocv:class:`gpucodec::VideoReader` .
 +
 +.. ocv:enum:: gpucodec::Codec
 +
 +  .. ocv:emember:: MPEG1 = 0
 +  .. ocv:emember:: MPEG2
 +  .. ocv:emember:: MPEG4
 +  .. ocv:emember:: VC1
 +  .. ocv:emember:: H264
 +  .. ocv:emember:: JPEG
 +  .. ocv:emember:: H264_SVC
 +  .. ocv:emember:: H264_MVC
 +
 +  .. ocv:emember:: Uncompressed_YUV420 = (('I'<<24)|('Y'<<16)|('U'<<8)|('V'))
 +
 +        Y,U,V (4:2:0)
 +
 +  .. ocv:emember:: Uncompressed_YV12   = (('Y'<<24)|('V'<<16)|('1'<<8)|('2'))
 +
 +        Y,V,U (4:2:0)
 +
 +  .. ocv:emember:: Uncompressed_NV12   = (('N'<<24)|('V'<<16)|('1'<<8)|('2'))
 +
 +        Y,UV  (4:2:0)
 +
 +  .. ocv:emember:: Uncompressed_YUYV   = (('Y'<<24)|('U'<<16)|('Y'<<8)|('V'))
 +
 +        YUYV/YUY2 (4:2:2)
 +
 +  .. ocv:emember:: Uncompressed_UYVY   = (('U'<<24)|('Y'<<16)|('V'<<8)|('Y'))
 +
 +        UYVY (4:2:2)
 +
 +
 +
 +gpucodec::ChromaFormat
 +----------------------
 +Chroma formats supported by :ocv:class:`gpucodec::VideoReader` .
 +
 +.. ocv:enum:: gpucodec::ChromaFormat
 +
 +  .. ocv:emember:: Monochrome = 0
 +  .. ocv:emember:: YUV420
 +  .. ocv:emember:: YUV422
 +  .. ocv:emember:: YUV444
 +
 +
 +
 +gpucodec::FormatInfo
 +--------------------
 +.. ocv:struct:: gpucodec::FormatInfo
 +
 +Struct providing information about video file format. ::
 +
 +    struct FormatInfo
 +    {
 +        Codec codec;
 +        ChromaFormat chromaFormat;
 +        int width;
 +        int height;
 +    };
 +
 +
 +
 +gpucodec::createVideoReader
 +---------------------------
 +Creates video reader.
 +
 +.. ocv:function:: Ptr<VideoReader> gpucodec::createVideoReader(const String& filename)
 +.. ocv:function:: Ptr<VideoReader> gpucodec::createVideoReader(const Ptr<RawVideoSource>& source)
 +
 +    :param filename: Name of the input video file.
 +
 +    :param source: RAW video source implemented by user.
 +
 +FFMPEG is used to read videos. User can implement own demultiplexing with :ocv:class:`gpucodec::RawVideoSource` .
 +
 +
 +
 +gpucodec::RawVideoSource
 +------------------------
 +.. ocv:class:: gpucodec::RawVideoSource
 +
 +Interface for video demultiplexing. ::
 +
 +    class RawVideoSource
 +    {
 +    public:
 +        virtual ~RawVideoSource() {}
 +
 +        virtual bool getNextPacket(unsigned char** data, int* size, bool* endOfFile) = 0;
 +
 +        virtual FormatInfo format() const = 0;
 +    };
 +
 +User can implement own demultiplexing by implementing this interface.
 +
 +
 +
 +gpucodec::RawVideoSource::getNextPacket
 +---------------------------------------
 +Returns next packet with RAW video frame.
 +
 +.. ocv:function:: bool gpucodec::VideoSource::getNextPacket(unsigned char** data, int* size, bool* endOfFile) = 0
 +
 +    :param data: Pointer to frame data.
 +
 +    :param size: Size in bytes of current frame.
 +
 +    :param endOfStream: Indicates that it is end of stream.
 +
 +
 +
 +gpucodec::RawVideoSource::format
 +--------------------------------
 +Returns information about video file format.
 +
 +.. ocv:function:: virtual FormatInfo gpucodec::RawVideoSource::format() const = 0
index 739ec0d,0000000..f1e20dc
mode 100644,000000..100644
--- /dev/null
@@@ -1,189 -1,0 +1,192 @@@
 +Video Encoding
 +==============
 +
 +.. highlight:: cpp
 +
 +
 +
 +gpucodec::VideoWriter
 +---------------------
 +Video writer interface.
 +
 +.. ocv:class:: gpucodec::VideoWriter
 +
 +The implementation uses H264 video codec.
 +
 +.. note:: Currently only Windows platform is supported.
 +
++.. Sample code::
++
++   * : An example on how to use the videoWriter class can be found at opencv_source_code/samples/gpu/video_writer.cpp
 +
 +
 +gpucodec::VideoWriter::write
 +----------------------------
 +Writes the next video frame.
 +
 +.. ocv:function:: void gpucodec::VideoWriter::write(InputArray frame, bool lastFrame = false) = 0
 +
 +    :param frame: The written frame.
 +
 +    :param lastFrame: Indicates that it is end of stream. The parameter can be ignored.
 +
 +The method write the specified image to video file. The image must have the same size and the same surface format as has been specified when opening the video writer.
 +
 +
 +
 +gpucodec::createVideoWriter
 +---------------------------
 +Creates video writer.
 +
 +.. ocv:function:: Ptr<gpucodec::VideoWriter> gpucodec::createVideoWriter(const String& fileName, Size frameSize, double fps, SurfaceFormat format = SF_BGR)
 +.. ocv:function:: Ptr<gpucodec::VideoWriter> gpucodec::createVideoWriter(const String& fileName, Size frameSize, double fps, const EncoderParams& params, SurfaceFormat format = SF_BGR)
 +.. ocv:function:: Ptr<gpucodec::VideoWriter> gpucodec::createVideoWriter(const Ptr<EncoderCallBack>& encoderCallback, Size frameSize, double fps, SurfaceFormat format = SF_BGR)
 +.. ocv:function:: Ptr<gpucodec::VideoWriter> gpucodec::createVideoWriter(const Ptr<EncoderCallBack>& encoderCallback, Size frameSize, double fps, const EncoderParams& params, SurfaceFormat format = SF_BGR)
 +
 +    :param fileName: Name of the output video file. Only AVI file format is supported.
 +
 +    :param frameSize: Size of the input video frames.
 +
 +    :param fps: Framerate of the created video stream.
 +
 +    :param params: Encoder parameters. See :ocv:struct:`gpucodec::EncoderParams` .
 +
 +    :param format: Surface format of input frames ( ``SF_UYVY`` , ``SF_YUY2`` , ``SF_YV12`` , ``SF_NV12`` , ``SF_IYUV`` , ``SF_BGR`` or ``SF_GRAY``). BGR or gray frames will be converted to YV12 format before encoding, frames with other formats will be used as is.
 +
 +    :param encoderCallback: Callbacks for video encoder. See :ocv:class:`gpucodec::EncoderCallBack` . Use it if you want to work with raw video stream.
 +
 +The constructors initialize video writer. FFMPEG is used to write videos. User can implement own multiplexing with :ocv:class:`gpucodec::EncoderCallBack` .
 +
 +
 +
 +gpucodec::EncoderParams
 +-----------------------
 +.. ocv:struct:: gpucodec::EncoderParams
 +
 +Different parameters for CUDA video encoder. ::
 +
 +    struct EncoderParams
 +    {
 +        int       P_Interval;      //    NVVE_P_INTERVAL,
 +        int       IDR_Period;      //    NVVE_IDR_PERIOD,
 +        int       DynamicGOP;      //    NVVE_DYNAMIC_GOP,
 +        int       RCType;          //    NVVE_RC_TYPE,
 +        int       AvgBitrate;      //    NVVE_AVG_BITRATE,
 +        int       PeakBitrate;     //    NVVE_PEAK_BITRATE,
 +        int       QP_Level_Intra;  //    NVVE_QP_LEVEL_INTRA,
 +        int       QP_Level_InterP; //    NVVE_QP_LEVEL_INTER_P,
 +        int       QP_Level_InterB; //    NVVE_QP_LEVEL_INTER_B,
 +        int       DeblockMode;     //    NVVE_DEBLOCK_MODE,
 +        int       ProfileLevel;    //    NVVE_PROFILE_LEVEL,
 +        int       ForceIntra;      //    NVVE_FORCE_INTRA,
 +        int       ForceIDR;        //    NVVE_FORCE_IDR,
 +        int       ClearStat;       //    NVVE_CLEAR_STAT,
 +        int       DIMode;          //    NVVE_SET_DEINTERLACE,
 +        int       Presets;         //    NVVE_PRESETS,
 +        int       DisableCabac;    //    NVVE_DISABLE_CABAC,
 +        int       NaluFramingType; //    NVVE_CONFIGURE_NALU_FRAMING_TYPE
 +        int       DisableSPSPPS;   //    NVVE_DISABLE_SPS_PPS
 +
 +        EncoderParams();
 +        explicit EncoderParams(const String& configFile);
 +
 +        void load(const String& configFile);
 +        void save(const String& configFile) const;
 +    };
 +
 +
 +
 +gpucodec::EncoderParams::EncoderParams
 +--------------------------------------
 +Constructors.
 +
 +.. ocv:function:: gpucodec::EncoderParams::EncoderParams()
 +.. ocv:function:: gpucodec::EncoderParams::EncoderParams(const String& configFile)
 +
 +    :param configFile: Config file name.
 +
 +Creates default parameters or reads parameters from config file.
 +
 +
 +
 +gpucodec::EncoderParams::load
 +-----------------------------
 +Reads parameters from config file.
 +
 +.. ocv:function:: void gpucodec::EncoderParams::load(const String& configFile)
 +
 +    :param configFile: Config file name.
 +
 +
 +
 +gpucodec::EncoderParams::save
 +-----------------------------
 +Saves parameters to config file.
 +
 +.. ocv:function:: void gpucodec::EncoderParams::save(const String& configFile) const
 +
 +    :param configFile: Config file name.
 +
 +
 +
 +gpucodec::EncoderCallBack
 +-------------------------
 +.. ocv:class:: gpucodec::EncoderCallBack
 +
 +Callbacks for CUDA video encoder. ::
 +
 +    class EncoderCallBack
 +    {
 +    public:
 +        enum PicType
 +        {
 +            IFRAME = 1,
 +            PFRAME = 2,
 +            BFRAME = 3
 +        };
 +
 +        virtual ~EncoderCallBack() {}
 +
 +        virtual unsigned char* acquireBitStream(int* bufferSize) = 0;
 +        virtual void releaseBitStream(unsigned char* data, int size) = 0;
 +        virtual void onBeginFrame(int frameNumber, PicType picType) = 0;
 +        virtual void onEndFrame(int frameNumber, PicType picType) = 0;
 +    };
 +
 +
 +
 +gpucodec::EncoderCallBack::acquireBitStream
 +-------------------------------------------
 +Callback function to signal the start of bitstream that is to be encoded.
 +
 +.. ocv:function:: virtual uchar* gpucodec::EncoderCallBack::acquireBitStream(int* bufferSize) = 0
 +
 +Callback must allocate buffer for CUDA encoder and return pointer to it and it's size.
 +
 +
 +
 +gpucodec::EncoderCallBack::releaseBitStream
 +-------------------------------------------
 +Callback function to signal that the encoded bitstream is ready to be written to file.
 +
 +.. ocv:function:: virtual void gpucodec::EncoderCallBack::releaseBitStream(unsigned char* data, int size) = 0
 +
 +
 +
 +gpucodec::EncoderCallBack::onBeginFrame
 +---------------------------------------
 +Callback function to signal that the encoding operation on the frame has started.
 +
 +.. ocv:function:: virtual void gpucodec::EncoderCallBack::onBeginFrame(int frameNumber, PicType picType) = 0
 +
 +    :param picType: Specify frame type (I-Frame, P-Frame or B-Frame).
 +
 +
 +
 +gpucodec::EncoderCallBack::onEndFrame
 +-------------------------------------
 +Callback function signals that the encoding operation on the frame has finished.
 +
 +.. ocv:function:: virtual void gpucodec::EncoderCallBack::onEndFrame(int frameNumber, PicType picType) = 0
 +
 +    :param picType: Specify frame type (I-Frame, P-Frame or B-Frame).
index 925b05f,0000000..4e90961
mode 100644,000000..100644
--- /dev/null
@@@ -1,334 -1,0 +1,336 @@@
 +Image Filtering
 +===============
 +
 +.. highlight:: cpp
 +
 +Functions and classes described in this section are used to perform various linear or non-linear filtering operations on 2D images.
 +
++.. Sample code::
 +
++   * : An example containing all basic morphology operators like erode and dilate can be found at opencv_source_code/samples/gpu/morphology.cpp
 +
 +gpu::Filter
 +-----------
 +.. ocv:class:: gpu::Filter
 +
 +Common interface for all GPU filters ::
 +
 +    class CV_EXPORTS Filter : public Algorithm
 +    {
 +    public:
 +        virtual void apply(InputArray src, OutputArray dst, Stream& stream = Stream::Null()) = 0;
 +    };
 +
 +
 +
 +gpu::Filter::apply
 +------------------
 +Applies the specified filter to the image.
 +
 +.. ocv:function:: void gpu::Filter::apply(InputArray src, OutputArray dst, Stream& stream = Stream::Null()) = 0
 +
 +    :param src: Input image.
 +
 +    :param dst: Output image.
 +
 +    :param stream: Stream for the asynchronous version.
 +
 +
 +
 +gpu::createBoxFilter
 +--------------------
 +Creates a normalized 2D box filter.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createBoxFilter(int srcType, int dstType, Size ksize, Point anchor = Point(-1,-1), int borderMode = BORDER_DEFAULT, Scalar borderVal = Scalar::all(0))
 +
 +    :param srcType: Input image type. Only ``CV_8UC1`` and ``CV_8UC4`` are supported for now.
 +
 +    :param dstType: Output image type. Only the same type as ``src`` is supported for now.
 +
 +    :param ksize: Kernel size.
 +
 +    :param anchor: Anchor point. The default value ``Point(-1, -1)`` means that the anchor is at the kernel center.
 +
 +    :param borderMode: Pixel extrapolation method. For details, see :ocv:func:`borderInterpolate` .
 +
 +    :param borderVal: Default border value.
 +
 +.. seealso:: :ocv:func:`boxFilter`
 +
 +
 +
 +gpu::createLinearFilter
 +-----------------------
 +Creates a non-separable linear 2D filter.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createLinearFilter(int srcType, int dstType, InputArray kernel, Point anchor = Point(-1,-1), int borderMode = BORDER_DEFAULT, Scalar borderVal = Scalar::all(0))
 +
 +    :param srcType: Input image type. Supports  ``CV_8U``  ,  ``CV_16U``  and  ``CV_32F``  one and four channel image.
 +
 +    :param dstType: Output image type. Only the same type as ``src`` is supported for now.
 +
 +    :param kernel: 2D array of filter coefficients.
 +
 +    :param anchor: Anchor point. The default value Point(-1, -1) means that the anchor is at the kernel center.
 +
 +    :param borderMode: Pixel extrapolation method. For details, see :ocv:func:`borderInterpolate` .
 +
 +    :param borderVal: Default border value.
 +
 +.. seealso:: :ocv:func:`filter2D`
 +
 +
 +
 +gpu::createLaplacianFilter
 +--------------------------
 +Creates a Laplacian operator.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createLaplacianFilter(int srcType, int dstType, int ksize = 1, double scale = 1, int borderMode = BORDER_DEFAULT, Scalar borderVal = Scalar::all(0))
 +
 +    :param srcType: Input image type. Supports  ``CV_8U``  ,  ``CV_16U``  and  ``CV_32F``  one and four channel image.
 +
 +    :param dstType: Output image type. Only the same type as ``src`` is supported for now.
 +
 +    :param ksize: Aperture size used to compute the second-derivative filters (see :ocv:func:`getDerivKernels`). It must be positive and odd. Only  ``ksize``  = 1 and  ``ksize``  = 3 are supported.
 +
 +    :param scale: Optional scale factor for the computed Laplacian values. By default, no scaling is applied (see  :ocv:func:`getDerivKernels` ).
 +
 +    :param borderMode: Pixel extrapolation method. For details, see :ocv:func:`borderInterpolate` .
 +
 +    :param borderVal: Default border value.
 +
 +.. seealso:: :ocv:func:`Laplacian`
 +
 +
 +
 +gpu::createSeparableLinearFilter
 +--------------------------------
 +Creates a separable linear filter.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createSeparableLinearFilter(int srcType, int dstType, InputArray rowKernel, InputArray columnKernel, Point anchor = Point(-1,-1), int rowBorderMode = BORDER_DEFAULT, int columnBorderMode = -1)
 +
 +    :param srcType: Source array type.
 +
 +    :param dstType: Destination array type.
 +
 +    :param rowKernel: Horizontal filter coefficients. Support kernels with ``size <= 32`` .
 +
 +    :param columnKernel: Vertical filter coefficients. Support kernels with ``size <= 32`` .
 +
 +    :param anchor: Anchor position within the kernel. Negative values mean that anchor is positioned at the aperture center.
 +
 +    :param rowBorderMode: Pixel extrapolation method in the vertical direction For details, see  :ocv:func:`borderInterpolate`.
 +
 +    :param columnBorderMode: Pixel extrapolation method in the horizontal direction.
 +
 +.. seealso:: :ocv:func:`sepFilter2D`
 +
 +
 +
 +gpu::createDerivFilter
 +----------------------
 +Creates a generalized Deriv operator.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createDerivFilter(int srcType, int dstType, int dx, int dy, int ksize, bool normalize = false, double scale = 1, int rowBorderMode = BORDER_DEFAULT, int columnBorderMode = -1)
 +
 +    :param srcType: Source image type.
 +
 +    :param dstType: Destination array type.
 +
 +    :param dx: Derivative order in respect of x.
 +
 +    :param dy: Derivative order in respect of y.
 +
 +    :param ksize: Aperture size. See  :ocv:func:`getDerivKernels` for details.
 +
 +    :param normalize: Flag indicating whether to normalize (scale down) the filter coefficients or not. See  :ocv:func:`getDerivKernels` for details.
 +
 +    :param scale: Optional scale factor for the computed derivative values. By default, no scaling is applied. For details, see  :ocv:func:`getDerivKernels` .
 +
 +    :param rowBorderMode: Pixel extrapolation method in the vertical direction. For details, see  :ocv:func:`borderInterpolate`.
 +
 +    :param columnBorderMode: Pixel extrapolation method in the horizontal direction.
 +
 +
 +
 +gpu::createSobelFilter
 +----------------------
 +Creates a Sobel operator.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createSobelFilter(int srcType, int dstType, int dx, int dy, int ksize = 3, double scale = 1, int rowBorderMode = BORDER_DEFAULT, int columnBorderMode = -1)
 +
 +    :param srcType: Source image type.
 +
 +    :param dstType: Destination array type.
 +
 +    :param dx: Derivative order in respect of x.
 +
 +    :param dy: Derivative order in respect of y.
 +
 +    :param ksize: Size of the extended Sobel kernel. Possible values are 1, 3, 5 or 7.
 +
 +    :param scale: Optional scale factor for the computed derivative values. By default, no scaling is applied. For details, see  :ocv:func:`getDerivKernels` .
 +
 +    :param rowBorderMode: Pixel extrapolation method in the vertical direction. For details, see  :ocv:func:`borderInterpolate`.
 +
 +    :param columnBorderMode: Pixel extrapolation method in the horizontal direction.
 +
 +.. seealso:: :ocv:func:`Sobel`
 +
 +
 +
 +gpu::createScharrFilter
 +-----------------------
 +Creates a vertical or horizontal Scharr operator.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createScharrFilter(int srcType, int dstType, int dx, int dy, double scale = 1, int rowBorderMode = BORDER_DEFAULT, int columnBorderMode = -1)
 +
 +    :param srcType: Source image type.
 +
 +    :param dstType: Destination array type.
 +
 +    :param dx: Order of the derivative x.
 +
 +    :param dy: Order of the derivative y.
 +
 +    :param scale: Optional scale factor for the computed derivative values. By default, no scaling is applied. See  :ocv:func:`getDerivKernels`  for details.
 +
 +    :param rowBorderMode: Pixel extrapolation method in the vertical direction. For details, see  :ocv:func:`borderInterpolate`.
 +
 +    :param columnBorderMode: Pixel extrapolation method in the horizontal direction.
 +
 +.. seealso:: :ocv:func:`Scharr`
 +
 +
 +
 +gpu::createGaussianFilter
 +-------------------------
 +Creates a Gaussian filter.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createGaussianFilter(int srcType, int dstType, Size ksize, double sigma1, double sigma2 = 0, int rowBorderMode = BORDER_DEFAULT, int columnBorderMode = -1)
 +
 +    :param srcType: Source image type.
 +
 +    :param dstType: Destination array type.
 +
 +    :param ksize: Aperture size. See  :ocv:func:`getGaussianKernel` for details.
 +
 +    :param sigma1: Gaussian sigma in the horizontal direction. See  :ocv:func:`getGaussianKernel` for details.
 +
 +    :param sigma2: Gaussian sigma in the vertical direction. If 0, then  :math:`\texttt{sigma2}\leftarrow\texttt{sigma1}` .
 +
 +    :param rowBorderMode: Pixel extrapolation method in the vertical direction. For details, see  :ocv:func:`borderInterpolate`.
 +
 +    :param columnBorderMode: Pixel extrapolation method in the horizontal direction.
 +
 +.. seealso:: :ocv:func:`GaussianBlur`
 +
 +
 +
 +gpu::createMorphologyFilter
 +---------------------------
 +Creates a 2D morphological filter.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createMorphologyFilter(int op, int srcType, InputArray kernel, Point anchor = Point(-1, -1), int iterations = 1)
 +
 +    :param op: Type of morphological operation. The following types are possible:
 +
 +        * **MORPH_ERODE** erode
 +
 +        * **MORPH_DILATE** dilate
 +
 +        * **MORPH_OPEN** opening
 +
 +        * **MORPH_CLOSE** closing
 +
 +        * **MORPH_GRADIENT** morphological gradient
 +
 +        * **MORPH_TOPHAT** "top hat"
 +
 +        * **MORPH_BLACKHAT** "black hat"
 +
 +    :param srcType: Input/output image type. Only  ``CV_8UC1``  and  ``CV_8UC4``  are supported.
 +
 +    :param kernel: 2D 8-bit structuring element for the morphological operation.
 +
 +    :param anchor: Anchor position within the structuring element. Negative values mean that the anchor is at the center.
 +
 +    :param iterations: Number of times erosion and dilation to be applied.
 +
 +.. seealso:: :ocv:func:`morphologyEx`
 +
 +
 +
 +gpu::createBoxMaxFilter
 +-----------------------
 +Creates the maximum filter.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createBoxMaxFilter(int srcType, Size ksize, Point anchor = Point(-1, -1), int borderMode = BORDER_DEFAULT, Scalar borderVal = Scalar::all(0))
 +
 +    :param srcType: Input/output image type. Only  ``CV_8UC1``  and  ``CV_8UC4`` are supported.
 +
 +    :param ksize: Kernel size.
 +
 +    :param anchor: Anchor point. The default value (-1) means that the anchor is at the kernel center.
 +
 +    :param borderMode: Pixel extrapolation method. For details, see :ocv:func:`borderInterpolate` .
 +
 +    :param borderVal: Default border value.
 +
 +
 +
 +gpu::createBoxMinFilter
 +-----------------------
 +Creates the minimum filter.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createBoxMinFilter(int srcType, Size ksize, Point anchor = Point(-1, -1), int borderMode = BORDER_DEFAULT, Scalar borderVal = Scalar::all(0))
 +
 +    :param srcType: Input/output image type. Only  ``CV_8UC1``  and  ``CV_8UC4`` are supported.
 +
 +    :param ksize: Kernel size.
 +
 +    :param anchor: Anchor point. The default value (-1) means that the anchor is at the kernel center.
 +
 +    :param borderMode: Pixel extrapolation method. For details, see :ocv:func:`borderInterpolate` .
 +
 +    :param borderVal: Default border value.
 +
 +
 +
 +gpu::createRowSumFilter
 +-----------------------
 +Creates a horizontal 1D box filter.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createRowSumFilter(int srcType, int dstType, int ksize, int anchor = -1, int borderMode = BORDER_DEFAULT, Scalar borderVal = Scalar::all(0))
 +
 +    :param srcType: Input image type. Only ``CV_8UC1`` type is supported for now.
 +
 +    :param sumType: Output image type. Only ``CV_32FC1`` type is supported for now.
 +
 +    :param ksize: Kernel size.
 +
 +    :param anchor: Anchor point. The default value (-1) means that the anchor is at the kernel center.
 +
 +    :param borderMode: Pixel extrapolation method. For details, see :ocv:func:`borderInterpolate` .
 +
 +    :param borderVal: Default border value.
 +
 +
 +
 +gpu::createColumnSumFilter
 +--------------------------
 +Creates a vertical 1D box filter.
 +
 +.. ocv:function:: Ptr<Filter> gpu::createColumnSumFilter(int srcType, int dstType, int ksize, int anchor = -1, int borderMode = BORDER_DEFAULT, Scalar borderVal = Scalar::all(0))
 +
 +    :param srcType: Input image type. Only ``CV_8UC1`` type is supported for now.
 +
 +    :param sumType: Output image type. Only ``CV_32FC1`` type is supported for now.
 +
 +    :param ksize: Kernel size.
 +
 +    :param anchor: Anchor point. The default value (-1) means that the anchor is at the kernel center.
 +
 +    :param borderMode: Pixel extrapolation method. For details, see :ocv:func:`borderInterpolate` .
 +
 +    :param borderVal: Default border value.
index 5cdcd57,0000000..f3863cb
mode 100644,000000..100644
--- /dev/null
@@@ -1,128 -1,0 +1,131 @@@
 +Color space processing
 +======================
 +
 +.. highlight:: cpp
 +
 +
 +
 +gpu::cvtColor
 +-------------
 +Converts an image from one color space to another.
 +
 +.. ocv:function:: void gpu::cvtColor(InputArray src, OutputArray dst, int code, int dcn = 0, Stream& stream = Stream::Null())
 +
 +    :param src: Source image with  ``CV_8U`` , ``CV_16U`` , or  ``CV_32F`` depth and 1, 3, or 4 channels.
 +
 +    :param dst: Destination image.
 +
 +    :param code: Color space conversion code. For details, see  :ocv:func:`cvtColor` .
 +
 +    :param dcn: Number of channels in the destination image. If the parameter is 0, the number of the channels is derived automatically from  ``src`` and the  ``code`` .
 +
 +    :param stream: Stream for the asynchronous version.
 +
 +3-channel color spaces (like ``HSV``, ``XYZ``, and so on) can be stored in a 4-channel image for better performance.
 +
 +.. seealso:: :ocv:func:`cvtColor`
 +
 +
 +
 +gpu::demosaicing
 +----------------
 +Converts an image from Bayer pattern to RGB or grayscale.
 +
 +.. ocv:function:: void gpu::demosaicing(InputArray src, OutputArray dst, int code, int dcn = -1, Stream& stream = Stream::Null())
 +
 +    :param src: Source image (8-bit or 16-bit single channel).
 +
 +    :param dst: Destination image.
 +
 +    :param code: Color space conversion code (see the description below).
 +
 +    :param dcn: Number of channels in the destination image. If the parameter is 0, the number of the channels is derived automatically from  ``src`` and the  ``code`` .
 +
 +    :param stream: Stream for the asynchronous version.
 +
 +The function can do the following transformations:
 +
 +* Demosaicing using bilinear interpolation
 +
 +    * ``COLOR_BayerBG2GRAY`` , ``COLOR_BayerGB2GRAY`` , ``COLOR_BayerRG2GRAY`` , ``COLOR_BayerGR2GRAY``
 +
 +    * ``COLOR_BayerBG2BGR`` , ``COLOR_BayerGB2BGR`` , ``COLOR_BayerRG2BGR`` , ``COLOR_BayerGR2BGR``
 +
 +* Demosaicing using Malvar-He-Cutler algorithm ([MHT2011]_)
 +
 +    * ``COLOR_BayerBG2GRAY_MHT`` , ``COLOR_BayerGB2GRAY_MHT`` , ``COLOR_BayerRG2GRAY_MHT`` , ``COLOR_BayerGR2GRAY_MHT``
 +
 +    * ``COLOR_BayerBG2BGR_MHT`` , ``COLOR_BayerGB2BGR_MHT`` , ``COLOR_BayerRG2BGR_MHT`` , ``COLOR_BayerGR2BGR_MHT``
 +
 +.. seealso:: :ocv:func:`cvtColor`
 +
 +
 +
 +gpu::swapChannels
 +-----------------
 +Exchanges the color channels of an image in-place.
 +
 +.. ocv:function:: void gpu::swapChannels(InputOutputArray image, const int dstOrder[4], Stream& stream = Stream::Null())
 +
 +    :param image: Source image. Supports only ``CV_8UC4`` type.
 +
 +    :param dstOrder: Integer array describing how channel values are permutated. The n-th entry of the array contains the number of the channel that is stored in the n-th channel of the output image. E.g. Given an RGBA image, aDstOrder = [3,2,1,0] converts this to ABGR channel order.
 +
 +    :param stream: Stream for the asynchronous version.
 +
 +The methods support arbitrary permutations of the original channels, including replication.
 +
 +
 +
 +gpu::gammaCorrection
 +--------------------
 +Routines for correcting image color gamma.
 +
 +.. ocv:function:: void gpu::gammaCorrection(InputArray src, OutputArray dst, bool forward = true, Stream& stream = Stream::Null())
 +
 +    :param src: Source image (3- or 4-channel 8 bit).
 +
 +    :param dst: Destination image.
 +
 +    :param forward: ``true`` for forward gamma correction or ``false`` for inverse gamma correction.
 +
 +    :param stream: Stream for the asynchronous version.
 +
 +
 +
 +gpu::alphaComp
 +--------------
 +Composites two images using alpha opacity values contained in each image.
 +
 +.. ocv:function:: void gpu::alphaComp(InputArray img1, InputArray img2, OutputArray dst, int alpha_op, Stream& stream = Stream::Null())
 +
 +    :param img1: First image. Supports ``CV_8UC4`` , ``CV_16UC4`` , ``CV_32SC4`` and ``CV_32FC4`` types.
 +
 +    :param img2: Second image. Must have the same size and the same type as ``img1`` .
 +
 +    :param dst: Destination image.
 +
 +    :param alpha_op: Flag specifying the alpha-blending operation:
 +
 +            * **ALPHA_OVER**
 +            * **ALPHA_IN**
 +            * **ALPHA_OUT**
 +            * **ALPHA_ATOP**
 +            * **ALPHA_XOR**
 +            * **ALPHA_PLUS**
 +            * **ALPHA_OVER_PREMUL**
 +            * **ALPHA_IN_PREMUL**
 +            * **ALPHA_OUT_PREMUL**
 +            * **ALPHA_ATOP_PREMUL**
 +            * **ALPHA_XOR_PREMUL**
 +            * **ALPHA_PLUS_PREMUL**
 +            * **ALPHA_PREMUL**
 +
 +    :param stream: Stream for the asynchronous version.
 +
++.. Sample code::
++
++   * : An example demonstrating the use of alphaComp can be found at opencv_source_code/samples/gpu/alpha_comp.cpp
 +
 +
 +.. [MHT2011] Pascal Getreuer, Malvar-He-Cutler Linear Image Demosaicking, Image Processing On Line, 2011
index eb0f83c,0000000..bf4185f
mode 100644,000000..100644
--- /dev/null
@@@ -1,312 -1,0 +1,315 @@@
 +Hough Transform
 +===============
 +
 +.. highlight:: cpp
 +
 +
 +
 +gpu::HoughLinesDetector
 +-----------------------
 +.. ocv:class:: gpu::HoughLinesDetector : public Algorithm
 +
 +Base class for lines detector algorithm. ::
 +
 +    class CV_EXPORTS HoughLinesDetector : public Algorithm
 +    {
 +    public:
 +        virtual void detect(InputArray src, OutputArray lines) = 0;
 +        virtual void downloadResults(InputArray d_lines, OutputArray h_lines, OutputArray h_votes = noArray()) = 0;
 +
 +        virtual void setRho(float rho) = 0;
 +        virtual float getRho() const = 0;
 +
 +        virtual void setTheta(float theta) = 0;
 +        virtual float getTheta() const = 0;
 +
 +        virtual void setThreshold(int threshold) = 0;
 +        virtual int getThreshold() const = 0;
 +
 +        virtual void setDoSort(bool doSort) = 0;
 +        virtual bool getDoSort() const = 0;
 +
 +        virtual void setMaxLines(int maxLines) = 0;
 +        virtual int getMaxLines() const = 0;
 +    };
 +
 +
 +
 +gpu::HoughLinesDetector::detect
 +-------------------------------
 +Finds lines in a binary image using the classical Hough transform.
 +
 +.. ocv:function:: void gpu::HoughLinesDetector::detect(InputArray src, OutputArray lines)
 +
 +    :param src: 8-bit, single-channel binary source image.
 +
 +    :param lines: Output vector of lines. Each line is represented by a two-element vector  :math:`(\rho, \theta)` .  :math:`\rho`  is the distance from the coordinate origin  :math:`(0,0)`  (top-left corner of the image).  :math:`\theta`  is the line rotation angle in radians ( :math:`0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}` ).
 +
 +.. seealso:: :ocv:func:`HoughLines`
 +
 +
 +
 +gpu::HoughLinesDetector::downloadResults
 +----------------------------------------
 +Downloads results from :ocv:func:`gpu::HoughLinesDetector::detect` to host memory.
 +
 +.. ocv:function:: void gpu::HoughLinesDetector::downloadResults(InputArray d_lines, OutputArray h_lines, OutputArray h_votes = noArray())
 +
 +    :param d_lines: Result of :ocv:func:`gpu::HoughLinesDetector::detect` .
 +
 +    :param h_lines: Output host array.
 +
 +    :param h_votes: Optional output array for line's votes.
 +
 +
 +
 +gpu::createHoughLinesDetector
 +-----------------------------
 +Creates implementation for :ocv:class:`gpu::HoughLinesDetector` .
 +
 +.. ocv:function:: Ptr<HoughLinesDetector> gpu::createHoughLinesDetector(float rho, float theta, int threshold, bool doSort = false, int maxLines = 4096)
 +
 +    :param rho: Distance resolution of the accumulator in pixels.
 +
 +    :param theta: Angle resolution of the accumulator in radians.
 +
 +    :param threshold: Accumulator threshold parameter. Only those lines are returned that get enough votes ( :math:`>\texttt{threshold}` ).
 +
 +    :param doSort: Performs lines sort by votes.
 +
 +    :param maxLines: Maximum number of output lines.
 +
 +
 +
 +gpu::HoughSegmentDetector
 +-------------------------
 +.. ocv:class:: gpu::HoughSegmentDetector : public Algorithm
 +
 +Base class for line segments detector algorithm. ::
 +
 +    class CV_EXPORTS HoughSegmentDetector : public Algorithm
 +    {
 +    public:
 +        virtual void detect(InputArray src, OutputArray lines) = 0;
 +
 +        virtual void setRho(float rho) = 0;
 +        virtual float getRho() const = 0;
 +
 +        virtual void setTheta(float theta) = 0;
 +        virtual float getTheta() const = 0;
 +
 +        virtual void setMinLineLength(int minLineLength) = 0;
 +        virtual int getMinLineLength() const = 0;
 +
 +        virtual void setMaxLineGap(int maxLineGap) = 0;
 +        virtual int getMaxLineGap() const = 0;
 +
 +        virtual void setMaxLines(int maxLines) = 0;
 +        virtual int getMaxLines() const = 0;
 +    };
 +
++.. Sample code::
++
++   * : An example using the Hough segment detector can be found at opencv_source_code/samples/gpu/houghlines.cpp
 +
 +
 +gpu::HoughSegmentDetector::detect
 +---------------------------------
 +Finds line segments in a binary image using the probabilistic Hough transform.
 +
 +.. ocv:function:: void gpu::HoughSegmentDetector::detect(InputArray src, OutputArray lines)
 +
 +    :param src: 8-bit, single-channel binary source image.
 +
 +    :param lines: Output vector of lines. Each line is represented by a 4-element vector  :math:`(x_1, y_1, x_2, y_2)` , where  :math:`(x_1,y_1)`  and  :math:`(x_2, y_2)`  are the ending points of each detected line segment.
 +
 +.. seealso:: :ocv:func:`HoughLinesP`
 +
 +
 +
 +gpu::createHoughSegmentDetector
 +-------------------------------
 +Creates implementation for :ocv:class:`gpu::HoughSegmentDetector` .
 +
 +.. ocv:function:: Ptr<HoughSegmentDetector> gpu::createHoughSegmentDetector(float rho, float theta, int minLineLength, int maxLineGap, int maxLines = 4096)
 +
 +    :param rho: Distance resolution of the accumulator in pixels.
 +
 +    :param theta: Angle resolution of the accumulator in radians.
 +
 +    :param minLineLength: Minimum line length. Line segments shorter than that are rejected.
 +
 +    :param maxLineGap: Maximum allowed gap between points on the same line to link them.
 +
 +    :param maxLines: Maximum number of output lines.
 +
 +
 +
 +gpu::HoughCirclesDetector
 +-------------------------
 +.. ocv:class:: gpu::HoughCirclesDetector : public Algorithm
 +
 +Base class for circles detector algorithm. ::
 +
 +    class CV_EXPORTS HoughCirclesDetector : public Algorithm
 +    {
 +    public:
 +        virtual void detect(InputArray src, OutputArray circles) = 0;
 +
 +        virtual void setDp(float dp) = 0;
 +        virtual float getDp() const = 0;
 +
 +        virtual void setMinDist(float minDist) = 0;
 +        virtual float getMinDist() const = 0;
 +
 +        virtual void setCannyThreshold(int cannyThreshold) = 0;
 +        virtual int getCannyThreshold() const = 0;
 +
 +        virtual void setVotesThreshold(int votesThreshold) = 0;
 +        virtual int getVotesThreshold() const = 0;
 +
 +        virtual void setMinRadius(int minRadius) = 0;
 +        virtual int getMinRadius() const = 0;
 +
 +        virtual void setMaxRadius(int maxRadius) = 0;
 +        virtual int getMaxRadius() const = 0;
 +
 +        virtual void setMaxCircles(int maxCircles) = 0;
 +        virtual int getMaxCircles() const = 0;
 +    };
 +
 +
 +
 +gpu::HoughCirclesDetector::detect
 +---------------------------------
 +Finds circles in a grayscale image using the Hough transform.
 +
 +.. ocv:function:: void gpu::HoughCirclesDetector::detect(InputArray src, OutputArray circles)
 +
 +    :param src: 8-bit, single-channel grayscale input image.
 +
 +    :param circles: Output vector of found circles. Each vector is encoded as a 3-element floating-point vector  :math:`(x, y, radius)` .
 +
 +.. seealso:: :ocv:func:`HoughCircles`
 +
 +
 +
 +gpu::createHoughCirclesDetector
 +-------------------------------
 +Creates implementation for :ocv:class:`gpu::HoughCirclesDetector` .
 +
 +.. ocv:function:: Ptr<HoughCirclesDetector> gpu::createHoughCirclesDetector(float dp, float minDist, int cannyThreshold, int votesThreshold, int minRadius, int maxRadius, int maxCircles = 4096)
 +
 +    :param dp: Inverse ratio of the accumulator resolution to the image resolution. For example, if  ``dp=1`` , the accumulator has the same resolution as the input image. If  ``dp=2`` , the accumulator has half as big width and height.
 +
 +    :param minDist: Minimum distance between the centers of the detected circles. If the parameter is too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is too large, some circles may be missed.
 +
 +    :param cannyThreshold: The higher threshold of the two passed to Canny edge detector (the lower one is twice smaller).
 +
 +    :param votesThreshold: The accumulator threshold for the circle centers at the detection stage. The smaller it is, the more false circles may be detected.
 +
 +    :param minRadius: Minimum circle radius.
 +
 +    :param maxRadius: Maximum circle radius.
 +
 +    :param maxCircles: Maximum number of output circles.
 +
 +
 +
 +gpu::GeneralizedHough
 +---------------------
 +.. ocv:class:: gpu::GeneralizedHough : public Algorithm
 +
 +Base class for generalized hough transform. ::
 +
 +    class CV_EXPORTS GeneralizedHough : public Algorithm
 +    {
 +    public:
 +        static Ptr<GeneralizedHough> create(int method);
 +
 +        virtual void setTemplate(InputArray templ, int cannyThreshold = 100, Point templCenter = Point(-1, -1)) = 0;
 +        virtual void setTemplate(InputArray edges, InputArray dx, InputArray dy, Point templCenter = Point(-1, -1)) = 0;
 +
 +        virtual void detect(InputArray image, OutputArray positions, int cannyThreshold = 100) = 0;
 +        virtual void detect(InputArray edges, InputArray dx, InputArray dy, OutputArray positions) = 0;
 +
 +        virtual void downloadResults(InputArray d_positions, OutputArray h_positions, OutputArray h_votes = noArray()) = 0;
 +    };
 +
 +
 +Finds arbitrary template in the grayscale image using Generalized Hough Transform.
 +
 +
 +
 +gpu::GeneralizedHough::create
 +-----------------------------
 +Creates implementation for :ocv:class:`gpu::GeneralizedHough` .
 +
 +.. ocv:function:: Ptr<GeneralizedHough> gpu::GeneralizedHough::create(int method)
 +
 +    :param method: Combination of flags ( ``cv::GeneralizedHough::GHT_POSITION`` , ``cv::GeneralizedHough::GHT_SCALE`` , ``cv::GeneralizedHough::GHT_ROTATION`` ) specifying transformation to find.
 +
 +For full affine transformations (move + scale + rotation) [Guil1999]_ algorithm is used, otherwise [Ballard1981]_ algorithm is used.
 +
 +
 +
 +gpu::GeneralizedHough::setTemplate
 +----------------------------------
 +Set template to search.
 +
 +.. ocv:function:: void gpu::GeneralizedHough::setTemplate(InputArray templ, int cannyThreshold = 100, Point templCenter = Point(-1, -1))
 +
 +.. ocv:function:: void gpu::GeneralizedHough::setTemplate(InputArray edges, InputArray dx, InputArray dy, Point templCenter = Point(-1, -1))
 +
 +    :param templ: Template image. Canny edge detector will be applied to extract template edges.
 +
 +    :param cannyThreshold: Threshold value for Canny edge detector.
 +
 +    :param templCenter: Center for rotation. By default image center will be used.
 +
 +    :param edges: Edge map for template image.
 +
 +    :param dx: First derivative of template image in the vertical direction. Support only ``CV_32S`` type.
 +
 +    :param dy: First derivative of template image in the horizontal direction. Support only ``CV_32S`` type.
 +
 +
 +
 +gpu::GeneralizedHough::detect
 +-----------------------------
 +Finds template (set by :ocv:func:`gpu::GeneralizedHough::setTemplate` ) in the grayscale image.
 +
 +.. ocv:function:: void gpu::GeneralizedHough::detect(InputArray image, OutputArray positions, int cannyThreshold = 100)
 +
 +.. ocv:function:: void gpu::GeneralizedHough::detect(InputArray edges, InputArray dx, InputArray dy, OutputArray positions)
 +
 +    :param templ: Input image. Canny edge detector will be applied to extract template edges.
 +
 +    :param positions: Output vector of found objects. Each vector is encoded as a 4-element floating-point vector  :math:`(x, y, scale, angle)` .
 +
 +    :param cannyThreshold: Threshold value for Canny edge detector.
 +
 +    :param edges: Edge map for input image.
 +
 +    :param dx: First derivative of input image in the vertical direction. Support only ``CV_32S`` type.
 +
 +    :param dy: First derivative of input image in the horizontal direction. Support only ``CV_32S`` type.
 +
 +
 +
 +gpu::GeneralizedHough::downloadResults
 +--------------------------------------
 +Downloads results from :ocv:func:`gpu::GeneralizedHough::detect` to host memory.
 +
 +.. ocv:function:: void gpu::GeneralizedHough::downloadResult(InputArray d_positions, OutputArray h_positions, OutputArray h_votes = noArray())
 +
 +    :param d_lines: Result of :ocv:func:`gpu::GeneralizedHough::detect` .
 +
 +    :param h_lines: Output host array.
 +
 +    :param h_votes: Optional output array for votes. Each vector is encoded as a 3-element integer-point vector  :math:`(position_votes, scale_votes, angle_votes)` .
 +
 +
 +
 +.. [Ballard1981] Ballard, D.H. (1981). Generalizing the Hough transform to detect arbitrary shapes. Pattern Recognition 13 (2): 111-122.
 +.. [Guil1999] Guil, N., González-Linares, J.M. and Zapata, E.L. (1999). Bidimensional shape detection using an invariant approach. Pattern Recognition 32 (6): 1025-1038.
index 474c27c,0000000..51931d7
mode 100644,000000..100644
--- /dev/null
@@@ -1,153 -1,0 +1,233 @@@
 +/*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*/
 +
 +#if !defined CUDA_DISABLER
 +
 +#include "opencv2/core/cuda/common.hpp"
 +#include "opencv2/core/cuda/functional.hpp"
 +#include "opencv2/core/cuda/emulation.hpp"
 +#include "opencv2/core/cuda/transform.hpp"
 +
 +using namespace cv::gpu;
 +using namespace cv::gpu::cudev;
 +
 +namespace hist
 +{
 +    __global__ void histogram256Kernel(const uchar* src, int cols, int rows, size_t step, int* hist)
 +    {
 +        __shared__ int shist[256];
 +
 +        const int y = blockIdx.x * blockDim.y + threadIdx.y;
 +        const int tid = threadIdx.y * blockDim.x + threadIdx.x;
 +
 +        shist[tid] = 0;
 +        __syncthreads();
 +
 +        if (y < rows)
 +        {
 +            const unsigned int* rowPtr = (const unsigned int*) (src + y * step);
 +
 +            const int cols_4 = cols / 4;
 +            for (int x = threadIdx.x; x < cols_4; x += blockDim.x)
 +            {
 +                unsigned int data = rowPtr[x];
 +
 +                Emulation::smem::atomicAdd(&shist[(data >>  0) & 0xFFU], 1);
 +                Emulation::smem::atomicAdd(&shist[(data >>  8) & 0xFFU], 1);
 +                Emulation::smem::atomicAdd(&shist[(data >> 16) & 0xFFU], 1);
 +                Emulation::smem::atomicAdd(&shist[(data >> 24) & 0xFFU], 1);
 +            }
 +
 +            if (cols % 4 != 0 && threadIdx.x == 0)
 +            {
 +                for (int x = cols_4 * 4; x < cols; ++x)
 +                {
 +                    unsigned int data = ((const uchar*)rowPtr)[x];
 +                    Emulation::smem::atomicAdd(&shist[data], 1);
 +                }
 +            }
 +        }
 +
 +        __syncthreads();
 +
 +        const int histVal = shist[tid];
 +        if (histVal > 0)
 +            ::atomicAdd(hist + tid, histVal);
 +    }
 +
 +    void histogram256(PtrStepSzb src, int* hist, cudaStream_t stream)
 +    {
 +        const dim3 block(32, 8);
 +        const dim3 grid(divUp(src.rows, block.y));
 +
 +        histogram256Kernel<<<grid, block, 0, stream>>>(src.data, src.cols, src.rows, src.step, hist);
 +        cudaSafeCall( cudaGetLastError() );
 +
 +        if (stream == 0)
 +            cudaSafeCall( cudaDeviceSynchronize() );
 +    }
 +}
 +
 +/////////////////////////////////////////////////////////////////////////
 +
 +namespace hist
 +{
++    __device__ __forceinline__ void histEvenInc(int* shist, uint data, int binSize, int lowerLevel, int upperLevel)
++    {
++        if (data >= lowerLevel && data <= upperLevel)
++        {
++            const uint ind = (data - lowerLevel) / binSize;
++            Emulation::smem::atomicAdd(shist + ind, 1);
++        }
++    }
++
++    __global__ void histEven8u(const uchar* src, const size_t step, const int rows, const int cols,
++                               int* hist, const int binCount, const int binSize, const int lowerLevel, const int upperLevel)
++    {
++        extern __shared__ int shist[];
++
++        const int y = blockIdx.x * blockDim.y + threadIdx.y;
++        const int tid = threadIdx.y * blockDim.x + threadIdx.x;
++
++        if (tid < binCount)
++            shist[tid] = 0;
++
++        __syncthreads();
++
++        if (y < rows)
++        {
++            const uchar* rowPtr = src + y * step;
++            const uint* rowPtr4 = (uint*) rowPtr;
++
++            const int cols_4 = cols / 4;
++            for (int x = threadIdx.x; x < cols_4; x += blockDim.x)
++            {
++                const uint data = rowPtr4[x];
++
++                histEvenInc(shist, (data >>  0) & 0xFFU, binSize, lowerLevel, upperLevel);
++                histEvenInc(shist, (data >>  8) & 0xFFU, binSize, lowerLevel, upperLevel);
++                histEvenInc(shist, (data >> 16) & 0xFFU, binSize, lowerLevel, upperLevel);
++                histEvenInc(shist, (data >> 24) & 0xFFU, binSize, lowerLevel, upperLevel);
++            }
++
++            if (cols % 4 != 0 && threadIdx.x == 0)
++            {
++                for (int x = cols_4 * 4; x < cols; ++x)
++                {
++                    const uchar data = rowPtr[x];
++                    histEvenInc(shist, data, binSize, lowerLevel, upperLevel);
++                }
++            }
++        }
++
++        __syncthreads();
++
++        if (tid < binCount)
++        {
++            const int histVal = shist[tid];
++
++            if (histVal > 0)
++                ::atomicAdd(hist + tid, histVal);
++        }
++    }
++
++    void histEven8u(PtrStepSzb src, int* hist, int binCount, int lowerLevel, int upperLevel, cudaStream_t stream)
++    {
++        const dim3 block(32, 8);
++        const dim3 grid(divUp(src.rows, block.y));
++
++        const int binSize = divUp(upperLevel - lowerLevel, binCount);
++
++        const size_t smem_size = binCount * sizeof(int);
++
++        histEven8u<<<grid, block, smem_size, stream>>>(src.data, src.step, src.rows, src.cols, hist, binCount, binSize, lowerLevel, upperLevel);
++        cudaSafeCall( cudaGetLastError() );
++
++        if (stream == 0)
++            cudaSafeCall( cudaDeviceSynchronize() );
++    }
++}
++
++/////////////////////////////////////////////////////////////////////////
++
++namespace hist
++{
 +    __constant__ int c_lut[256];
 +
 +    struct EqualizeHist : unary_function<uchar, uchar>
 +    {
 +        float scale;
 +
 +        __host__ EqualizeHist(float _scale) : scale(_scale) {}
 +
 +        __device__ __forceinline__ uchar operator ()(uchar val) const
 +        {
 +            const int lut = c_lut[val];
 +            return __float2int_rn(scale * lut);
 +        }
 +    };
 +}
 +
 +namespace cv { namespace gpu { namespace cudev
 +{
 +    template <> struct TransformFunctorTraits<hist::EqualizeHist> : DefaultTransformFunctorTraits<hist::EqualizeHist>
 +    {
 +        enum { smart_shift = 4 };
 +    };
 +}}}
 +
 +namespace hist
 +{
 +    void equalizeHist(PtrStepSzb src, PtrStepSzb dst, const int* lut, cudaStream_t stream)
 +    {
 +        if (stream == 0)
 +            cudaSafeCall( cudaMemcpyToSymbol(c_lut, lut, 256 * sizeof(int), 0, cudaMemcpyDeviceToDevice) );
 +        else
 +            cudaSafeCall( cudaMemcpyToSymbolAsync(c_lut, lut, 256 * sizeof(int), 0, cudaMemcpyDeviceToDevice, stream) );
 +
 +        const float scale = 255.0f / (src.cols * src.rows);
 +
 +        cudev::transform(src, dst, EqualizeHist(scale), WithOutMask(), stream);
 +    }
 +}
 +
 +#endif /* CUDA_DISABLER */
index e54b337,0000000..1baa892
mode 100644,000000..100644
--- /dev/null
@@@ -1,558 -1,0 +1,579 @@@
 +/*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 "precomp.hpp"
 +
 +using namespace cv;
 +using namespace cv::gpu;
 +
 +#if !defined (HAVE_CUDA) || defined (CUDA_DISABLER)
 +
 +void cv::gpu::calcHist(InputArray, OutputArray, Stream&) { throw_no_cuda(); }
 +
 +void cv::gpu::equalizeHist(InputArray, OutputArray, InputOutputArray, Stream&) { throw_no_cuda(); }
 +
 +cv::Ptr<cv::gpu::CLAHE> cv::gpu::createCLAHE(double, cv::Size) { throw_no_cuda(); return cv::Ptr<cv::gpu::CLAHE>(); }
 +
 +void cv::gpu::evenLevels(OutputArray, int, int, int) { throw_no_cuda(); }
 +
 +void cv::gpu::histEven(InputArray, OutputArray, InputOutputArray, int, int, int, Stream&) { throw_no_cuda(); }
 +void cv::gpu::histEven(InputArray, GpuMat*, InputOutputArray, int*, int*, int*, Stream&) { throw_no_cuda(); }
 +
 +void cv::gpu::histRange(InputArray, OutputArray, InputArray, InputOutputArray, Stream&) { throw_no_cuda(); }
 +void cv::gpu::histRange(InputArray, GpuMat*, const GpuMat*, InputOutputArray, Stream&) { throw_no_cuda(); }
 +
 +#else /* !defined (HAVE_CUDA) */
 +
 +////////////////////////////////////////////////////////////////////////
 +// calcHist
 +
 +namespace hist
 +{
 +    void histogram256(PtrStepSzb src, int* hist, cudaStream_t stream);
 +}
 +
 +void cv::gpu::calcHist(InputArray _src, OutputArray _hist, Stream& stream)
 +{
 +    GpuMat src = _src.getGpuMat();
 +
 +    CV_Assert( src.type() == CV_8UC1 );
 +
 +    _hist.create(1, 256, CV_32SC1);
 +    GpuMat hist = _hist.getGpuMat();
 +
 +    hist.setTo(Scalar::all(0), stream);
 +
 +    hist::histogram256(src, hist.ptr<int>(), StreamAccessor::getStream(stream));
 +}
 +
 +////////////////////////////////////////////////////////////////////////
 +// equalizeHist
 +
 +namespace hist
 +{
 +    void equalizeHist(PtrStepSzb src, PtrStepSzb dst, const int* lut, cudaStream_t stream);
 +}
 +
 +void cv::gpu::equalizeHist(InputArray _src, OutputArray _dst, InputOutputArray _buf, Stream& _stream)
 +{
 +    GpuMat src = _src.getGpuMat();
 +
 +    CV_Assert( src.type() == CV_8UC1 );
 +
 +    _dst.create(src.size(), src.type());
 +    GpuMat dst = _dst.getGpuMat();
 +
 +    int intBufSize;
 +    nppSafeCall( nppsIntegralGetBufferSize_32s(256, &intBufSize) );
 +
 +    size_t bufSize = intBufSize + 2 * 256 * sizeof(int);
 +
 +    ensureSizeIsEnough(1, static_cast<int>(bufSize), CV_8UC1, _buf);
 +    GpuMat buf = _buf.getGpuMat();
 +
 +    GpuMat hist(1, 256, CV_32SC1, buf.data);
 +    GpuMat lut(1, 256, CV_32SC1, buf.data + 256 * sizeof(int));
 +    GpuMat intBuf(1, intBufSize, CV_8UC1, buf.data + 2 * 256 * sizeof(int));
 +
 +    gpu::calcHist(src, hist, _stream);
 +
 +    cudaStream_t stream = StreamAccessor::getStream(_stream);
 +    NppStreamHandler h(stream);
 +
 +    nppSafeCall( nppsIntegral_32s(hist.ptr<Npp32s>(), lut.ptr<Npp32s>(), 256, intBuf.ptr<Npp8u>()) );
 +
 +    hist::equalizeHist(src, dst, lut.ptr<int>(), stream);
 +}
 +
 +////////////////////////////////////////////////////////////////////////
 +// CLAHE
 +
 +namespace clahe
 +{
 +    void calcLut(PtrStepSzb src, PtrStepb lut, int tilesX, int tilesY, int2 tileSize, int clipLimit, float lutScale, cudaStream_t stream);
 +    void transform(PtrStepSzb src, PtrStepSzb dst, PtrStepb lut, int tilesX, int tilesY, int2 tileSize, cudaStream_t stream);
 +}
 +
 +namespace
 +{
 +    class CLAHE_Impl : public cv::gpu::CLAHE
 +    {
 +    public:
 +        CLAHE_Impl(double clipLimit = 40.0, int tilesX = 8, int tilesY = 8);
 +
 +        cv::AlgorithmInfo* info() const;
 +
 +        void apply(cv::InputArray src, cv::OutputArray dst);
 +        void apply(InputArray src, OutputArray dst, Stream& stream);
 +
 +        void setClipLimit(double clipLimit);
 +        double getClipLimit() const;
 +
 +        void setTilesGridSize(cv::Size tileGridSize);
 +        cv::Size getTilesGridSize() const;
 +
 +        void collectGarbage();
 +
 +    private:
 +        double clipLimit_;
 +        int tilesX_;
 +        int tilesY_;
 +
 +        GpuMat srcExt_;
 +        GpuMat lut_;
 +    };
 +
 +    CLAHE_Impl::CLAHE_Impl(double clipLimit, int tilesX, int tilesY) :
 +        clipLimit_(clipLimit), tilesX_(tilesX), tilesY_(tilesY)
 +    {
 +    }
 +
 +    CV_INIT_ALGORITHM(CLAHE_Impl, "CLAHE_GPU",
 +        obj.info()->addParam(obj, "clipLimit", obj.clipLimit_);
 +        obj.info()->addParam(obj, "tilesX", obj.tilesX_);
 +        obj.info()->addParam(obj, "tilesY", obj.tilesY_))
 +
 +    void CLAHE_Impl::apply(cv::InputArray _src, cv::OutputArray _dst)
 +    {
 +        apply(_src, _dst, Stream::Null());
 +    }
 +
 +    void CLAHE_Impl::apply(InputArray _src, OutputArray _dst, Stream& s)
 +    {
 +        GpuMat src = _src.getGpuMat();
 +
 +        CV_Assert( src.type() == CV_8UC1 );
 +
 +        _dst.create( src.size(), src.type() );
 +        GpuMat dst = _dst.getGpuMat();
 +
 +        const int histSize = 256;
 +
 +        ensureSizeIsEnough(tilesX_ * tilesY_, histSize, CV_8UC1, lut_);
 +
 +        cudaStream_t stream = StreamAccessor::getStream(s);
 +
 +        cv::Size tileSize;
 +        GpuMat srcForLut;
 +
 +        if (src.cols % tilesX_ == 0 && src.rows % tilesY_ == 0)
 +        {
 +            tileSize = cv::Size(src.cols / tilesX_, src.rows / tilesY_);
 +            srcForLut = src;
 +        }
 +        else
 +        {
 +#ifndef HAVE_OPENCV_GPUARITHM
 +            throw_no_cuda();
 +#else
 +            cv::gpu::copyMakeBorder(src, srcExt_, 0, tilesY_ - (src.rows % tilesY_), 0, tilesX_ - (src.cols % tilesX_), cv::BORDER_REFLECT_101, cv::Scalar(), s);
 +#endif
 +
 +            tileSize = cv::Size(srcExt_.cols / tilesX_, srcExt_.rows / tilesY_);
 +            srcForLut = srcExt_;
 +        }
 +
 +        const int tileSizeTotal = tileSize.area();
 +        const float lutScale = static_cast<float>(histSize - 1) / tileSizeTotal;
 +
 +        int clipLimit = 0;
 +        if (clipLimit_ > 0.0)
 +        {
 +            clipLimit = static_cast<int>(clipLimit_ * tileSizeTotal / histSize);
 +            clipLimit = std::max(clipLimit, 1);
 +        }
 +
 +        clahe::calcLut(srcForLut, lut_, tilesX_, tilesY_, make_int2(tileSize.width, tileSize.height), clipLimit, lutScale, stream);
 +
 +        clahe::transform(src, dst, lut_, tilesX_, tilesY_, make_int2(tileSize.width, tileSize.height), stream);
 +    }
 +
 +    void CLAHE_Impl::setClipLimit(double clipLimit)
 +    {
 +        clipLimit_ = clipLimit;
 +    }
 +
 +    double CLAHE_Impl::getClipLimit() const
 +    {
 +        return clipLimit_;
 +    }
 +
 +    void CLAHE_Impl::setTilesGridSize(cv::Size tileGridSize)
 +    {
 +        tilesX_ = tileGridSize.width;
 +        tilesY_ = tileGridSize.height;
 +    }
 +
 +    cv::Size CLAHE_Impl::getTilesGridSize() const
 +    {
 +        return cv::Size(tilesX_, tilesY_);
 +    }
 +
 +    void CLAHE_Impl::collectGarbage()
 +    {
 +        srcExt_.release();
 +        lut_.release();
 +    }
 +}
 +
 +cv::Ptr<cv::gpu::CLAHE> cv::gpu::createCLAHE(double clipLimit, cv::Size tileGridSize)
 +{
 +    return new CLAHE_Impl(clipLimit, tileGridSize.width, tileGridSize.height);
 +}
 +
 +////////////////////////////////////////////////////////////////////////
 +// NPP Histogram
 +
 +namespace
 +{
 +    typedef NppStatus (*get_buf_size_c1_t)(NppiSize oSizeROI, int nLevels, int* hpBufferSize);
 +    typedef NppStatus (*get_buf_size_c4_t)(NppiSize oSizeROI, int nLevels[], int* hpBufferSize);
 +
 +    template<int SDEPTH> struct NppHistogramEvenFuncC1
 +    {
 +        typedef typename NPPTypeTraits<SDEPTH>::npp_type src_t;
 +
 +    typedef NppStatus (*func_ptr)(const src_t* pSrc, int nSrcStep, NppiSize oSizeROI, Npp32s * pHist,
 +            int nLevels, Npp32s nLowerLevel, Npp32s nUpperLevel, Npp8u * pBuffer);
 +    };
 +    template<int SDEPTH> struct NppHistogramEvenFuncC4
 +    {
 +        typedef typename NPPTypeTraits<SDEPTH>::npp_type src_t;
 +
 +        typedef NppStatus (*func_ptr)(const src_t* pSrc, int nSrcStep, NppiSize oSizeROI,
 +            Npp32s * pHist[4], int nLevels[4], Npp32s nLowerLevel[4], Npp32s nUpperLevel[4], Npp8u * pBuffer);
 +    };
 +
 +    template<int SDEPTH, typename NppHistogramEvenFuncC1<SDEPTH>::func_ptr func, get_buf_size_c1_t get_buf_size>
 +    struct NppHistogramEvenC1
 +    {
 +        typedef typename NppHistogramEvenFuncC1<SDEPTH>::src_t src_t;
 +
 +        static void hist(const GpuMat& src, OutputArray _hist, InputOutputArray _buf, int histSize, int lowerLevel, int upperLevel, cudaStream_t stream)
 +        {
 +            const int levels = histSize + 1;
 +
 +            _hist.create(1, histSize, CV_32S);
 +            GpuMat hist = _hist.getGpuMat();
 +
 +            NppiSize sz;
 +            sz.width = src.cols;
 +            sz.height = src.rows;
 +
 +            int buf_size;
 +            get_buf_size(sz, levels, &buf_size);
 +
 +            ensureSizeIsEnough(1, buf_size, CV_8UC1, _buf);
 +            GpuMat buf = _buf.getGpuMat();
 +
 +            NppStreamHandler h(stream);
 +
 +            nppSafeCall( func(src.ptr<src_t>(), static_cast<int>(src.step), sz, hist.ptr<Npp32s>(), levels,
 +                lowerLevel, upperLevel, buf.ptr<Npp8u>()) );
 +
 +            if (stream == 0)
 +                cudaSafeCall( cudaDeviceSynchronize() );
 +        }
 +    };
 +    template<int SDEPTH, typename NppHistogramEvenFuncC4<SDEPTH>::func_ptr func, get_buf_size_c4_t get_buf_size>
 +    struct NppHistogramEvenC4
 +    {
 +        typedef typename NppHistogramEvenFuncC4<SDEPTH>::src_t src_t;
 +
 +        static void hist(const GpuMat& src, GpuMat hist[4],InputOutputArray _buf, int histSize[4], int lowerLevel[4], int upperLevel[4], cudaStream_t stream)
 +        {
 +            int levels[] = {histSize[0] + 1, histSize[1] + 1, histSize[2] + 1, histSize[3] + 1};
 +            hist[0].create(1, histSize[0], CV_32S);
 +            hist[1].create(1, histSize[1], CV_32S);
 +            hist[2].create(1, histSize[2], CV_32S);
 +            hist[3].create(1, histSize[3], CV_32S);
 +
 +            NppiSize sz;
 +            sz.width = src.cols;
 +            sz.height = src.rows;
 +
 +            Npp32s* pHist[] = {hist[0].ptr<Npp32s>(), hist[1].ptr<Npp32s>(), hist[2].ptr<Npp32s>(), hist[3].ptr<Npp32s>()};
 +
 +            int buf_size;
 +            get_buf_size(sz, levels, &buf_size);
 +
 +            ensureSizeIsEnough(1, buf_size, CV_8U, _buf);
 +            GpuMat buf = _buf.getGpuMat();
 +
 +            NppStreamHandler h(stream);
 +
 +            nppSafeCall( func(src.ptr<src_t>(), static_cast<int>(src.step), sz, pHist, levels, lowerLevel, upperLevel, buf.ptr<Npp8u>()) );
 +
 +            if (stream == 0)
 +                cudaSafeCall( cudaDeviceSynchronize() );
 +        }
 +    };
 +
 +    template<int SDEPTH> struct NppHistogramRangeFuncC1
 +    {
 +        typedef typename NPPTypeTraits<SDEPTH>::npp_type src_t;
 +        typedef Npp32s level_t;
 +        enum {LEVEL_TYPE_CODE=CV_32SC1};
 +
 +        typedef NppStatus (*func_ptr)(const src_t* pSrc, int nSrcStep, NppiSize oSizeROI, Npp32s* pHist,
 +            const Npp32s* pLevels, int nLevels, Npp8u* pBuffer);
 +    };
 +    template<> struct NppHistogramRangeFuncC1<CV_32F>
 +    {
 +        typedef Npp32f src_t;
 +        typedef Npp32f level_t;
 +        enum {LEVEL_TYPE_CODE=CV_32FC1};
 +
 +        typedef NppStatus (*func_ptr)(const Npp32f* pSrc, int nSrcStep, NppiSize oSizeROI, Npp32s* pHist,
 +            const Npp32f* pLevels, int nLevels, Npp8u* pBuffer);
 +    };
 +    template<int SDEPTH> struct NppHistogramRangeFuncC4
 +    {
 +        typedef typename NPPTypeTraits<SDEPTH>::npp_type src_t;
 +        typedef Npp32s level_t;
 +        enum {LEVEL_TYPE_CODE=CV_32SC1};
 +
 +        typedef NppStatus (*func_ptr)(const src_t* pSrc, int nSrcStep, NppiSize oSizeROI, Npp32s* pHist[4],
 +            const Npp32s* pLevels[4], int nLevels[4], Npp8u* pBuffer);
 +    };
 +    template<> struct NppHistogramRangeFuncC4<CV_32F>
 +    {
 +        typedef Npp32f src_t;
 +        typedef Npp32f level_t;
 +        enum {LEVEL_TYPE_CODE=CV_32FC1};
 +
 +        typedef NppStatus (*func_ptr)(const Npp32f* pSrc, int nSrcStep, NppiSize oSizeROI, Npp32s* pHist[4],
 +            const Npp32f* pLevels[4], int nLevels[4], Npp8u* pBuffer);
 +    };
 +
 +    template<int SDEPTH, typename NppHistogramRangeFuncC1<SDEPTH>::func_ptr func, get_buf_size_c1_t get_buf_size>
 +    struct NppHistogramRangeC1
 +    {
 +        typedef typename NppHistogramRangeFuncC1<SDEPTH>::src_t src_t;
 +        typedef typename NppHistogramRangeFuncC1<SDEPTH>::level_t level_t;
 +        enum {LEVEL_TYPE_CODE=NppHistogramRangeFuncC1<SDEPTH>::LEVEL_TYPE_CODE};
 +
 +        static void hist(const GpuMat& src, OutputArray _hist, const GpuMat& levels, InputOutputArray _buf, cudaStream_t stream)
 +        {
 +            CV_Assert( levels.type() == LEVEL_TYPE_CODE && levels.rows == 1 );
 +
 +            _hist.create(1, levels.cols - 1, CV_32S);
 +            GpuMat hist = _hist.getGpuMat();
 +
 +            NppiSize sz;
 +            sz.width = src.cols;
 +            sz.height = src.rows;
 +
 +            int buf_size;
 +            get_buf_size(sz, levels.cols, &buf_size);
 +
 +            ensureSizeIsEnough(1, buf_size, CV_8U, _buf);
 +            GpuMat buf = _buf.getGpuMat();
 +
 +            NppStreamHandler h(stream);
 +
 +            nppSafeCall( func(src.ptr<src_t>(), static_cast<int>(src.step), sz, hist.ptr<Npp32s>(), levels.ptr<level_t>(), levels.cols, buf.ptr<Npp8u>()) );
 +
 +            if (stream == 0)
 +                cudaSafeCall( cudaDeviceSynchronize() );
 +        }
 +    };
 +    template<int SDEPTH, typename NppHistogramRangeFuncC4<SDEPTH>::func_ptr func, get_buf_size_c4_t get_buf_size>
 +    struct NppHistogramRangeC4
 +    {
 +        typedef typename NppHistogramRangeFuncC4<SDEPTH>::src_t src_t;
 +        typedef typename NppHistogramRangeFuncC1<SDEPTH>::level_t level_t;
 +        enum {LEVEL_TYPE_CODE=NppHistogramRangeFuncC1<SDEPTH>::LEVEL_TYPE_CODE};
 +
 +        static void hist(const GpuMat& src, GpuMat hist[4], const GpuMat levels[4],InputOutputArray _buf, cudaStream_t stream)
 +        {
 +            CV_Assert( levels[0].type() == LEVEL_TYPE_CODE && levels[0].rows == 1 );
 +            CV_Assert( levels[1].type() == LEVEL_TYPE_CODE && levels[1].rows == 1 );
 +            CV_Assert( levels[2].type() == LEVEL_TYPE_CODE && levels[2].rows == 1 );
 +            CV_Assert( levels[3].type() == LEVEL_TYPE_CODE && levels[3].rows == 1 );
 +
 +            hist[0].create(1, levels[0].cols - 1, CV_32S);
 +            hist[1].create(1, levels[1].cols - 1, CV_32S);
 +            hist[2].create(1, levels[2].cols - 1, CV_32S);
 +            hist[3].create(1, levels[3].cols - 1, CV_32S);
 +
 +            Npp32s* pHist[] = {hist[0].ptr<Npp32s>(), hist[1].ptr<Npp32s>(), hist[2].ptr<Npp32s>(), hist[3].ptr<Npp32s>()};
 +            int nLevels[] = {levels[0].cols, levels[1].cols, levels[2].cols, levels[3].cols};
 +            const level_t* pLevels[] = {levels[0].ptr<level_t>(), levels[1].ptr<level_t>(), levels[2].ptr<level_t>(), levels[3].ptr<level_t>()};
 +
 +            NppiSize sz;
 +            sz.width = src.cols;
 +            sz.height = src.rows;
 +
 +            int buf_size;
 +            get_buf_size(sz, nLevels, &buf_size);
 +
 +            ensureSizeIsEnough(1, buf_size, CV_8U, _buf);
 +            GpuMat buf = _buf.getGpuMat();
 +
 +            NppStreamHandler h(stream);
 +
 +            nppSafeCall( func(src.ptr<src_t>(), static_cast<int>(src.step), sz, pHist, pLevels, nLevels, buf.ptr<Npp8u>()) );
 +
 +            if (stream == 0)
 +                cudaSafeCall( cudaDeviceSynchronize() );
 +        }
 +    };
 +}
 +
 +void cv::gpu::evenLevels(OutputArray _levels, int nLevels, int lowerLevel, int upperLevel)
 +{
 +    const int kind = _levels.kind();
 +
 +    _levels.create(1, nLevels, CV_32SC1);
 +
 +    Mat host_levels;
 +    if (kind == _InputArray::GPU_MAT)
 +        host_levels.create(1, nLevels, CV_32SC1);
 +    else
 +        host_levels = _levels.getMat();
 +
 +    nppSafeCall( nppiEvenLevelsHost_32s(host_levels.ptr<Npp32s>(), nLevels, lowerLevel, upperLevel) );
 +
 +    if (kind == _InputArray::GPU_MAT)
 +        _levels.getGpuMatRef().upload(host_levels);
 +}
 +
++namespace hist
++{
++    void histEven8u(PtrStepSzb src, int* hist, int binCount, int lowerLevel, int upperLevel, cudaStream_t stream);
++}
++
++namespace
++{
++    void histEven8u(const GpuMat& src, GpuMat& hist, int histSize, int lowerLevel, int upperLevel, cudaStream_t stream)
++    {
++        hist.create(1, histSize, CV_32S);
++        cudaSafeCall( cudaMemsetAsync(hist.data, 0, histSize * sizeof(int), stream) );
++        hist::histEven8u(src, hist.ptr<int>(), histSize, lowerLevel, upperLevel, stream);
++    }
++}
++
 +void cv::gpu::histEven(InputArray _src, OutputArray hist, InputOutputArray buf, int histSize, int lowerLevel, int upperLevel, Stream& stream)
 +{
 +    typedef void (*hist_t)(const GpuMat& src, OutputArray hist, InputOutputArray buf, int levels, int lowerLevel, int upperLevel, cudaStream_t stream);
 +    static const hist_t hist_callers[] =
 +    {
 +        NppHistogramEvenC1<CV_8U , nppiHistogramEven_8u_C1R , nppiHistogramEvenGetBufferSize_8u_C1R >::hist,
 +        0,
 +        NppHistogramEvenC1<CV_16U, nppiHistogramEven_16u_C1R, nppiHistogramEvenGetBufferSize_16u_C1R>::hist,
 +        NppHistogramEvenC1<CV_16S, nppiHistogramEven_16s_C1R, nppiHistogramEvenGetBufferSize_16s_C1R>::hist
 +    };
 +
 +    GpuMat src = _src.getGpuMat();
 +
++    if (src.depth() == CV_8U && deviceSupports(FEATURE_SET_COMPUTE_30))
++    {
++        histEven8u(src, hist.getGpuMatRef(), histSize, lowerLevel, upperLevel, StreamAccessor::getStream(stream));
++        return;
++    }
++
 +    CV_Assert( src.type() == CV_8UC1 || src.type() == CV_16UC1 || src.type() == CV_16SC1 );
 +
 +    hist_callers[src.depth()](src, hist, buf, histSize, lowerLevel, upperLevel, StreamAccessor::getStream(stream));
 +}
 +
 +void cv::gpu::histEven(InputArray _src, GpuMat hist[4], InputOutputArray buf, int histSize[4], int lowerLevel[4], int upperLevel[4], Stream& stream)
 +{
 +    typedef void (*hist_t)(const GpuMat& src, GpuMat hist[4], InputOutputArray buf, int levels[4], int lowerLevel[4], int upperLevel[4], cudaStream_t stream);
 +    static const hist_t hist_callers[] =
 +    {
 +        NppHistogramEvenC4<CV_8U , nppiHistogramEven_8u_C4R , nppiHistogramEvenGetBufferSize_8u_C4R >::hist,
 +        0,
 +        NppHistogramEvenC4<CV_16U, nppiHistogramEven_16u_C4R, nppiHistogramEvenGetBufferSize_16u_C4R>::hist,
 +        NppHistogramEvenC4<CV_16S, nppiHistogramEven_16s_C4R, nppiHistogramEvenGetBufferSize_16s_C4R>::hist
 +    };
 +
 +    GpuMat src = _src.getGpuMat();
 +
 +    CV_Assert( src.type() == CV_8UC4 || src.type() == CV_16UC4 || src.type() == CV_16SC4 );
 +
 +    hist_callers[src.depth()](src, hist, buf, histSize, lowerLevel, upperLevel, StreamAccessor::getStream(stream));
 +}
 +
 +void cv::gpu::histRange(InputArray _src, OutputArray hist, InputArray _levels, InputOutputArray buf, Stream& stream)
 +{
 +    typedef void (*hist_t)(const GpuMat& src, OutputArray hist, const GpuMat& levels, InputOutputArray buf, cudaStream_t stream);
 +    static const hist_t hist_callers[] =
 +    {
 +        NppHistogramRangeC1<CV_8U , nppiHistogramRange_8u_C1R , nppiHistogramRangeGetBufferSize_8u_C1R >::hist,
 +        0,
 +        NppHistogramRangeC1<CV_16U, nppiHistogramRange_16u_C1R, nppiHistogramRangeGetBufferSize_16u_C1R>::hist,
 +        NppHistogramRangeC1<CV_16S, nppiHistogramRange_16s_C1R, nppiHistogramRangeGetBufferSize_16s_C1R>::hist,
 +        0,
 +        NppHistogramRangeC1<CV_32F, nppiHistogramRange_32f_C1R, nppiHistogramRangeGetBufferSize_32f_C1R>::hist
 +    };
 +
 +    GpuMat src = _src.getGpuMat();
 +    GpuMat levels = _levels.getGpuMat();
 +
 +    CV_Assert( src.type() == CV_8UC1 || src.type() == CV_16UC1 || src.type() == CV_16SC1 || src.type() == CV_32FC1 );
 +
 +    hist_callers[src.depth()](src, hist, levels, buf, StreamAccessor::getStream(stream));
 +}
 +
 +void cv::gpu::histRange(InputArray _src, GpuMat hist[4], const GpuMat levels[4], InputOutputArray buf, Stream& stream)
 +{
 +    typedef void (*hist_t)(const GpuMat& src, GpuMat hist[4], const GpuMat levels[4], InputOutputArray buf, cudaStream_t stream);
 +    static const hist_t hist_callers[] =
 +    {
 +        NppHistogramRangeC4<CV_8U , nppiHistogramRange_8u_C4R , nppiHistogramRangeGetBufferSize_8u_C4R >::hist,
 +        0,
 +        NppHistogramRangeC4<CV_16U, nppiHistogramRange_16u_C4R, nppiHistogramRangeGetBufferSize_16u_C4R>::hist,
 +        NppHistogramRangeC4<CV_16S, nppiHistogramRange_16s_C4R, nppiHistogramRangeGetBufferSize_16s_C4R>::hist,
 +        0,
 +        NppHistogramRangeC4<CV_32F, nppiHistogramRange_32f_C4R, nppiHistogramRangeGetBufferSize_32f_C4R>::hist
 +    };
 +
 +    GpuMat src = _src.getGpuMat();
 +
 +    CV_Assert( src.type() == CV_8UC4 || src.type() == CV_16UC4 || src.type() == CV_16SC4 || src.type() == CV_32FC4 );
 +
 +    hist_callers[src.depth()](src, hist, levels, buf, StreamAccessor::getStream(stream));
 +}
 +
 +#endif /* !defined (HAVE_CUDA) */
index 8a5b22a,0000000..5562117
mode 100644,000000..100644
--- /dev/null
@@@ -1,227 -1,0 +1,216 @@@
- struct HistEven : testing::TestWithParam<cv::gpu::DeviceInfo>
 +/*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 "test_precomp.hpp"
 +
 +#ifdef HAVE_CUDA
 +
 +using namespace cvtest;
 +
 +///////////////////////////////////////////////////////////////////////////////////////////////////////
 +// HistEven
 +
-         devInfo = GetParam();
++PARAM_TEST_CASE(HistEven, cv::gpu::DeviceInfo, cv::Size)
 +{
 +    cv::gpu::DeviceInfo devInfo;
 +
++    cv::Size size;
++
 +    virtual void SetUp()
 +    {
-     cv::Mat img = readImage("stereobm/aloe-L.png");
-     ASSERT_FALSE(img.empty());
-     cv::Mat hsv;
-     cv::cvtColor(img, hsv, cv::COLOR_BGR2HSV);
++        devInfo = GET_PARAM(0);
++        size = GET_PARAM(1);
 +
 +        cv::gpu::setDevice(devInfo.deviceID());
 +    }
 +};
 +
 +GPU_TEST_P(HistEven, Accuracy)
 +{
-     float hranges[] = {0.0f, 180.0f};
-     std::vector<cv::Mat> srcs;
-     cv::split(hsv, srcs);
++    cv::Mat src = randomMat(size, CV_8UC1);
 +
 +    int hbins = 30;
-     cv::gpu::histEven(loadMat(srcs[0]), hist, hbins, (int)hranges[0], (int)hranges[1]);
++    float hranges[] = {50.0f, 200.0f};
 +
 +    cv::gpu::GpuMat hist;
-     cv::MatND histnd;
++    cv::gpu::histEven(loadMat(src), hist, hbins, (int) hranges[0], (int) hranges[1]);
++
++    cv::Mat hist_gold;
 +
-     cv::calcHist(&hsv, 1, channels, cv::Mat(), histnd, 1, histSize, ranges);
 +    int histSize[] = {hbins};
 +    const float* ranges[] = {hranges};
 +    int channels[] = {0};
-     cv::Mat hist_gold = histnd;
++    cv::calcHist(&src, 1, channels, cv::Mat(), hist_gold, 1, histSize, ranges);
 +
- INSTANTIATE_TEST_CASE_P(GPU_ImgProc, HistEven, ALL_DEVICES);
 +    hist_gold = hist_gold.t();
 +    hist_gold.convertTo(hist_gold, CV_32S);
 +
 +    EXPECT_MAT_NEAR(hist_gold, hist, 0.0);
 +}
 +
- namespace
- {
-     void calcHistGold(const cv::Mat& src, cv::Mat& hist)
-     {
-         hist.create(1, 256, CV_32SC1);
-         hist.setTo(cv::Scalar::all(0));
-         int* hist_row = hist.ptr<int>();
-         for (int y = 0; y < src.rows; ++y)
-         {
-             const uchar* src_row = src.ptr(y);
-             for (int x = 0; x < src.cols; ++x)
-                 ++hist_row[src_row[x]];
-         }
-     }
- }
++INSTANTIATE_TEST_CASE_P(GPU_ImgProc, HistEven, testing::Combine(
++    ALL_DEVICES,
++    DIFFERENT_SIZES));
 +
 +///////////////////////////////////////////////////////////////////////////////////////////////////////
 +// CalcHist
 +
-     calcHistGold(src, hist_gold);
 +PARAM_TEST_CASE(CalcHist, cv::gpu::DeviceInfo, cv::Size)
 +{
 +    cv::gpu::DeviceInfo devInfo;
 +
 +    cv::Size size;
 +
 +    virtual void SetUp()
 +    {
 +        devInfo = GET_PARAM(0);
 +        size = GET_PARAM(1);
 +
 +        cv::gpu::setDevice(devInfo.deviceID());
 +    }
 +};
 +
 +GPU_TEST_P(CalcHist, Accuracy)
 +{
 +    cv::Mat src = randomMat(size, CV_8UC1);
 +
 +    cv::gpu::GpuMat hist;
 +    cv::gpu::calcHist(loadMat(src), hist);
 +
 +    cv::Mat hist_gold;
++
++    const int hbins = 256;
++    const float hranges[] = {0.0f, 256.0f};
++    const int histSize[] = {hbins};
++    const float* ranges[] = {hranges};
++    const int channels[] = {0};
++
++    cv::calcHist(&src, 1, channels, cv::Mat(), hist_gold, 1, histSize, ranges);
++    hist_gold = hist_gold.reshape(1, 1);
++    hist_gold.convertTo(hist_gold, CV_32S);
 +
 +    EXPECT_MAT_NEAR(hist_gold, hist, 0.0);
 +}
 +
 +INSTANTIATE_TEST_CASE_P(GPU_ImgProc, CalcHist, testing::Combine(
 +    ALL_DEVICES,
 +    DIFFERENT_SIZES));
 +
 +///////////////////////////////////////////////////////////////////////////////////////////////////////
 +// EqualizeHist
 +
 +PARAM_TEST_CASE(EqualizeHist, cv::gpu::DeviceInfo, cv::Size)
 +{
 +    cv::gpu::DeviceInfo devInfo;
 +    cv::Size size;
 +
 +    virtual void SetUp()
 +    {
 +        devInfo = GET_PARAM(0);
 +        size = GET_PARAM(1);
 +
 +        cv::gpu::setDevice(devInfo.deviceID());
 +    }
 +};
 +
 +GPU_TEST_P(EqualizeHist, Accuracy)
 +{
 +    cv::Mat src = randomMat(size, CV_8UC1);
 +
 +    cv::gpu::GpuMat dst;
 +    cv::gpu::equalizeHist(loadMat(src), dst);
 +
 +    cv::Mat dst_gold;
 +    cv::equalizeHist(src, dst_gold);
 +
 +    EXPECT_MAT_NEAR(dst_gold, dst, 3.0);
 +}
 +
 +INSTANTIATE_TEST_CASE_P(GPU_ImgProc, EqualizeHist, testing::Combine(
 +    ALL_DEVICES,
 +    DIFFERENT_SIZES));
 +
 +///////////////////////////////////////////////////////////////////////////////////////////////////////
 +// CLAHE
 +
 +namespace
 +{
 +    IMPLEMENT_PARAM_CLASS(ClipLimit, double)
 +}
 +
 +PARAM_TEST_CASE(CLAHE, cv::gpu::DeviceInfo, cv::Size, ClipLimit)
 +{
 +    cv::gpu::DeviceInfo devInfo;
 +    cv::Size size;
 +    double clipLimit;
 +
 +    virtual void SetUp()
 +    {
 +        devInfo = GET_PARAM(0);
 +        size = GET_PARAM(1);
 +        clipLimit = GET_PARAM(2);
 +
 +        cv::gpu::setDevice(devInfo.deviceID());
 +    }
 +};
 +
 +GPU_TEST_P(CLAHE, Accuracy)
 +{
 +    cv::Mat src = randomMat(size, CV_8UC1);
 +
 +    cv::Ptr<cv::gpu::CLAHE> clahe = cv::gpu::createCLAHE(clipLimit);
 +    cv::gpu::GpuMat dst;
 +    clahe->apply(loadMat(src), dst);
 +
 +    cv::Ptr<cv::CLAHE> clahe_gold = cv::createCLAHE(clipLimit);
 +    cv::Mat dst_gold;
 +    clahe_gold->apply(src, dst_gold);
 +
 +    ASSERT_MAT_NEAR(dst_gold, dst, 1.0);
 +}
 +
 +INSTANTIATE_TEST_CASE_P(GPU_ImgProc, CLAHE, testing::Combine(
 +    ALL_DEVICES,
 +    DIFFERENT_SIZES,
 +    testing::Values(0.0, 40.0)));
 +
 +#endif // HAVE_CUDA
index 5962b2b,0000000..923fe9e
mode 100644,000000..100644
--- /dev/null
@@@ -1,219 -1,0 +1,229 @@@
 +Optical Flow
 +============
 +
 +.. highlight:: cpp
 +
++.. Sample code::
++
++   * : A general optical flow example can be found at opencv_source_code/samples/gpu/optical_flow.cpp
++   * : A feneral optical flow example using the nvidia API can be found at opencv_source_code/samples/gpu/opticalflow_nvidia_api.cpp
 +
 +
 +gpu::BroxOpticalFlow
 +--------------------
 +.. ocv:class:: gpu::BroxOpticalFlow
 +
 +Class computing the optical flow for two images using Brox et al Optical Flow algorithm ([Brox2004]_). ::
 +
 +    class BroxOpticalFlow
 +    {
 +    public:
 +        BroxOpticalFlow(float alpha_, float gamma_, float scale_factor_, int inner_iterations_, int outer_iterations_, int solver_iterations_);
 +
 +        //! Compute optical flow
 +        //! frame0 - source frame (supports only CV_32FC1 type)
 +        //! frame1 - frame to track (with the same size and type as frame0)
 +        //! u      - flow horizontal component (along x axis)
 +        //! v      - flow vertical component (along y axis)
 +        void operator ()(const GpuMat& frame0, const GpuMat& frame1, GpuMat& u, GpuMat& v, Stream& stream = Stream::Null());
 +
 +        //! flow smoothness
 +        float alpha;
 +
 +        //! gradient constancy importance
 +        float gamma;
 +
 +        //! pyramid scale factor
 +        float scale_factor;
 +
 +        //! number of lagged non-linearity iterations (inner loop)
 +        int inner_iterations;
 +
 +        //! number of warping iterations (number of pyramid levels)
 +        int outer_iterations;
 +
 +        //! number of linear system solver iterations
 +        int solver_iterations;
 +
 +        GpuMat buf;
 +    };
 +
++.. Sample code::
++
++   * : An example illustrating the Brox et al optical flow algorithm can be found at opencv_source_code/samples/gpu/brox_optical_flow.cpp
 +
 +
 +gpu::FarnebackOpticalFlow
 +-------------------------
 +.. ocv:class:: gpu::FarnebackOpticalFlow
 +
 +Class computing a dense optical flow using the Gunnar Farneback’s algorithm. ::
 +
 +    class CV_EXPORTS FarnebackOpticalFlow
 +    {
 +    public:
 +        FarnebackOpticalFlow()
 +        {
 +            numLevels = 5;
 +            pyrScale = 0.5;
 +            fastPyramids = false;
 +            winSize = 13;
 +            numIters = 10;
 +            polyN = 5;
 +            polySigma = 1.1;
 +            flags = 0;
 +        }
 +
 +        int numLevels;
 +        double pyrScale;
 +        bool fastPyramids;
 +        int winSize;
 +        int numIters;
 +        int polyN;
 +        double polySigma;
 +        int flags;
 +
 +        void operator ()(const GpuMat &frame0, const GpuMat &frame1, GpuMat &flowx, GpuMat &flowy, Stream &s = Stream::Null());
 +
 +        void releaseMemory();
 +
 +    private:
 +        /* hidden */
 +    };
 +
 +
 +
 +gpu::FarnebackOpticalFlow::operator ()
 +--------------------------------------
 +Computes a dense optical flow using the Gunnar Farneback’s algorithm.
 +
 +.. ocv:function:: void gpu::FarnebackOpticalFlow::operator ()(const GpuMat &frame0, const GpuMat &frame1, GpuMat &flowx, GpuMat &flowy, Stream &s = Stream::Null())
 +
 +    :param frame0: First 8-bit gray-scale input image
 +    :param frame1: Second 8-bit gray-scale input image
 +    :param flowx: Flow horizontal component
 +    :param flowy: Flow vertical component
 +    :param s: Stream
 +
 +.. seealso:: :ocv:func:`calcOpticalFlowFarneback`
 +
 +
 +
 +gpu::FarnebackOpticalFlow::releaseMemory
 +----------------------------------------
 +Releases unused auxiliary memory buffers.
 +
 +.. ocv:function:: void gpu::FarnebackOpticalFlow::releaseMemory()
 +
 +
 +
 +gpu::PyrLKOpticalFlow
 +---------------------
 +.. ocv:class:: gpu::PyrLKOpticalFlow
 +
 +Class used for calculating an optical flow. ::
 +
 +    class PyrLKOpticalFlow
 +    {
 +    public:
 +        PyrLKOpticalFlow();
 +
 +        void sparse(const GpuMat& prevImg, const GpuMat& nextImg, const GpuMat& prevPts, GpuMat& nextPts,
 +            GpuMat& status, GpuMat* err = 0);
 +
 +        void dense(const GpuMat& prevImg, const GpuMat& nextImg, GpuMat& u, GpuMat& v, GpuMat* err = 0);
 +
 +        Size winSize;
 +        int maxLevel;
 +        int iters;
 +        bool useInitialFlow;
 +
 +        void releaseMemory();
 +    };
 +
 +The class can calculate an optical flow for a sparse feature set or dense optical flow using the iterative Lucas-Kanade method with pyramids.
 +
 +.. seealso:: :ocv:func:`calcOpticalFlowPyrLK`
 +
++.. Sample code::
++
++   * : An example of the Lucas Kanade optical flow algorithm can be found at opencv_source_code/samples/gpu/pyrlk_optical_flow.cpp
 +
 +
 +gpu::PyrLKOpticalFlow::sparse
 +-----------------------------
 +Calculate an optical flow for a sparse feature set.
 +
 +.. ocv:function:: void gpu::PyrLKOpticalFlow::sparse(const GpuMat& prevImg, const GpuMat& nextImg, const GpuMat& prevPts, GpuMat& nextPts, GpuMat& status, GpuMat* err = 0)
 +
 +    :param prevImg: First 8-bit input image (supports both grayscale and color images).
 +
 +    :param nextImg: Second input image of the same size and the same type as  ``prevImg`` .
 +
 +    :param prevPts: Vector of 2D points for which the flow needs to be found. It must be one row matrix with CV_32FC2 type.
 +
 +    :param nextPts: Output vector of 2D points (with single-precision floating-point coordinates) containing the calculated new positions of input features in the second image. When ``useInitialFlow`` is true, the vector must have the same size as in the input.
 +
 +    :param status: Output status vector (CV_8UC1 type). Each element of the vector is set to 1 if the flow for the corresponding features has been found. Otherwise, it is set to 0.
 +
 +    :param err: Output vector (CV_32FC1 type) that contains the difference between patches around the original and moved points or min eigen value if ``getMinEigenVals`` is checked. It can be NULL, if not needed.
 +
 +.. seealso:: :ocv:func:`calcOpticalFlowPyrLK`
 +
 +
 +
 +gpu::PyrLKOpticalFlow::dense
 +-----------------------------
 +Calculate dense optical flow.
 +
 +.. ocv:function:: void gpu::PyrLKOpticalFlow::dense(const GpuMat& prevImg, const GpuMat& nextImg, GpuMat& u, GpuMat& v, GpuMat* err = 0)
 +
 +    :param prevImg: First 8-bit grayscale input image.
 +
 +    :param nextImg: Second input image of the same size and the same type as  ``prevImg`` .
 +
 +    :param u: Horizontal component of the optical flow of the same size as input images, 32-bit floating-point, single-channel
 +
 +    :param v: Vertical component of the optical flow of the same size as input images, 32-bit floating-point, single-channel
 +
 +    :param err: Output vector (CV_32FC1 type) that contains the difference between patches around the original and moved points or min eigen value if ``getMinEigenVals`` is checked. It can be NULL, if not needed.
 +
 +
 +
 +gpu::PyrLKOpticalFlow::releaseMemory
 +------------------------------------
 +Releases inner buffers memory.
 +
 +.. ocv:function:: void gpu::PyrLKOpticalFlow::releaseMemory()
 +
 +
 +
 +gpu::interpolateFrames
 +----------------------
 +Interpolates frames (images) using provided optical flow (displacement field).
 +
 +.. ocv:function:: void gpu::interpolateFrames(const GpuMat& frame0, const GpuMat& frame1, const GpuMat& fu, const GpuMat& fv, const GpuMat& bu, const GpuMat& bv, float pos, GpuMat& newFrame, GpuMat& buf, Stream& stream = Stream::Null())
 +
 +    :param frame0: First frame (32-bit floating point images, single channel).
 +
 +    :param frame1: Second frame. Must have the same type and size as ``frame0`` .
 +
 +    :param fu: Forward horizontal displacement.
 +
 +    :param fv: Forward vertical displacement.
 +
 +    :param bu: Backward horizontal displacement.
 +
 +    :param bv: Backward vertical displacement.
 +
 +    :param pos: New frame position.
 +
 +    :param newFrame: Output image.
 +
 +    :param buf: Temporary buffer, will have width x 6*height size, CV_32FC1 type and contain 6 GpuMat: occlusion masks for first frame, occlusion masks for second, interpolated forward horizontal flow, interpolated forward vertical flow, interpolated backward horizontal flow, interpolated backward vertical flow.
 +
 +    :param stream: Stream for the asynchronous version.
 +
 +
 +
 +.. [Brox2004] T. Brox, A. Bruhn, N. Papenberg, J. Weickert. *High accuracy optical flow estimation based on a theory for warping*. ECCV 2004.
index 4064fe0,0000000..612777d
mode 100644,000000..100644
--- /dev/null
@@@ -1,332 -1,0 +1,336 @@@
 +Stereo Correspondence
 +=====================
 +
 +.. highlight:: cpp
 +
++.. Sample code::
 +
++   * : A basic stereo matching example can be found at opencv_source_code/samples/gpu/stereo_match.cpp
++   * : A stereo matching example using several GPU's can be found at opencv_source_code/samples/gpu/stereo_multi.cpp
++   * : A stereo matching example using several GPU's and driver API can be found at opencv_source_code/samples/gpu/driver_api_stereo_multi.cpp
 +
 +gpu::StereoBM
 +-------------
 +.. ocv:class:: gpu::StereoBM : public cv::StereoBM
 +
 +Class computing stereo correspondence (disparity map) using the block matching algorithm. ::
 +
 +.. seealso:: :ocv:class:`StereoBM`
 +
 +
 +
 +gpu::createStereoBM
 +-------------------
 +Creates StereoBM object.
 +
 +.. ocv:function:: Ptr<gpu::StereoBM> gpu::createStereoBM(int numDisparities = 64, int blockSize = 19)
 +
 +    :param numDisparities: the disparity search range. For each pixel algorithm will find the best disparity from 0 (default minimum disparity) to ``numDisparities``. The search range can then be shifted by changing the minimum disparity.
 +
 +    :param blockSize: the linear size of the blocks compared by the algorithm. The size should be odd (as the block is centered at the current pixel). Larger block size implies smoother, though less accurate disparity map. Smaller block size gives more detailed disparity map, but there is higher chance for algorithm to find a wrong correspondence.
 +
 +
 +
 +gpu::StereoBeliefPropagation
 +----------------------------
 +.. ocv:class:: gpu::StereoBeliefPropagation : public cv::StereoMatcher
 +
 +Class computing stereo correspondence using the belief propagation algorithm. ::
 +
 +    class CV_EXPORTS StereoBeliefPropagation : public cv::StereoMatcher
 +    {
 +    public:
 +        using cv::StereoMatcher::compute;
 +
 +        virtual void compute(InputArray left, InputArray right, OutputArray disparity, Stream& stream) = 0;
 +
 +        //! version for user specified data term
 +        virtual void compute(InputArray data, OutputArray disparity, Stream& stream = Stream::Null()) = 0;
 +
 +        //! number of BP iterations on each level
 +        virtual int getNumIters() const = 0;
 +        virtual void setNumIters(int iters) = 0;
 +
 +        //! number of levels
 +        virtual int getNumLevels() const = 0;
 +        virtual void setNumLevels(int levels) = 0;
 +
 +        //! truncation of data cost
 +        virtual double getMaxDataTerm() const = 0;
 +        virtual void setMaxDataTerm(double max_data_term) = 0;
 +
 +        //! data weight
 +        virtual double getDataWeight() const = 0;
 +        virtual void setDataWeight(double data_weight) = 0;
 +
 +        //! truncation of discontinuity cost
 +        virtual double getMaxDiscTerm() const = 0;
 +        virtual void setMaxDiscTerm(double max_disc_term) = 0;
 +
 +        //! discontinuity single jump
 +        virtual double getDiscSingleJump() const = 0;
 +        virtual void setDiscSingleJump(double disc_single_jump) = 0;
 +
 +        virtual int getMsgType() const = 0;
 +        virtual void setMsgType(int msg_type) = 0;
 +
 +        static void estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels);
 +    };
 +
 +
 +The class implements algorithm described in [Felzenszwalb2006]_ . It can compute own data cost (using a truncated linear model) or use a user-provided data cost.
 +
 +.. note::
 +
 +    ``StereoBeliefPropagation`` requires a lot of memory for message storage:
 +
 +    .. math::
 +
 +        width \_ step  \cdot height  \cdot ndisp  \cdot 4  \cdot (1 + 0.25)
 +
 +    and for data cost storage:
 +
 +    .. math::
 +
 +        width\_step \cdot height \cdot ndisp \cdot (1 + 0.25 + 0.0625 +  \dotsm + \frac{1}{4^{levels}})
 +
 +    ``width_step`` is the number of bytes in a line including padding.
 +
 +``StereoBeliefPropagation`` uses a truncated linear model for the data cost and discontinuity terms:
 +
 +.. math::
 +
 +    DataCost = data \_ weight  \cdot \min ( \lvert Img_Left(x,y)-Img_Right(x-d,y)  \rvert , max \_ data \_ term)
 +
 +.. math::
 +
 +    DiscTerm =  \min (disc \_ single \_ jump  \cdot \lvert f_1-f_2  \rvert , max \_ disc \_ term)
 +
 +For more details, see [Felzenszwalb2006]_.
 +
 +By default, ``StereoBeliefPropagation`` uses floating-point arithmetics and the ``CV_32FC1`` type for messages. But it can also use fixed-point arithmetics and the ``CV_16SC1`` message type for better performance. To avoid an overflow in this case, the parameters must satisfy the following requirement:
 +
 +.. math::
 +
 +    10  \cdot 2^{levels-1}  \cdot max \_ data \_ term < SHRT \_ MAX
 +
 +.. seealso:: :ocv:class:`StereoMatcher`
 +
 +
 +
 +gpu::createStereoBeliefPropagation
 +----------------------------------
 +Creates StereoBeliefPropagation object.
 +
 +.. ocv:function:: Ptr<gpu::StereoBeliefPropagation> gpu::createStereoBeliefPropagation(int ndisp = 64, int iters = 5, int levels = 5, int msg_type = CV_32F)
 +
 +    :param ndisp: Number of disparities.
 +
 +    :param iters: Number of BP iterations on each level.
 +
 +    :param levels: Number of levels.
 +
 +    :param msg_type: Type for messages.  ``CV_16SC1``  and  ``CV_32FC1`` types are supported.
 +
 +
 +
 +gpu::StereoBeliefPropagation::estimateRecommendedParams
 +-------------------------------------------------------
 +Uses a heuristic method to compute the recommended parameters ( ``ndisp``, ``iters`` and ``levels`` ) for the specified image size ( ``width`` and ``height`` ).
 +
 +.. ocv:function:: void gpu::StereoBeliefPropagation::estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels)
 +
 +
 +
 +gpu::StereoBeliefPropagation::compute
 +-------------------------------------
 +Enables the stereo correspondence operator that finds the disparity for the specified data cost.
 +
 +.. ocv:function:: void gpu::StereoBeliefPropagation::compute(InputArray data, OutputArray disparity, Stream& stream = Stream::Null())
 +
 +    :param data: User-specified data cost, a matrix of ``msg_type`` type and ``Size(<image columns>*ndisp, <image rows>)`` size.
 +
 +    :param disparity: Output disparity map. If  ``disparity``  is empty, the output type is  ``CV_16SC1`` . Otherwise, the type is retained.
 +
 +    :param stream: Stream for the asynchronous version.
 +
 +
 +
 +gpu::StereoConstantSpaceBP
 +--------------------------
 +.. ocv:class:: gpu::StereoConstantSpaceBP : public gpu::StereoBeliefPropagation
 +
 +Class computing stereo correspondence using the constant space belief propagation algorithm. ::
 +
 +    class CV_EXPORTS StereoConstantSpaceBP : public gpu::StereoBeliefPropagation
 +    {
 +    public:
 +        //! number of active disparity on the first level
 +        virtual int getNrPlane() const = 0;
 +        virtual void setNrPlane(int nr_plane) = 0;
 +
 +        virtual bool getUseLocalInitDataCost() const = 0;
 +        virtual void setUseLocalInitDataCost(bool use_local_init_data_cost) = 0;
 +
 +        static void estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels, int& nr_plane);
 +    };
 +
 +
 +The class implements algorithm described in [Yang2010]_. ``StereoConstantSpaceBP`` supports both local minimum and global minimum data cost initialization algorithms. For more details, see the paper mentioned above. By default, a local algorithm is used. To enable a global algorithm, set ``use_local_init_data_cost`` to ``false`` .
 +
 +``StereoConstantSpaceBP`` uses a truncated linear model for the data cost and discontinuity terms:
 +
 +.. math::
 +
 +    DataCost = data \_ weight  \cdot \min ( \lvert I_2-I_1  \rvert , max \_ data \_ term)
 +
 +.. math::
 +
 +    DiscTerm =  \min (disc \_ single \_ jump  \cdot \lvert f_1-f_2  \rvert , max \_ disc \_ term)
 +
 +For more details, see [Yang2010]_.
 +
 +By default, ``StereoConstantSpaceBP`` uses floating-point arithmetics and the ``CV_32FC1`` type for messages. But it can also use fixed-point arithmetics and the ``CV_16SC1`` message type for better performance. To avoid an overflow in this case, the parameters must satisfy the following requirement:
 +
 +.. math::
 +
 +    10  \cdot 2^{levels-1}  \cdot max \_ data \_ term < SHRT \_ MAX
 +
 +
 +
 +gpu::createStereoConstantSpaceBP
 +--------------------------------
 +Creates StereoConstantSpaceBP object.
 +
 +.. ocv:function:: Ptr<gpu::StereoConstantSpaceBP> gpu::createStereoConstantSpaceBP(int ndisp = 128, int iters = 8, int levels = 4, int nr_plane = 4, int msg_type = CV_32F)
 +
 +    :param ndisp: Number of disparities.
 +
 +    :param iters: Number of BP iterations on each level.
 +
 +    :param levels: Number of levels.
 +
 +    :param nr_plane: Number of disparity levels on the first level.
 +
 +    :param msg_type: Type for messages.  ``CV_16SC1``  and  ``CV_32FC1`` types are supported.
 +
 +
 +
 +gpu::StereoConstantSpaceBP::estimateRecommendedParams
 +-----------------------------------------------------
 +Uses a heuristic method to compute parameters (ndisp, iters, levelsand nrplane) for the specified image size (widthand height).
 +
 +.. ocv:function:: void gpu::StereoConstantSpaceBP::estimateRecommendedParams(int width, int height, int& ndisp, int& iters, int& levels, int& nr_plane)
 +
 +
 +
 +gpu::DisparityBilateralFilter
 +-----------------------------
 +.. ocv:class:: gpu::DisparityBilateralFilter : public cv::Algorithm
 +
 +Class refining a disparity map using joint bilateral filtering. ::
 +
 +    class CV_EXPORTS DisparityBilateralFilter : public cv::Algorithm
 +    {
 +    public:
 +        //! the disparity map refinement operator. Refine disparity map using joint bilateral filtering given a single color image.
 +        //! disparity must have CV_8U or CV_16S type, image must have CV_8UC1 or CV_8UC3 type.
 +        virtual void apply(InputArray disparity, InputArray image, OutputArray dst, Stream& stream = Stream::Null()) = 0;
 +
 +        virtual int getNumDisparities() const = 0;
 +        virtual void setNumDisparities(int numDisparities) = 0;
 +
 +        virtual int getRadius() const = 0;
 +        virtual void setRadius(int radius) = 0;
 +
 +        virtual int getNumIters() const = 0;
 +        virtual void setNumIters(int iters) = 0;
 +
 +        //! truncation of data continuity
 +        virtual double getEdgeThreshold() const = 0;
 +        virtual void setEdgeThreshold(double edge_threshold) = 0;
 +
 +        //! truncation of disparity continuity
 +        virtual double getMaxDiscThreshold() const = 0;
 +        virtual void setMaxDiscThreshold(double max_disc_threshold) = 0;
 +
 +        //! filter range sigma
 +        virtual double getSigmaRange() const = 0;
 +        virtual void setSigmaRange(double sigma_range) = 0;
 +    };
 +
 +
 +The class implements [Yang2010]_ algorithm.
 +
 +
 +
 +gpu::createDisparityBilateralFilter
 +-----------------------------------
 +Creates DisparityBilateralFilter object.
 +
 +.. ocv:function:: Ptr<gpu::DisparityBilateralFilter> gpu::createDisparityBilateralFilter(int ndisp = 64, int radius = 3, int iters = 1)
 +
 +    :param ndisp: Number of disparities.
 +
 +    :param radius: Filter radius.
 +
 +    :param iters: Number of iterations.
 +
 +
 +
 +gpu::DisparityBilateralFilter::apply
 +------------------------------------
 +Refines a disparity map using joint bilateral filtering.
 +
 +.. ocv:function:: void gpu::DisparityBilateralFilter::apply(InputArray disparity, InputArray image, OutputArray dst, Stream& stream = Stream::Null())
 +
 +    :param disparity: Input disparity map.  ``CV_8UC1``  and  ``CV_16SC1``  types are supported.
 +
 +    :param image: Input image. ``CV_8UC1``  and  ``CV_8UC3``  types are supported.
 +
 +    :param dst: Destination disparity map. It has the same size and type as  ``disparity`` .
 +
 +    :param stream: Stream for the asynchronous version.
 +
 +
 +
 +gpu::reprojectImageTo3D
 +-----------------------
 +Reprojects a disparity image to 3D space.
 +
 +.. ocv:function:: void gpu::reprojectImageTo3D(InputArray disp, OutputArray xyzw, InputArray Q, int dst_cn = 4, Stream& stream = Stream::Null())
 +
 +    :param disp: Input disparity image.  ``CV_8U``  and  ``CV_16S``  types are supported.
 +
 +    :param xyzw: Output 3- or 4-channel floating-point image of the same size as  ``disp`` . Each element of  ``xyzw(x,y)``  contains 3D coordinates ``(x,y,z)`` or ``(x,y,z,1)``  of the point  ``(x,y)`` , computed from the disparity map.
 +
 +    :param Q: :math:`4 \times 4`  perspective transformation matrix that can be obtained via  :ocv:func:`stereoRectify` .
 +
 +    :param dst_cn: The number of channels for output image. Can be 3 or 4.
 +
 +    :param stream: Stream for the asynchronous version.
 +
 +.. seealso:: :ocv:func:`reprojectImageTo3D`
 +
 +
 +
 +gpu::drawColorDisp
 +------------------
 +Colors a disparity image.
 +
 +.. ocv:function:: void gpu::drawColorDisp(InputArray src_disp, OutputArray dst_disp, int ndisp, Stream& stream = Stream::Null())
 +
 +    :param src_disp: Source disparity image.  ``CV_8UC1``  and  ``CV_16SC1``  types are supported.
 +
 +    :param dst_disp: Output disparity image. It has the same size as  ``src_disp`` . The  type is ``CV_8UC4``  in  ``BGRA``  format (alpha = 255).
 +
 +    :param ndisp: Number of disparities.
 +
 +    :param stream: Stream for the asynchronous version.
 +
 +This function draws a colored disparity map by converting disparity values from ``[0..ndisp)`` interval first to ``HSV`` color space (where different disparity values correspond to different hues) and then converting the pixels to ``RGB`` for visualization.
 +
 +
 +
 +.. [Felzenszwalb2006] Pedro F. Felzenszwalb algorithm [Pedro F. Felzenszwalb and Daniel P. Huttenlocher. *Efficient belief propagation for early vision*. International Journal of Computer Vision, 70(1), October 2006
 +.. [Yang2010] Q. Yang, L. Wang, and N. Ahuja. *A constant-space belief propagation algorithm for stereo matching*. In CVPR, 2010.
@@@ -20,14 -19,7 +19,13 @@@ if(HAVE_JPEG
    list(APPEND GRFMT_LIBS ${JPEG_LIBRARIES})
  endif()
  
- if(WITH_PNG)
-   add_definitions(-DHAVE_PNG)
 +if(WITH_WEBP)
 +  add_definitions(-DHAVE_WEBP)
 +  ocv_include_directories(${WEBP_INCLUDE_DIR})
 +  list(APPEND GRFMT_LIBS ${WEBP_LIBRARIES})
 +endif()
 +
+ if(HAVE_PNG)
    add_definitions(${PNG_DEFINITIONS})
    ocv_include_directories(${PNG_INCLUDE_DIR})
    list(APPEND GRFMT_LIBS ${PNG_LIBRARIES})
@@@ -216,19 -202,21 +208,17 @@@ if(HAVE_GIGE_API
    list(APPEND highgui_srcs src/cap_giganetix.cpp)
  endif(HAVE_GIGE_API)
  
- if(WITH_AVFOUNDATION)
-   add_definitions(-DHAVE_AVFOUNDATION=1)
 -if(HAVE_IMAGEIO AND IOS)
 -  list(APPEND HIGHGUI_LIBRARIES "-framework ImageIO")
 -endif()
 -
+ if(HAVE_AVFOUNDATION)
    list(APPEND highgui_srcs src/cap_avfoundation.mm)
    list(APPEND HIGHGUI_LIBRARIES "-framework AVFoundation" "-framework QuartzCore")
+ endif()
+ if(HAVE_QUICKTIME)
+   list(APPEND highgui_srcs src/cap_qt.cpp)
+   list(APPEND HIGHGUI_LIBRARIES "-framework Carbon" "-framework QuickTime" "-framework CoreFoundation" "-framework QuartzCore")
  elseif(APPLE)
-   add_definitions(-DHAVE_QUICKTIME=1)
-   if(WITH_QUICKTIME)
-     list(APPEND highgui_srcs src/cap_qt.cpp)
-     list(APPEND HIGHGUI_LIBRARIES "-framework Carbon" "-framework QuickTime" "-framework CoreFoundation" "-framework QuartzCore")
-   else()
-     list(APPEND highgui_srcs src/cap_qtkit.mm)
-     list(APPEND HIGHGUI_LIBRARIES "-framework QTKit" "-framework QuartzCore" "-framework AppKit")
-   endif()
+   list(APPEND highgui_srcs src/cap_qtkit.mm)
+   list(APPEND HIGHGUI_LIBRARIES "-framework QTKit" "-framework QuartzCore" "-framework AppKit")
  endif()
  
  if(IOS)
@@@ -86,9 -95,17 +91,15 @@@ Creates a window
  
  .. ocv:cfunction:: int cvNamedWindow( const char* name, int flags=CV_WINDOW_AUTOSIZE )
  
 -.. ocv:pyoldfunction:: cv.NamedWindow(name, flags=CV_WINDOW_AUTOSIZE)-> None
 -
      :param name: Name of the window in the window caption that may be used as a window identifier.
  
-     :param flags: Flags of the window. Currently the only supported flag is  ``CV_WINDOW_AUTOSIZE`` . If this is set, the window size is automatically adjusted to fit the displayed image (see  :ocv:func:`imshow` ), and you cannot change the window size manually.
+     :param flags: Flags of the window. The supported flags are:
+         * **WINDOW_NORMAL** If this is set, the user can resize the window (no constraint).
+         * **WINDOW_AUTOSIZE** If this is set, the window size is automatically adjusted to fit the displayed image (see  :ocv:func:`imshow` ), and you cannot change the window size manually.
+         * **WINDOW_OPENGL** If this is set, the window will be created with OpenGL support.
  
  The function ``namedWindow`` creates a window that can be used as a placeholder for images and trackbars. Created windows are referred to by their names.
  
Simple merge
Simple merge
Simple merge
@@@ -784,3 -810,9 +800,9 @@@ See the sample ``grabcut.cpp`` to lear
  .. [Meyer92] Meyer, F. *Color Image Segmentation*, ICIP92, 1992
  
  .. [Telea04] Alexandru Telea, *An Image Inpainting Technique Based on the Fast Marching Method*. Journal of Graphics, GPU, and Game Tools 9 1, pp 23-34 (2004)
 -   * : PYTHON : An example using the GrabCut algorithm can be found at opencv_source_code/samples/python2/grabcut.py
+ .. Sample code::
+    * : An example using the GrabCut algorithm can be found at opencv_source_code/samples/cpp/grabcut.cpp
++   * : PYTHON : An example using the GrabCut algorithm can be found at opencv_source_code/samples/python2/grabcut.py
@@@ -73,3 -74,6 +73,6 @@@ image patch
  After the function finishes the comparison, the best matches can be found as global minimums (when ``CV_TM_SQDIFF`` was used) or maximums (when ``CV_TM_CCORR`` or ``CV_TM_CCOEFF`` was used) using the
  :ocv:func:`minMaxLoc` function. In case of a color image, template summation in the numerator and each sum in the denominator is done over all of the channels and separate mean values are used for each channel. That is, the function can take a color template and a color image. The result will still be a single-channel image, which is easier to analyze.
  
 -   * : PYTHON : An example on how to match mouse selected regions in an image can be found at opencv_source_code/samples/python2/mouse_and_match.py
+ .. Sample code::
++   * : PYTHON : An example on how to match mouse selected regions in an image can be found at opencv_source_code/samples/python2/mouse_and_match.py
@@@ -192,6 -166,100 +192,14 @@@ The function retrieves contours from th
  
  .. note:: If you use the new Python interface then the ``CV_`` prefix has to be omitted in contour retrieval mode and contour approximation method parameters (for example, use ``cv2.RETR_LIST`` and ``cv2.CHAIN_APPROX_NONE`` parameters). If you use the old Python interface then these parameters have the ``CV_`` prefix (for example, use ``cv.CV_RETR_LIST`` and ``cv.CV_CHAIN_APPROX_NONE``).
  
 -drawContours
 -----------------
 -Draws contours outlines or filled contours.
 -
 -.. ocv:function:: void drawContours( InputOutputArray image, InputArrayOfArrays contours,                   int contourIdx, const Scalar& color, int thickness=1, int lineType=8, InputArray hierarchy=noArray(), int maxLevel=INT_MAX, Point offset=Point() )
 -
 -.. ocv:pyfunction:: cv2.drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset]]]]]) -> None
 -
 -.. ocv:cfunction:: void cvDrawContours( CvArr *img, CvSeq* contour, CvScalar externalColor, CvScalar holeColor, int maxLevel, int thickness=1, int lineType=8 )
 -.. ocv:pyoldfunction:: cv.DrawContours(img, contour, external_color, hole_color, max_level, thickness=1, lineType=8, offset=(0, 0))-> None
 -
 -    :param image: Destination image.
 -
 -    :param contours: All the input contours. Each contour is stored as a point vector.
 -
 -    :param contourIdx: Parameter indicating a contour to draw. If it is negative, all the contours are drawn.
 -
 -    :param color: Color of the contours.
 -
 -    :param thickness: Thickness of lines the contours are drawn with. If it is negative (for example,  ``thickness=CV_FILLED`` ), the contour interiors are
 -        drawn.
 -
 -    :param lineType: Line connectivity. See  :ocv:func:`line`  for details.
 -
 -    :param hierarchy: Optional information about hierarchy. It is only needed if you want to draw only some of the  contours (see  ``maxLevel`` ).
 -
 -    :param maxLevel: Maximal level for drawn contours. If it is 0, only
 -        the specified contour is drawn. If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This parameter is only taken into account when there is  ``hierarchy``  available.
 -
 -    :param offset: Optional contour shift parameter. Shift all the drawn contours by the specified  :math:`\texttt{offset}=(dx,dy)` .
 -
 -    :param contour: Pointer to the first contour.
 -
 -    :param externalColor: Color of external contours.
 -
 -    :param holeColor: Color of internal contours (holes).
 -
 -The function draws contour outlines in the image if
 -:math:`\texttt{thickness} \ge 0` or fills the area bounded by the contours if
 -:math:`\texttt{thickness}<0` . The example below shows how to retrieve connected components from the binary image and label them: ::
 -
 -    #include "cv.h"
 -    #include "highgui.h"
 -
 -    using namespace cv;
 -
 -    int main( int argc, char** argv )
 -    {
 -        Mat src;
 -        // the first command-line parameter must be a filename of the binary
 -        // (black-n-white) image
 -        if( argc != 2 || !(src=imread(argv[1], 0)).data)
 -            return -1;
 -
 -        Mat dst = Mat::zeros(src.rows, src.cols, CV_8UC3);
 -
 -        src = src > 1;
 -        namedWindow( "Source", 1 );
 -        imshow( "Source", src );
 -
 -        vector<vector<Point> > contours;
 -        vector<Vec4i> hierarchy;
 -
 -        findContours( src, contours, hierarchy,
 -            CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
 -
 -        // iterate through all the top-level contours,
 -        // draw each connected component with its own random color
 -        int idx = 0;
 -        for( ; idx >= 0; idx = hierarchy[idx][0] )
 -        {
 -            Scalar color( rand()&255, rand()&255, rand()&255 );
 -            drawContours( dst, contours, idx, color, CV_FILLED, 8, hierarchy );
 -        }
 -
 -        namedWindow( "Components", 1 );
 -        imshow( "Components", dst );
 -        waitKey(0);
 -    }
 -
 -.. Sample code::
 -
 -   * : An example using the drawContour functionality can be found at opencv_source_code/samples/cpp/contours2.cpp
 -   * : An example using drawContours to clean up a background segmentation result at opencv_source_code/samples/cpp/segment_objects.cpp
 -
 -   * : PYTHON : An example using the drawContour functionality can be found at opencv_source/samples/python2/contours.py
+ .. Sample code::
+    * : An example using the findContour functionality can be found at opencv_source_code/samples/cpp/contours2.cpp
+    * : An example using findContours to clean up a background segmentation result at opencv_source_code/samples/cpp/segment_objects.cpp
+    * : PYTHON : An example using the findContour functionality can be found at opencv_source/samples/python2/contours.py
+    * : PYTHON : An example of detecting squares in an image can be found at opencv_source/samples/python2/squares.py
  
  approxPolyDP
  ----------------
@@@ -406,6 -490,10 +418,11 @@@ Fits an ellipse around a set of 2D poin
  
  The function calculates the ellipse that fits (in a least-squares sense) a set of 2D points best of all. It returns the rotated rectangle in which the ellipse is inscribed. The algorithm [Fitzgibbon95]_ is used.
  
+ .. Sample code::
+    * : An example using the fitEllipse technique can be found at opencv_source_code/samples/cpp/fitellipse.cpp
++
  fitLine
  -----------
  Fits a line to a 2D or 3D point set.
@@@ -476,8 -566,10 +493,11 @@@ http://en.wikipedia.org/wiki/M-estimato
  :math:`w_i` are adjusted to be inversely proportional to
  :math:`\rho(r_i)` .
  
+ .. Sample code:
+    * : PYTHON : An example of robust line fitting can be found at opencv_source_code/samples/python2/fitline.py
  
 +
  isContourConvex
  -------------------
  Tests a contour convexity.
Simple merge
Simple merge
@@@ -1,12 -1,37 +1,37 @@@
  #define LOG_TAG "org.opencv.core.Mat"
  
+ #include <stdexcept>
  #include "common.h"
 -#include "opencv2/core/core.hpp"
 +#include "opencv2/core.hpp"
  
  using namespace cv;
  
 -  
+ /// throw java exception
+ static void throwJavaException(JNIEnv *env, const std::exception *e, const char *method) {
+   std::string what = "unknown exception";
+   jclass je = 0;
 -    
++
+   if(e) {
+     std::string exception_type = "std::exception";
 -  
++
+     if(dynamic_cast<const cv::Exception*>(e)) {
+       exception_type = "cv::Exception";
+       je = env->FindClass("org/opencv/core/CvException");
+     }
+     what = exception_type + ": " + e->what();
+   }
 -  
++
+   if(!je) je = env->FindClass("java/lang/Exception");
+   env->ThrowNew(je, what.c_str());
++
+   LOGE("%s caught %s", method, what.c_str());
+   (void)method;        // avoid "unused" warning
+ }
  extern "C" {
 -  
 +
  
  //
  //   MatXXX::MatXXX()
@@@ -35,24 -60,17 +60,17 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
  JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1Mat__III
    (JNIEnv* env, jclass, jint rows, jint cols, jint type)
  {
+     static const char method_name[] = "Mat::n_1Mat__III()";
      try {
-         LOGD("Mat::n_1Mat__III()");
-         Mat* _retval_ = new Mat( rows, cols, type );
-         return (jlong) _retval_;
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1Mat__III() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+         LOGD("%s", method_name);
+         return (jlong) new Mat( rows, cols, type );
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1Mat__III() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1Mat__III()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -67,24 -85,18 +85,18 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
  JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1Mat__DDI
    (JNIEnv* env, jclass, jdouble size_width, jdouble size_height, jint type)
  {
+     static const char method_name[] = "Mat::n_1Mat__DDI()";
      try {
-         LOGD("Mat::n_1Mat__DDI()");
+         LOGD("%s", method_name);
          Size size((int)size_width, (int)size_height);
-         Mat* _retval_ = new Mat( size, type );
-         return (jlong) _retval_;
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1Mat__DDI() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+         return (jlong) new Mat( size, type );
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1Mat__DDI() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1Mat__DDI()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -100,24 -112,18 +112,18 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
  JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1Mat__IIIDDDD
    (JNIEnv* env, jclass, jint rows, jint cols, jint type, jdouble s_val0, jdouble s_val1, jdouble s_val2, jdouble s_val3)
  {
+     static const char method_name[] = "Mat::n_1Mat__IIIDDDD()";
      try {
-         LOGD("Mat::n_1Mat__IIIDDDD()");
+         LOGD("%s", method_name);
          Scalar s(s_val0, s_val1, s_val2, s_val3);
-         Mat* _retval_ = new Mat( rows, cols, type, s );
-         return (jlong) _retval_;
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1Mat__IIIDDDD() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+         return (jlong) new Mat( rows, cols, type, s );
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1Mat__IIIDDDD() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1Mat__IIIDDDD()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -132,25 -138,19 +138,19 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
  JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1Mat__DDIDDDD
    (JNIEnv* env, jclass, jdouble size_width, jdouble size_height, jint type, jdouble s_val0, jdouble s_val1, jdouble s_val2, jdouble s_val3)
  {
+     static const char method_name[] = "Mat::n_1Mat__DDIDDDD()";
      try {
-         LOGD("Mat::n_1Mat__DDIDDDD()");
+         LOGD("%s", method_name);
          Size size((int)size_width, (int)size_height);
          Scalar s(s_val0, s_val1, s_val2, s_val3);
-         Mat* _retval_ = new Mat( size, type, s );
-         return (jlong) _retval_;
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1Mat__DDIDDDD() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+         return (jlong) new Mat( size, type, s );
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1Mat__DDIDDDD() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1Mat__DDIDDDD()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -165,25 -165,19 +165,19 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
  JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1Mat__JIIII
    (JNIEnv* env, jclass, jlong m_nativeObj, jint rowRange_start, jint rowRange_end, jint colRange_start, jint colRange_end)
  {
+     static const char method_name[] = "Mat::n_1Mat__JIIII()";
      try {
-         LOGD("Mat::n_1Mat__JIIII()");
+         LOGD("%s", method_name);
          Range rowRange(rowRange_start, rowRange_end);
          Range colRange(colRange_start, colRange_end);
-         Mat* _retval_ = new Mat( (*(Mat*)m_nativeObj), rowRange, colRange );
-         return (jlong) _retval_;
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1Mat__JIIII() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+         return (jlong) new Mat( (*(Mat*)m_nativeObj), rowRange, colRange );
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1Mat__JIIII() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1Mat__JIIII()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -194,24 -188,18 +188,18 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
  JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1Mat__JII
    (JNIEnv* env, jclass, jlong m_nativeObj, jint rowRange_start, jint rowRange_end)
  {
+     static const char method_name[] = "Mat::n_1Mat__JII()";
      try {
-         LOGD("Mat::n_1Mat__JII()");
+         LOGD("%s", method_name);
          Range rowRange(rowRange_start, rowRange_end);
-         Mat* _retval_ = new Mat( (*(Mat*)m_nativeObj), rowRange );
-         return (jlong) _retval_;
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1Mat__JII() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+         return (jlong) new Mat( (*(Mat*)m_nativeObj), rowRange );
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1Mat__JII() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1Mat__JII()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -225,24 -213,19 +213,19 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
  JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1adjustROI
    (JNIEnv* env, jclass, jlong self, jint dtop, jint dbottom, jint dleft, jint dright)
  {
+     static const char method_name[] = "Mat::n_1adjustROI()";
      try {
-         LOGD("Mat::n_1adjustROI()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
          Mat _retval_ = me->adjustROI( dtop, dbottom, dleft, dright );
          return (jlong) new Mat(_retval_);
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1adjustROI() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1adjustROI() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1adjustROI()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -316,24 -283,18 +283,18 @@@ JNIEXPORT jint JNICALL Java_org_opencv_
  JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1channels
    (JNIEnv* env, jclass, jlong self)
  {
+     static const char method_name[] = "Mat::n_1channels()";
      try {
-         LOGD("Mat::n_1channels()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
-         int _retval_ = me->channels(  );
-         return _retval_;
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1channels() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+         return me->channels(  );
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1channels() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1channels()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -348,24 -309,18 +309,18 @@@ JNIEXPORT jint JNICALL Java_org_opencv_
  JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1checkVector__JIIZ
    (JNIEnv* env, jclass, jlong self, jint elemChannels, jint depth, jboolean requireContinuous)
  {
+     static const char method_name[] = "Mat::n_1checkVector__JIIZ()";
      try {
-         LOGD("Mat::n_1checkVector__JIIZ()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
-         int _retval_ = me->checkVector( elemChannels, depth, requireContinuous );
-         return _retval_;
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1checkVector__JIIZ() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+         return me->checkVector( elemChannels, depth, requireContinuous );
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1checkVector__JIIZ() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1checkVector__JIIZ()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -376,24 -331,18 +331,18 @@@ JNIEXPORT jint JNICALL Java_org_opencv_
  JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1checkVector__JII
    (JNIEnv* env, jclass, jlong self, jint elemChannels, jint depth)
  {
+     static const char method_name[] = "Mat::n_1checkVector__JII()";
      try {
-         LOGD("Mat::n_1checkVector__JII()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
-         int _retval_ = me->checkVector( elemChannels, depth );
-         return _retval_;
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1checkVector__JII() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+         return me->checkVector( elemChannels, depth );
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1checkVector__JII() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1checkVector__JII()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -404,24 -353,18 +353,18 @@@ JNIEXPORT jint JNICALL Java_org_opencv_
  JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1checkVector__JI
    (JNIEnv* env, jclass, jlong self, jint elemChannels)
  {
+     static const char method_name[] = "Mat::n_1checkVector__JI()";
      try {
-         LOGD("Mat::n_1checkVector__JI()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
-         int _retval_ = me->checkVector( elemChannels );
-         return _retval_;
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1checkVector__JI() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+         return me->checkVector( elemChannels );
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1checkVector__JI() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1checkVector__JI()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -437,24 -380,19 +380,19 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
  JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1clone
    (JNIEnv* env, jclass, jlong self)
  {
+     static const char method_name[] = "Mat::n_1clone()";
      try {
-         LOGD("Mat::n_1clone()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
          Mat _retval_ = me->clone(  );
          return (jlong) new Mat(_retval_);
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1clone() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1clone() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1clone()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -469,24 -407,19 +407,19 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
  JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1col
    (JNIEnv* env, jclass, jlong self, jint x)
  {
+     static const char method_name[] = "Mat::n_1col()";
      try {
-         LOGD("Mat::n_1col()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
          Mat _retval_ = me->col( x );
          return (jlong) new Mat(_retval_);
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1col() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1col() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1col()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -501,24 -434,19 +434,19 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
  JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1colRange
    (JNIEnv* env, jclass, jlong self, jint startcol, jint endcol)
  {
+     static const char method_name[] = "Mat::n_1colRange()";
      try {
-         LOGD("Mat::n_1colRange()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
          Mat _retval_ = me->colRange( startcol, endcol );
          return (jlong) new Mat(_retval_);
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1colRange() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1colRange() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1colRange()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -533,24 -461,18 +461,18 @@@ JNIEXPORT jint JNICALL Java_org_opencv_
  JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1dims
    (JNIEnv* env, jclass, jlong self)
  {
+     static const char method_name[] = "Mat::n_1dims()";
      try {
-         LOGD("Mat::n_1dims()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
-         int _retval_ = me->dims;
-         return _retval_;
+         return me->dims;
      } catch(cv::Exception e) {
-         LOGD("Mat::n_1dims() catched cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1dims() catched unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1dims()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -564,24 -487,18 +487,18 @@@ JNIEXPORT jint JNICALL Java_org_opencv_
  JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1cols
    (JNIEnv* env, jclass, jlong self)
  {
+     static const char method_name[] = "Mat::n_1cols()";
      try {
-         LOGD("Mat::n_1cols()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
-         int _retval_ = me->cols;
-         return _retval_;
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1cols() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+         return me->cols;
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1cols() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1cols()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -822,20 -684,14 +684,14 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
          Mat* me = (Mat*) self; //TODO: check for NULL
          Mat& m = *((Mat*)m_nativeObj);
          Mat _retval_ = me->cross( m );
          return (jlong) new Mat(_retval_);
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1cross() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1cross() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1cross()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -867,24 -723,18 +723,18 @@@ JNIEXPORT jint JNICALL Java_org_opencv_
  JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1depth
    (JNIEnv* env, jclass, jlong self)
  {
+     static const char method_name[] = "Mat::n_1depth()";
      try {
-         LOGD("Mat::n_1depth()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
-         int _retval_ = me->depth(  );
-         return _retval_;
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1depth() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+         return me->depth(  );
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1depth() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1depth()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -899,24 -749,19 +749,19 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
  JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1diag__JI
    (JNIEnv* env, jclass, jlong self, jint d)
  {
+     static const char method_name[] = "Mat::n_1diag__JI()";
      try {
-         LOGD("Mat::n_1diag__JI()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
          Mat _retval_ = me->diag( d );
          return (jlong) new Mat(_retval_);
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1diag__JI() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1diag__JI() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1diag__JI()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -932,24 -777,18 +777,18 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
  JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1diag__J
    (JNIEnv* env, jclass, jlong d_nativeObj)
  {
+     static const char method_name[] = "Mat::n_1diag__J()";
      try {
-         LOGD("Mat::n_1diag__J()");
+         LOGD("%s", method_name);
          Mat _retval_ = Mat::diag( (*(Mat*)d_nativeObj) );
          return (jlong) new Mat(_retval_);
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1diag__J() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1diag__J() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1diag__J()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -964,25 -803,19 +803,19 @@@ JNIEXPORT jdouble JNICALL Java_org_open
  JNIEXPORT jdouble JNICALL Java_org_opencv_core_Mat_n_1dot
    (JNIEnv* env, jclass, jlong self, jlong m_nativeObj)
  {
+     static const char method_name[] = "Mat::n_1dot()";
      try {
-         LOGD("Mat::n_1dot()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
          Mat& m = *((Mat*)m_nativeObj);
-         double _retval_ = me->dot( m );
-         return _retval_;
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1dot() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+         return me->dot( m );
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1dot() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1dot()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -997,24 -830,18 +830,18 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
  JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1elemSize
    (JNIEnv* env, jclass, jlong self)
  {
+     static const char method_name[] = "Mat::n_1elemSize()";
      try {
-         LOGD("Mat::n_1elemSize()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
-         size_t _retval_ = me->elemSize(  );
-         return _retval_;
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1elemSize() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+         return me->elemSize(  );
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1elemSize() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1elemSize()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -1029,24 -856,18 +856,18 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
  JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1elemSize1
    (JNIEnv* env, jclass, jlong self)
  {
+     static const char method_name[] = "Mat::n_1elemSize1()";
      try {
-         LOGD("Mat::n_1elemSize1()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
-         size_t _retval_ = me->elemSize1(  );
-         return _retval_;
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1elemSize1() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+         return me->elemSize1(  );
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1elemSize1() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1elemSize1()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -1061,24 -882,18 +882,18 @@@ JNIEXPORT jboolean JNICALL Java_org_ope
  JNIEXPORT jboolean JNICALL Java_org_opencv_core_Mat_n_1empty
    (JNIEnv* env, jclass, jlong self)
  {
+     static const char method_name[] = "Mat::n_1empty()";
      try {
-         LOGD("Mat::n_1empty()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
-         bool _retval_ = me->empty(  );
-         return _retval_;
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1empty() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+         return me->empty(  );
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1empty() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1empty()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -1093,24 -908,18 +908,18 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
  JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1eye__III
    (JNIEnv* env, jclass, jint rows, jint cols, jint type)
  {
+     static const char method_name[] = "Mat::n_1eye__III()";
      try {
-         LOGD("Mat::n_1eye__III()");
+         LOGD("%s", method_name);
          Mat _retval_ = Mat::eye( rows, cols, type );
          return (jlong) new Mat(_retval_);
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1eye__III() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1eye__III() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1eye__III()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -1125,24 -934,19 +934,19 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
  JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1eye__DDI
    (JNIEnv* env, jclass, jdouble size_width, jdouble size_height, jint type)
  {
+     static const char method_name[] = "Mat::n_1eye__DDI()";
      try {
-         LOGD("Mat::n_1eye__DDI()");
+         LOGD("%s", method_name);
          Size size((int)size_width, (int)size_height);
          Mat _retval_ = Mat::eye( size, type );
          return (jlong) new Mat(_retval_);
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1eye__DDI() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1eye__DDI() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1eye__DDI()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -1157,24 -961,19 +961,19 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
  JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1inv__JI
    (JNIEnv* env, jclass, jlong self, jint method)
  {
+     static const char method_name[] = "Mat::n_1inv__JI()";
      try {
-         LOGD("Mat::n_1inv__JI()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
          Mat _retval_ = me->inv( method );
          return (jlong) new Mat(_retval_);
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1inv__JI() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1inv__JI() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1inv__JI()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -1184,24 -983,19 +983,19 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
  JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1inv__J
    (JNIEnv* env, jclass, jlong self)
  {
+     static const char method_name[] = "Mat::n_1inv__J()";
      try {
-         LOGD("Mat::n_1inv__J()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
          Mat _retval_ = me->inv(  );
          return (jlong) new Mat(_retval_);
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1inv__J() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1inv__J() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1inv__J()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -1216,24 -1010,18 +1010,18 @@@ JNIEXPORT jboolean JNICALL Java_org_ope
  JNIEXPORT jboolean JNICALL Java_org_opencv_core_Mat_n_1isContinuous
    (JNIEnv* env, jclass, jlong self)
  {
+     static const char method_name[] = "Mat::n_1isContinuous()";
      try {
-         LOGD("Mat::n_1isContinuous()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
-         bool _retval_ = me->isContinuous(  );
-         return _retval_;
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1isContinuous() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+         return me->isContinuous(  );
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1isContinuous() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1isContinuous()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -1248,24 -1036,18 +1036,18 @@@ JNIEXPORT jboolean JNICALL Java_org_ope
  JNIEXPORT jboolean JNICALL Java_org_opencv_core_Mat_n_1isSubmatrix
    (JNIEnv* env, jclass, jlong self)
  {
+     static const char method_name[] = "Mat::n_1isSubmatrix()";
      try {
-         LOGD("Mat::n_1isSubmatrix()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
-         bool _retval_ = me->isSubmatrix(  );
-         return _retval_;
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1isSubmatrix() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+         return me->isSubmatrix(  );
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1isSubmatrix() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1isSubmatrix()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -1319,20 -1095,14 +1095,14 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
          Mat* me = (Mat*) self; //TODO: check for NULL
          Mat& m = *((Mat*)m_nativeObj);
          Mat _retval_ = me->mul( m, scale );
          return (jlong) new Mat(_retval_);
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1mul__JJD() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1mul__JJD() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1mul__JJD()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -1504,24 -1242,19 +1242,19 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
  JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1reshape__JII
    (JNIEnv* env, jclass, jlong self, jint cn, jint rows)
  {
+     static const char method_name[] = "Mat::n_1reshape__JII()";
      try {
-         LOGD("Mat::n_1reshape__JII()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
          Mat _retval_ = me->reshape( cn, rows );
          return (jlong) new Mat(_retval_);
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1reshape__JII() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1reshape__JII() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1reshape__JII()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -1532,24 -1265,19 +1265,19 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
  JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1reshape__JI
    (JNIEnv* env, jclass, jlong self, jint cn)
  {
+     static const char method_name[] = "Mat::n_1reshape__JI()";
      try {
-         LOGD("Mat::n_1reshape__JI()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
          Mat _retval_ = me->reshape( cn );
          return (jlong) new Mat(_retval_);
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1reshape__JI() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1reshape__JI() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1reshape__JI()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -1564,24 -1292,19 +1292,19 @@@ JNIEXPORT jlong JNICALL Java_org_opencv
  JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1row
    (JNIEnv* env, jclass, jlong self, jint y)
  {
+     static const char method_name[] = "Mat::n_1row()";
      try {
-         LOGD("Mat::n_1row()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
          Mat _retval_ = me->row( y );
          return (jlong) new Mat(_retval_);
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1row() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1row() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1row()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
 -    
++
+     return 0;
  }
  
  
@@@ -1790,24 -1482,22 +1482,22 @@@ JNIEXPORT jdoubleArray JNICALL Java_org
  JNIEXPORT jdoubleArray JNICALL Java_org_opencv_core_Mat_n_1size
    (JNIEnv* env, jclass, jlong self)
  {
+     static const char method_name[] = "Mat::n_1size()";
      try {
-         LOGD("Mat::n_1size()");
+         LOGD("%s", method_name);
          Mat* me = (Mat*) self; //TODO: check for NULL
          Size _retval_ = me->size(  );
-         jdoubleArray _da_retval_ = env->NewDoubleArray(2);  jdouble _tmp_retval_[2] = {_retval_.width, _retval_.height}; env->SetDoubleArrayRegion(_da_retval_, 0, 2, _tmp_retval_);
 -        jdoubleArray _da_retval_ = env->NewDoubleArray(2);  
++        jdoubleArray _da_retval_ = env->NewDoubleArray(2);
+         jdouble _tmp_retval_[2] = {_retval_.width, _retval_.height};
+         env->SetDoubleArrayRegion(_da_retval_, 0, 2, _tmp_retval_);
          return _da_retval_;
-     } catch(cv::Exception e) {
-         LOGD("Mat::n_1size() caught cv::Exception: %s", e.what());
-         jclass je = env->FindClass("org/opencv/core/CvException");
-         if(!je) je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, e.what());
-         return 0;
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
      } catch (...) {
-         LOGD("Mat::n_1size() caught unknown exception (...)");
-         jclass je = env->FindClass("java/lang/Exception");
-         env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1size()}");
-         return 0;
+         throwJavaException(env, 0, method_name);
      }
+     return 0;
  }
  
  
@@@ -2573,28 -2169,21 +2169,24 @@@ JNIEXPORT jstring JNICALL Java_org_open
  JNIEXPORT jstring JNICALL Java_org_opencv_core_Mat_nDump
    (JNIEnv *env, jclass, jlong self)
  {
-     cv::Mat* me = (cv::Mat*) self; //TODO: check for NULL
+     static const char method_name[] = "Mat::nDump()";
      try {
-             LOGD("Mat::nDump()");
-             String s;
-             Ptr<Formatted> fmtd = Formatter::get()->format(*me);
-             for(const char* str = fmtd->next(); str; str = fmtd->next())
-             {
-                 s = s + String(str);
-             }
-             return env->NewStringUTF(s.c_str());
-         } catch(cv::Exception e) {
-             LOGE("Mat::nDump() caught cv::Exception: %s", e.what());
-             jclass je = env->FindClass("org/opencv/core/CvException");
-             if(!je) je = env->FindClass("java/lang/Exception");
-             env->ThrowNew(je, e.what());
-             return env->NewStringUTF("ERROR");
-         } catch (...) {
-             LOGE("Mat::nDump() caught unknown exception (...)");
-             jclass je = env->FindClass("java/lang/Exception");
-             env->ThrowNew(je, "Unknown exception in JNI code {Mat::nDump()}");
-             return env->NewStringUTF("ERROR");
+         LOGD("%s", method_name);
+         cv::Mat* me = (cv::Mat*) self; //TODO: check for NULL
 -        std::stringstream s;
 -        s << *me;
 -        std::string str = s.str();
 -        return env->NewStringUTF(str.c_str());
++        String s;
++        Ptr<Formatted> fmtd = Formatter::get()->format(*me);
++        for(const char* str = fmtd->next(); str; str = fmtd->next())
++        {
++            s = s + String(str);
 +        }
++        return env->NewStringUTF(s.c_str());
+     } catch(const std::exception &e) {
+         throwJavaException(env, &e, method_name);
+     } catch (...) {
+         throwJavaException(env, 0, method_name);
+     }
+     return 0;
  }
  
  
@@@ -188,5 -194,5 +194,3 @@@ The sample below (currently using the o
          cvReleaseMat( &trainData );
          return 0;
      }
--
--
  #ifndef __OPENCV_PRECOMP_H__
  #define __OPENCV_PRECOMP_H__
  
 -#include "cvconfig.h"
--
 -#include "opencv2/ml/ml.hpp"
 +#include "opencv2/core.hpp"
 +#include "opencv2/ml.hpp"
  #include "opencv2/core/core_c.h"
 -#include "opencv2/core/internal.hpp"
 +#include "opencv2/core/utility.hpp"
 +
 +#include "opencv2/core/private.hpp"
  
  #include <assert.h>
  #include <float.h>
@@@ -337,3 -335,7 +344,7 @@@ The ``descriptors`` matrix is :math:`\t
  The class ``SURF_OCL`` uses some buffers and provides access to it. All buffers can be safely released between function calls.
  
  .. seealso:: :ocv:class:`SURF`
 -   * : OCL : An example of the SURF detector can be found at opencv_source_code/samples/ocl/surf_matcher.cpp
+ .. Sample code::
++   * : OCL : An example of the SURF detector can be found at opencv_source_code/samples/ocl/surf_matcher.cpp
index ca78f1a,0000000..febd3ae
mode 100644,000000..100644
--- /dev/null
@@@ -1,412 -1,0 +1,430 @@@
 +/*M///////////////////////////////////////////////////////////////////////////////////////
 +//
 +//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
 +//
 +//  By downloading, copying, installing or using the software you agree to this license.
 +//  If you do not agree to this license, do not download, install,
 +//  copy or use the software.
 +//
 +//
 +//                          License Agreement
 +//                For Open Source Computer Vision Library
 +//
 +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
 +// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
 +// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
 +// Third party copyrights are property of their respective owners.
 +//
 +// Redistribution and use in source and binary forms, with or without modification,
 +// are permitted provided that the following conditions are met:
 +//
 +//   * Redistribution's of source code must retain the above copyright notice,
 +//     this list of conditions and the following disclaimer.
 +//
 +//   * Redistribution's in binary form must reproduce the above copyright notice,
 +//     this list of conditions and the following disclaimer in the documentation
 +//     and/or other materials provided with the distribution.
 +//
 +//   * The name of the copyright holders may not be used to endorse or promote products
 +//     derived from this software without specific prior written permission.
 +//
 +// This software is provided by the copyright holders and contributors "as is" and
 +// any express or implied warranties, including, but not limited to, the implied
 +// warranties of merchantability and fitness for a particular purpose are disclaimed.
 +// In no event shall the Intel Corporation or contributors be liable for any direct,
 +// indirect, incidental, special, exemplary, or consequential damages
 +// (including, but not limited to, procurement of substitute goods or services;
 +// loss of use, data, or profits; or business interruption) however caused
 +// and on any theory of liability, whether in contract, strict liability,
 +// or tort (including negligence or otherwise) arising in any way out of
 +// the use of this software, even if advised of the possibility of such damage.
 +//
 +//M*/
 +
 +#ifndef __OPENCV_OBJDETECT_HPP__
 +#define __OPENCV_OBJDETECT_HPP__
 +
 +#include "opencv2/core.hpp"
 +
 +typedef struct CvLatentSvmDetector CvLatentSvmDetector;
 +typedef struct CvHaarClassifierCascade CvHaarClassifierCascade;
 +
 +namespace cv
 +{
 +
 +///////////////////////////// Object Detection ////////////////////////////
 +
 +/*
 + * This is a class wrapping up the structure CvLatentSvmDetector and functions working with it.
 + * The class goals are:
 + * 1) provide c++ interface;
 + * 2) make it possible to load and detect more than one class (model) unlike CvLatentSvmDetector.
 + */
 +class CV_EXPORTS LatentSvmDetector
 +{
 +public:
 +    struct CV_EXPORTS ObjectDetection
 +    {
 +        ObjectDetection();
 +        ObjectDetection( const Rect& rect, float score, int classID = -1 );
 +        Rect rect;
 +        float score;
 +        int classID;
 +    };
 +
 +    LatentSvmDetector();
 +    LatentSvmDetector( const std::vector<String>& filenames, const std::vector<String>& classNames = std::vector<String>() );
 +    virtual ~LatentSvmDetector();
 +
 +    virtual void clear();
 +    virtual bool empty() const;
 +    bool load( const std::vector<String>& filenames, const std::vector<String>& classNames = std::vector<String>() );
 +
 +    virtual void detect( const Mat& image,
 +                         std::vector<ObjectDetection>& objectDetections,
 +                         float overlapThreshold = 0.5f,
 +                         int numThreads = -1 );
 +
 +    const std::vector<String>& getClassNames() const;
 +    size_t getClassCount() const;
 +
 +private:
 +    std::vector<CvLatentSvmDetector*> detectors;
 +    std::vector<String> classNames;
 +};
 +
++// class for grouping object candidates, detected by Cascade Classifier, HOG etc.
++// instance of the class is to be passed to cv::partition (see cxoperations.hpp)
++class CV_EXPORTS SimilarRects
++{
++public:
++    SimilarRects(double _eps) : eps(_eps) {}
++    inline bool operator()(const Rect& r1, const Rect& r2) const
++    {
++        double delta = eps*(std::min(r1.width, r2.width) + std::min(r1.height, r2.height))*0.5;
++        return std::abs(r1.x - r2.x) <= delta &&
++            std::abs(r1.y - r2.y) <= delta &&
++            std::abs(r1.x + r1.width - r2.x - r2.width) <= delta &&
++            std::abs(r1.y + r1.height - r2.y - r2.height) <= delta;
++    }
++    double eps;
++};
++
 +CV_EXPORTS   void groupRectangles(std::vector<Rect>& rectList, int groupThreshold, double eps = 0.2);
 +CV_EXPORTS_W void groupRectangles(CV_IN_OUT std::vector<Rect>& rectList, CV_OUT std::vector<int>& weights, int groupThreshold, double eps = 0.2);
 +CV_EXPORTS   void groupRectangles(std::vector<Rect>& rectList, int groupThreshold, double eps, std::vector<int>* weights, std::vector<double>* levelWeights );
 +CV_EXPORTS   void groupRectangles(std::vector<Rect>& rectList, std::vector<int>& rejectLevels,
 +                                  std::vector<double>& levelWeights, int groupThreshold, double eps = 0.2);
 +CV_EXPORTS   void groupRectangles_meanshift(std::vector<Rect>& rectList, std::vector<double>& foundWeights, std::vector<double>& foundScales,
 +                                          double detectThreshold = 0.0, Size winDetSize = Size(64, 128));
 +
 +class CV_EXPORTS FeatureEvaluator
 +{
 +public:
 +    enum { HAAR = 0,
 +           LBP  = 1,
 +           HOG  = 2
 +         };
 +
 +    virtual ~FeatureEvaluator();
 +
 +    virtual bool read(const FileNode& node);
 +    virtual Ptr<FeatureEvaluator> clone() const;
 +    virtual int getFeatureType() const;
 +
 +    virtual bool setImage(const Mat& img, Size origWinSize);
 +    virtual bool setWindow(Point p);
 +
 +    virtual double calcOrd(int featureIdx) const;
 +    virtual int calcCat(int featureIdx) const;
 +
 +    static Ptr<FeatureEvaluator> create(int type);
 +};
 +
 +template<> CV_EXPORTS void Ptr<CvHaarClassifierCascade>::delete_obj();
 +
 +enum { CASCADE_DO_CANNY_PRUNING    = 1,
 +       CASCADE_SCALE_IMAGE         = 2,
 +       CASCADE_FIND_BIGGEST_OBJECT = 4,
 +       CASCADE_DO_ROUGH_SEARCH     = 8
 +     };
 +
 +class CV_EXPORTS_W CascadeClassifier
 +{
 +public:
 +    CV_WRAP CascadeClassifier();
 +    CV_WRAP CascadeClassifier( const String& filename );
 +    virtual ~CascadeClassifier();
 +
 +    CV_WRAP virtual bool empty() const;
 +    CV_WRAP bool load( const String& filename );
 +    virtual bool read( const FileNode& node );
 +    CV_WRAP virtual void detectMultiScale( const Mat& image,
 +                                   CV_OUT std::vector<Rect>& objects,
 +                                   double scaleFactor = 1.1,
 +                                   int minNeighbors = 3, int flags = 0,
 +                                   Size minSize = Size(),
 +                                   Size maxSize = Size() );
 +
 +    CV_WRAP virtual void detectMultiScale( const Mat& image,
 +                                   CV_OUT std::vector<Rect>& objects,
 +                                   CV_OUT std::vector<int>& numDetections,
 +                                   double scaleFactor=1.1,
 +                                   int minNeighbors=3, int flags=0,
 +                                   Size minSize=Size(),
 +                                   Size maxSize=Size() );
 +
 +    CV_WRAP virtual void detectMultiScale( const Mat& image,
 +                                   CV_OUT std::vector<Rect>& objects,
 +                                   CV_OUT std::vector<int>& rejectLevels,
 +                                   CV_OUT std::vector<double>& levelWeights,
 +                                   double scaleFactor = 1.1,
 +                                   int minNeighbors = 3, int flags = 0,
 +                                   Size minSize = Size(),
 +                                   Size maxSize = Size(),
 +                                   bool outputRejectLevels = false );
 +
 +
 +    bool isOldFormatCascade() const;
 +    virtual Size getOriginalWindowSize() const;
 +    int getFeatureType() const;
 +    bool setImage( const Mat& );
 +
 +protected:
 +    virtual bool detectSingleScale( const Mat& image, int stripCount, Size processingRectSize,
 +                                    int stripSize, int yStep, double factor, std::vector<Rect>& candidates,
 +                                    std::vector<int>& rejectLevels, std::vector<double>& levelWeights, bool outputRejectLevels = false );
 +
 +    virtual void detectMultiScaleNoGrouping( const Mat& image, std::vector<Rect>& candidates,
 +                                             std::vector<int>& rejectLevels, std::vector<double>& levelWeights,
 +                                             double scaleFactor, Size minObjectSize, Size maxObjectSize,
 +                                             bool outputRejectLevels = false );
 +
 +protected:
 +    enum { BOOST = 0
 +         };
 +    enum { DO_CANNY_PRUNING    = CASCADE_DO_CANNY_PRUNING,
 +           SCALE_IMAGE         = CASCADE_SCALE_IMAGE,
 +           FIND_BIGGEST_OBJECT = CASCADE_FIND_BIGGEST_OBJECT,
 +           DO_ROUGH_SEARCH     = CASCADE_DO_ROUGH_SEARCH
 +         };
 +
 +    friend class CascadeClassifierInvoker;
 +
 +    template<class FEval>
 +    friend int predictOrdered( CascadeClassifier& cascade, Ptr<FeatureEvaluator> &featureEvaluator, double& weight);
 +
 +    template<class FEval>
 +    friend int predictCategorical( CascadeClassifier& cascade, Ptr<FeatureEvaluator> &featureEvaluator, double& weight);
 +
 +    template<class FEval>
 +    friend int predictOrderedStump( CascadeClassifier& cascade, Ptr<FeatureEvaluator> &featureEvaluator, double& weight);
 +
 +    template<class FEval>
 +    friend int predictCategoricalStump( CascadeClassifier& cascade, Ptr<FeatureEvaluator> &featureEvaluator, double& weight);
 +
 +    bool setImage( Ptr<FeatureEvaluator>& feval, const Mat& image);
 +    virtual int runAt( Ptr<FeatureEvaluator>& feval, Point pt, double& weight );
 +
 +    class Data
 +    {
 +    public:
 +        struct CV_EXPORTS DTreeNode
 +        {
 +            int featureIdx;
 +            float threshold; // for ordered features only
 +            int left;
 +            int right;
 +        };
 +
 +        struct CV_EXPORTS DTree
 +        {
 +            int nodeCount;
 +        };
 +
 +        struct CV_EXPORTS Stage
 +        {
 +            int first;
 +            int ntrees;
 +            float threshold;
 +        };
 +
 +        bool read(const FileNode &node);
 +
 +        bool isStumpBased;
 +
 +        int stageType;
 +        int featureType;
 +        int ncategories;
 +        Size origWinSize;
 +
 +        std::vector<Stage> stages;
 +        std::vector<DTree> classifiers;
 +        std::vector<DTreeNode> nodes;
 +        std::vector<float> leaves;
 +        std::vector<int> subsets;
 +    };
 +
 +    Data data;
 +    Ptr<FeatureEvaluator> featureEvaluator;
 +    Ptr<CvHaarClassifierCascade> oldCascade;
 +
 +public:
 +    class CV_EXPORTS MaskGenerator
 +    {
 +    public:
 +        virtual ~MaskGenerator() {}
 +        virtual cv::Mat generateMask(const cv::Mat& src)=0;
 +        virtual void initializeMask(const cv::Mat& /*src*/) {};
 +    };
 +    void setMaskGenerator(Ptr<MaskGenerator> maskGenerator);
 +    Ptr<MaskGenerator> getMaskGenerator();
 +
 +    void setFaceDetectionMaskGenerator();
 +
 +protected:
 +    Ptr<MaskGenerator> maskGenerator;
 +};
 +
 +//////////////// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector //////////////
 +
 +// struct for detection region of interest (ROI)
 +struct DetectionROI
 +{
 +   // scale(size) of the bounding box
 +   double scale;
 +   // set of requrested locations to be evaluated
 +   std::vector<cv::Point> locations;
 +   // vector that will contain confidence values for each location
 +   std::vector<double> confidences;
 +};
 +
 +struct CV_EXPORTS_W HOGDescriptor
 +{
 +public:
 +    enum { L2Hys = 0
 +         };
 +    enum { DEFAULT_NLEVELS = 64
 +         };
 +
 +    CV_WRAP HOGDescriptor() : winSize(64,128), blockSize(16,16), blockStride(8,8),
 +        cellSize(8,8), nbins(9), derivAperture(1), winSigma(-1),
 +        histogramNormType(HOGDescriptor::L2Hys), L2HysThreshold(0.2), gammaCorrection(true),
 +        nlevels(HOGDescriptor::DEFAULT_NLEVELS)
 +    {}
 +
 +    CV_WRAP HOGDescriptor(Size _winSize, Size _blockSize, Size _blockStride,
 +                  Size _cellSize, int _nbins, int _derivAperture=1, double _winSigma=-1,
 +                  int _histogramNormType=HOGDescriptor::L2Hys,
 +                  double _L2HysThreshold=0.2, bool _gammaCorrection=false,
 +                  int _nlevels=HOGDescriptor::DEFAULT_NLEVELS)
 +    : winSize(_winSize), blockSize(_blockSize), blockStride(_blockStride), cellSize(_cellSize),
 +    nbins(_nbins), derivAperture(_derivAperture), winSigma(_winSigma),
 +    histogramNormType(_histogramNormType), L2HysThreshold(_L2HysThreshold),
 +    gammaCorrection(_gammaCorrection), nlevels(_nlevels)
 +    {}
 +
 +    CV_WRAP HOGDescriptor(const String& filename)
 +    {
 +        load(filename);
 +    }
 +
 +    HOGDescriptor(const HOGDescriptor& d)
 +    {
 +        d.copyTo(*this);
 +    }
 +
 +    virtual ~HOGDescriptor() {}
 +
 +    CV_WRAP size_t getDescriptorSize() const;
 +    CV_WRAP bool checkDetectorSize() const;
 +    CV_WRAP double getWinSigma() const;
 +
 +    CV_WRAP virtual void setSVMDetector(InputArray _svmdetector);
 +
 +    virtual bool read(FileNode& fn);
 +    virtual void write(FileStorage& fs, const String& objname) const;
 +
 +    CV_WRAP virtual bool load(const String& filename, const String& objname = String());
 +    CV_WRAP virtual void save(const String& filename, const String& objname = String()) const;
 +    virtual void copyTo(HOGDescriptor& c) const;
 +
 +    CV_WRAP virtual void compute(const Mat& img,
 +                         CV_OUT std::vector<float>& descriptors,
 +                         Size winStride = Size(), Size padding = Size(),
 +                         const std::vector<Point>& locations = std::vector<Point>()) const;
 +    //with found weights output
 +    CV_WRAP virtual void detect(const Mat& img, CV_OUT std::vector<Point>& foundLocations,
 +                        CV_OUT std::vector<double>& weights,
 +                        double hitThreshold = 0, Size winStride = Size(),
 +                        Size padding = Size(),
 +                        const std::vector<Point>& searchLocations = std::vector<Point>()) const;
 +    //without found weights output
 +    virtual void detect(const Mat& img, CV_OUT std::vector<Point>& foundLocations,
 +                        double hitThreshold = 0, Size winStride = Size(),
 +                        Size padding = Size(),
 +                        const std::vector<Point>& searchLocations=std::vector<Point>()) const;
 +    //with result weights output
 +    CV_WRAP virtual void detectMultiScale(const Mat& img, CV_OUT std::vector<Rect>& foundLocations,
 +                                  CV_OUT std::vector<double>& foundWeights, double hitThreshold = 0,
 +                                  Size winStride = Size(), Size padding = Size(), double scale = 1.05,
 +                                  double finalThreshold = 2.0,bool useMeanshiftGrouping = false) const;
 +    //without found weights output
 +    virtual void detectMultiScale(const Mat& img, CV_OUT std::vector<Rect>& foundLocations,
 +                                  double hitThreshold = 0, Size winStride = Size(),
 +                                  Size padding = Size(), double scale = 1.05,
 +                                  double finalThreshold = 2.0, bool useMeanshiftGrouping = false) const;
 +
 +    CV_WRAP virtual void computeGradient(const Mat& img, CV_OUT Mat& grad, CV_OUT Mat& angleOfs,
 +                                 Size paddingTL = Size(), Size paddingBR = Size()) const;
 +
 +    CV_WRAP static std::vector<float> getDefaultPeopleDetector();
 +    CV_WRAP static std::vector<float> getDaimlerPeopleDetector();
 +
 +    CV_PROP Size winSize;
 +    CV_PROP Size blockSize;
 +    CV_PROP Size blockStride;
 +    CV_PROP Size cellSize;
 +    CV_PROP int nbins;
 +    CV_PROP int derivAperture;
 +    CV_PROP double winSigma;
 +    CV_PROP int histogramNormType;
 +    CV_PROP double L2HysThreshold;
 +    CV_PROP bool gammaCorrection;
 +    CV_PROP std::vector<float> svmDetector;
 +    CV_PROP int nlevels;
 +
 +
 +   // evaluate specified ROI and return confidence value for each location
 +   virtual void detectROI(const cv::Mat& img, const std::vector<cv::Point> &locations,
 +                                   CV_OUT std::vector<cv::Point>& foundLocations, CV_OUT std::vector<double>& confidences,
 +                                   double hitThreshold = 0, cv::Size winStride = Size(),
 +                                   cv::Size padding = Size()) const;
 +
 +   // evaluate specified ROI and return confidence value for each location in multiple scales
 +   virtual void detectMultiScaleROI(const cv::Mat& img,
 +                                                       CV_OUT std::vector<cv::Rect>& foundLocations,
 +                                                       std::vector<DetectionROI>& locations,
 +                                                       double hitThreshold = 0,
 +                                                       int groupThreshold = 0) const;
 +
 +   // read/parse Dalal's alt model file
 +   void readALTModel(String modelfile);
++   void groupRectangles(std::vector<cv::Rect>& rectList, std::vector<double>& weights, int groupThreshold, double eps) const;
 +};
 +
 +
 +CV_EXPORTS_W void findDataMatrix(InputArray image,
 +                                 CV_OUT std::vector<String>& codes,
 +                                 OutputArray corners = noArray(),
 +                                 OutputArrayOfArrays dmtx = noArray());
 +
 +CV_EXPORTS_W void drawDataMatrixCodes(InputOutputArray image,
 +                                      const std::vector<String>& codes,
 +                                      InputArray corners);
 +}
 +
 +#include "opencv2/objdetect/linemod.hpp"
 +#include "opencv2/objdetect/erfilter.hpp"
 +
 +#endif
@@@ -113,25 -114,7 +113,7 @@@ struct Logge
  namespace cv
  {
  
- // class for grouping object candidates, detected by Cascade Classifier, HOG etc.
- // instance of the class is to be passed to cv::partition (see cxoperations.hpp)
- class CV_EXPORTS SimilarRects
- {
- public:
-     SimilarRects(double _eps) : eps(_eps) {}
-     inline bool operator()(const Rect& r1, const Rect& r2) const
-     {
-         double delta = eps*(std::min(r1.width, r2.width) + std::min(r1.height, r2.height))*0.5;
-         return std::abs(r1.x - r2.x) <= delta &&
-         std::abs(r1.y - r2.y) <= delta &&
-         std::abs(r1.x + r1.width - r2.x - r2.width) <= delta &&
-         std::abs(r1.y + r1.height - r2.y - r2.height) <= delta;
-     }
-     double eps;
- };
 -void groupRectangles(vector<Rect>& rectList, int groupThreshold, double eps, vector<int>* weights, vector<double>* levelWeights)
 +void groupRectangles(std::vector<Rect>& rectList, int groupThreshold, double eps, std::vector<int>* weights, std::vector<double>* levelWeights)
  {
      if( groupThreshold <= 0 || rectList.empty() )
      {
@@@ -1301,72 -1055,24 +1301,72 @@@ void HOGDescriptor::detectMultiScale
      std::copy(tempWeights.begin(), tempWeights.end(), back_inserter(foundWeights));
  
      if ( useMeanshiftGrouping )
 -    {
          groupRectangles_meanshift(foundLocations, foundWeights, foundScales, finalThreshold, winSize);
 -    }
      else
-         groupRectangles(foundLocations, (int)finalThreshold, 0.2);
 -    {
+         groupRectangles(foundLocations, foundWeights, (int)finalThreshold, 0.2);
 -    }
  }
  
 -void HOGDescriptor::detectMultiScale(const Mat& img, vector<Rect>& foundLocations,
 -                                     double hitThreshold, Size winStride, Size padding,
 -                                     double scale0, double finalThreshold, bool useMeanshiftGrouping) const
 +void HOGDescriptor::detectMultiScale(const Mat& img, std::vector<Rect>& foundLocations,
 +    double hitThreshold, Size winStride, Size padding,
 +    double scale0, double finalThreshold, bool useMeanshiftGrouping) const
  {
 -    vector<double> foundWeights;
 +    std::vector<double> foundWeights;
      detectMultiScale(img, foundLocations, foundWeights, hitThreshold, winStride,
 -                     padding, scale0, finalThreshold, useMeanshiftGrouping);
 +                padding, scale0, finalThreshold, useMeanshiftGrouping);
  }
  
 +template<typename _ClsName> struct RTTIImpl
 +{
 +public:
 +    static int isInstance(const void* ptr)
 +    {
 +        static _ClsName dummy;
 +        static void* dummyp = &dummy;
 +        union
 +        {
 +            const void* p;
 +            const void** pp;
 +        } a, b;
 +        a.p = dummyp;
 +        b.p = ptr;
 +        return *a.pp == *b.pp;
 +    }
 +    static void release(void** dbptr)
 +    {
 +        if(dbptr && *dbptr)
 +        {
 +            delete (_ClsName*)*dbptr;
 +            *dbptr = 0;
 +        }
 +    }
 +    static void* read(CvFileStorage* fs, CvFileNode* n)
 +    {
 +        FileNode fn(fs, n);
 +        _ClsName* obj = new _ClsName;
 +        if(obj->read(fn))
 +            return obj;
 +        delete obj;
 +        return 0;
 +    }
 +
 +    static void write(CvFileStorage* _fs, const char* name, const void* ptr, CvAttrList)
 +    {
 +        if(ptr && _fs)
 +        {
 +            FileStorage fs(_fs);
 +            fs.fs.addref();
 +            ((const _ClsName*)ptr)->write(fs, String(name));
 +        }
 +    }
 +
 +    static void* clone(const void* ptr)
 +    {
 +        if(!ptr)
 +            return 0;
 +        return new _ClsName(*(const _ClsName*)ptr);
 +    }
 +};
 +
  typedef RTTIImpl<HOGDescriptor> HOGRTTI;
  
  CvType hog_type( CV_TYPE_NAME_HOG_DESCRIPTOR, HOGRTTI::isInstance,
@@@ -2684,265 -2389,327 +2684,343 @@@ std::vector<float> HOGDescriptor::getDa
          -0.025054f, -0.093026f, -0.035372f, -0.233209f,
          -0.049869f, -0.039151f, -0.022279f, -0.065380f,
          -9.063785f};
 -        return vector<float>(detector, detector + sizeof(detector)/sizeof(detector[0]));
 +    return std::vector<float>(detector, detector + sizeof(detector)/sizeof(detector[0]));
  }
  
 -class HOGConfInvoker : public ParallelLoopBody
 +class HOGConfInvoker :
 +    public ParallelLoopBody
  {
  public:
 -       HOGConfInvoker( const HOGDescriptor* _hog, const Mat& _img,
 -                               double _hitThreshold, Size _padding,
 -                               std::vector<DetectionROI>* locs,
 -                               std::vector<Rect>* _vec, Mutex* _mtx )
 -       {
 -               hog = _hog;
 -               img = _img;
 -               hitThreshold = _hitThreshold;
 -               padding = _padding;
 -               locations = locs;
 -               vec = _vec;
 -               mtx = _mtx;
 -       }
 -
 -       void operator()( const Range& range ) const
 -       {
 -               int i, i1 = range.start, i2 = range.end;
 -
 -               Size maxSz(cvCeil(img.cols/(*locations)[0].scale), cvCeil(img.rows/(*locations)[0].scale));
 -               Mat smallerImgBuf(maxSz, img.type());
 -               vector<Point> dets;
 -
 -               for( i = i1; i < i2; i++ )
 -               {
 -                       double scale = (*locations)[i].scale;
 -
 -                       Size sz(cvRound(img.cols / scale), cvRound(img.rows / scale));
 -                       Mat smallerImg(sz, img.type(), smallerImgBuf.data);
 -
 -                       if( sz == img.size() )
 -                               smallerImg = Mat(sz, img.type(), img.data, img.step);
 -                       else
 -                               resize(img, smallerImg, sz);
 -
 -                       hog->detectROI(smallerImg, (*locations)[i].locations, dets, (*locations)[i].confidences, hitThreshold, Size(), padding);
 -                       Size scaledWinSize = Size(cvRound(hog->winSize.width*scale), cvRound(hog->winSize.height*scale));
 -                       mtx->lock();
 -                       for( size_t j = 0; j < dets.size(); j++ )
 -                       {
 -                               vec->push_back(Rect(cvRound(dets[j].x*scale),
 -                                                                       cvRound(dets[j].y*scale),
 -                                                                       scaledWinSize.width, scaledWinSize.height));
 -                       }
 -                       mtx->unlock();
 -               }
 -       }
 -
 -       const HOGDescriptor* hog;
 -       Mat img;
 -       double hitThreshold;
 -       std::vector<DetectionROI>* locations;
 -       Size padding;
 -       std::vector<Rect>* vec;
 -       Mutex* mtx;
 +    HOGConfInvoker( const HOGDescriptor* _hog, const Mat& _img,
 +        double _hitThreshold, const Size& _padding,
 +        std::vector<DetectionROI>* locs,
 +        std::vector<Rect>* _vec, Mutex* _mtx )
 +    {
 +        hog = _hog;
 +        img = _img;
 +        hitThreshold = _hitThreshold;
 +        padding = _padding;
 +        locations = locs;
 +        vec = _vec;
 +        mtx = _mtx;
 +    }
 +
 +    void operator()( const Range& range ) const
 +    {
 +        int i, i1 = range.start, i2 = range.end;
 +
 +        Size maxSz(cvCeil(img.cols/(*locations)[0].scale), cvCeil(img.rows/(*locations)[0].scale));
 +        Mat smallerImgBuf(maxSz, img.type());
 +        std::vector<Point> dets;
 +
 +        for( i = i1; i < i2; i++ )
 +        {
 +            double scale = (*locations)[i].scale;
 +
 +            Size sz(cvRound(img.cols / scale), cvRound(img.rows / scale));
 +            Mat smallerImg(sz, img.type(), smallerImgBuf.data);
 +
 +            if( sz == img.size() )
 +                smallerImg = Mat(sz, img.type(), img.data, img.step);
 +            else
 +                resize(img, smallerImg, sz);
 +
 +            hog->detectROI(smallerImg, (*locations)[i].locations, dets, (*locations)[i].confidences, hitThreshold, Size(), padding);
 +            Size scaledWinSize = Size(cvRound(hog->winSize.width*scale), cvRound(hog->winSize.height*scale));
 +            mtx->lock();
 +            for( size_t j = 0; j < dets.size(); j++ )
 +                vec->push_back(Rect(cvRound(dets[j].x*scale),
 +                                    cvRound(dets[j].y*scale),
 +                                    scaledWinSize.width, scaledWinSize.height));
 +            mtx->unlock();
 +        }
 +    }
 +
 +    const HOGDescriptor* hog;
 +    Mat img;
 +    double hitThreshold;
 +    std::vector<DetectionROI>* locations;
 +    Size padding;
 +    std::vector<Rect>* vec;
 +    Mutex* mtx;
  };
  
 -void HOGDescriptor::detectROI(const cv::Mat& img, const vector<cv::Point> &locations,
 -                                       CV_OUT std::vector<cv::Point>& foundLocations, CV_OUT std::vector<double>& confidences,
 -                                       double hitThreshold, cv::Size winStride,
 -                                       cv::Size padding) const
 +void HOGDescriptor::detectROI(const cv::Mat& img, const std::vector<cv::Point> &locations,
 +    CV_OUT std::vector<cv::Point>& foundLocations, CV_OUT std::vector<double>& confidences,
 +    double hitThreshold, cv::Size winStride, cv::Size padding) const
  {
 -   foundLocations.clear();
 -
 -   confidences.clear();
 -
 -   if( svmDetector.empty() )
 -       return;
 -
 -   if( locations.empty() )
 -       return;
 -
 -   if( winStride == Size() )
 -       winStride = cellSize;
 -
 -   Size cacheStride(gcd(winStride.width, blockStride.width),
 -                                    gcd(winStride.height, blockStride.height));
 -
 -   size_t nwindows = locations.size();
 -   padding.width = (int)alignSize(std::max(padding.width, 0), cacheStride.width);
 -   padding.height = (int)alignSize(std::max(padding.height, 0), cacheStride.height);
 -   Size paddedImgSize(img.cols + padding.width*2, img.rows + padding.height*2);
 -
 -   // HOGCache cache(this, img, padding, padding, nwindows == 0, cacheStride);
 -   HOGCache cache(this, img, padding, padding, true, cacheStride);
 -   if( !nwindows )
 -           nwindows = cache.windowsInImage(paddedImgSize, winStride).area();
 -
 -   const HOGCache::BlockData* blockData = &cache.blockData[0];
 -
 -   int nblocks = cache.nblocks.area();
 -   int blockHistogramSize = cache.blockHistogramSize;
 -   size_t dsize = getDescriptorSize();
 -
 -   double rho = svmDetector.size() > dsize ? svmDetector[dsize] : 0;
 -   vector<float> blockHist(blockHistogramSize);
 -
 -   for( size_t i = 0; i < nwindows; i++ )
 -   {
 -           Point pt0;
 -           pt0 = locations[i];
 -           if( pt0.x < -padding.width || pt0.x > img.cols + padding.width - winSize.width ||
 -                   pt0.y < -padding.height || pt0.y > img.rows + padding.height - winSize.height )
 -           {
 -               // out of image
 -               confidences.push_back(-10.0);
 -               continue;
 -           }
 -
 -           double s = rho;
 -           const float* svmVec = &svmDetector[0];
 -           int j, k;
 -
 -           for( j = 0; j < nblocks; j++, svmVec += blockHistogramSize )
 -           {
 -                   const HOGCache::BlockData& bj = blockData[j];
 -                   Point pt = pt0 + bj.imgOffset;
 -                   // need to devide this into 4 parts!
 -                   const float* vec = cache.getBlock(pt, &blockHist[0]);
 -                   for( k = 0; k <= blockHistogramSize - 4; k += 4 )
 -                           s += vec[k]*svmVec[k] + vec[k+1]*svmVec[k+1] +
 -                                   vec[k+2]*svmVec[k+2] + vec[k+3]*svmVec[k+3];
 -                   for( ; k < blockHistogramSize; k++ )
 -                           s += vec[k]*svmVec[k];
 -           }
 -           // cv::waitKey();
 -           confidences.push_back(s);
 -
 -           if( s >= hitThreshold )
 -                   foundLocations.push_back(pt0);
 -   }
 - }
 +    foundLocations.clear();
 +    confidences.clear();
 +
 +    if( svmDetector.empty() || locations.empty())
 +        return;
 +
 +    if( winStride == Size() )
 +        winStride = cellSize;
 +    Size cacheStride(gcd(winStride.width, blockStride.width),
 +                     gcd(winStride.height, blockStride.height));
 +
 +    size_t nwindows = locations.size();
 +    padding.width = (int)alignSize(std::max(padding.width, 0), cacheStride.width);
 +    padding.height = (int)alignSize(std::max(padding.height, 0), cacheStride.height);
 +    Size paddedImgSize(img.cols + padding.width*2, img.rows + padding.height*2);
 +
 +    // HOGCache cache(this, img, padding, padding, nwindows == 0, cacheStride);
 +    HOGCache cache(this, img, padding, padding, true, cacheStride);
 +    if( !nwindows )
 +        nwindows = cache.windowsInImage(paddedImgSize, winStride).area();
 +
 +    const HOGCache::BlockData* blockData = &cache.blockData[0];
 +
 +    int nblocks = cache.nblocks.area();
 +    int blockHistogramSize = cache.blockHistogramSize;
 +    size_t dsize = getDescriptorSize();
 +
 +    double rho = svmDetector.size() > dsize ? svmDetector[dsize] : 0;
 +    std::vector<float> blockHist(blockHistogramSize);
 +
 +#if CV_SSE2
 +    float partSum[4];
 +#endif
 +
 +    for( size_t i = 0; i < nwindows; i++ )
 +    {
 +        Point pt0;
 +        pt0 = locations[i];
 +        if( pt0.x < -padding.width || pt0.x > img.cols + padding.width - winSize.width ||
 +                pt0.y < -padding.height || pt0.y > img.rows + padding.height - winSize.height )
 +        {
 +            // out of image
 +            confidences.push_back(-10.0);
 +            continue;
 +        }
 +
 +        double s = rho;
 +        const float* svmVec = &svmDetector[0];
 +        int j, k;
 +
 +        for( j = 0; j < nblocks; j++, svmVec += blockHistogramSize )
 +        {
 +            const HOGCache::BlockData& bj = blockData[j];
 +            Point pt = pt0 + bj.imgOffset;
 +
 +            // need to devide this into 4 parts!
 +            const float* vec = cache.getBlock(pt, &blockHist[0]);
 +#if CV_SSE2
 +            __m128 _vec = _mm_loadu_ps(vec);
 +            __m128 _svmVec = _mm_loadu_ps(svmVec);
 +            __m128 sum = _mm_mul_ps(_svmVec, _vec);
 +
 +            for( k = 4; k <= blockHistogramSize - 4; k += 4 )
 +            {
 +                _vec = _mm_loadu_ps(vec + k);
 +                _svmVec = _mm_loadu_ps(svmVec + k);
 +
 +                sum = _mm_add_ps(sum, _mm_mul_ps(_vec, _svmVec));
 +            }
 +
 +            _mm_storeu_ps(partSum, sum);
 +            double t0 = partSum[0] + partSum[1];
 +            double t1 = partSum[2] + partSum[3];
 +            s += t0 + t1;
 +#else
 +            for( k = 0; k <= blockHistogramSize - 4; k += 4 )
 +                s += vec[k]*svmVec[k] + vec[k+1]*svmVec[k+1] +
 +                        vec[k+2]*svmVec[k+2] + vec[k+3]*svmVec[k+3];
 +#endif
 +            for( ; k < blockHistogramSize; k++ )
 +                s += vec[k]*svmVec[k];
 +        }
 +        confidences.push_back(s);
 +
 +        if( s >= hitThreshold )
 +            foundLocations.push_back(pt0);
 +    }
 +}
  
  void HOGDescriptor::detectMultiScaleROI(const cv::Mat& img,
 -                                                           CV_OUT std::vector<cv::Rect>& foundLocations,
 -                                                           std::vector<DetectionROI>& locations,
 -                                                           double hitThreshold,
 -                                                           int groupThreshold) const
 +    CV_OUT std::vector<cv::Rect>& foundLocations, std::vector<DetectionROI>& locations,
 +    double hitThreshold, int groupThreshold) const
  {
 -   std::vector<Rect> allCandidates;
 -   Mutex mtx;
 +    std::vector<Rect> allCandidates;
 +    Mutex mtx;
  
 -   parallel_for_(Range(0, (int)locations.size()),
 -                        HOGConfInvoker(this, img, hitThreshold, Size(8, 8), &locations, &allCandidates, &mtx));
 +    parallel_for_(Range(0, (int)locations.size()),
 +                  HOGConfInvoker(this, img, hitThreshold, Size(8, 8),
 +                                 &locations, &allCandidates, &mtx));
  
 -   foundLocations.resize(allCandidates.size());
 -   std::copy(allCandidates.begin(), allCandidates.end(), foundLocations.begin());
 -   cv::groupRectangles(foundLocations, groupThreshold, 0.2);
 +    foundLocations.resize(allCandidates.size());
 +    std::copy(allCandidates.begin(), allCandidates.end(), foundLocations.begin());
 +    cv::groupRectangles(foundLocations, groupThreshold, 0.2);
  }
  
 -void HOGDescriptor::readALTModel(std::string modelfile)
 +void HOGDescriptor::readALTModel(String modelfile)
  {
 -   // read model from SVMlight format..
 -   FILE *modelfl;
 -   if ((modelfl = fopen(modelfile.c_str(), "rb")) == NULL)
 -   {
 -       std::string eerr("file not exist");
 -       std::string efile(__FILE__);
 -       std::string efunc(__FUNCTION__);
 -       throw Exception(CV_StsError, eerr, efile, efunc, __LINE__);
 -   }
 -   char version_buffer[10];
 -   if (!fread (&version_buffer,sizeof(char),10,modelfl))
 -   {
 -       std::string eerr("version?");
 -       std::string efile(__FILE__);
 -       std::string efunc(__FUNCTION__);
 -       throw Exception(CV_StsError, eerr, efile, efunc, __LINE__);
 -   }
 -   if(strcmp(version_buffer,"V6.01")) {
 -       std::string eerr("version doesnot match");
 -       std::string efile(__FILE__);
 -       std::string efunc(__FUNCTION__);
 -       throw Exception(CV_StsError, eerr, efile, efunc, __LINE__);
 -   }
 -   /* read version number */
 -   int version = 0;
 -   if (!fread (&version,sizeof(int),1,modelfl))
 -   { throw Exception(); }
 -   if (version < 200)
 -   {
 -       std::string eerr("version doesnot match");
 -       std::string efile(__FILE__);
 -       std::string efunc(__FUNCTION__);
 -       throw Exception();
 -   }
 -   int kernel_type;
 -   size_t nread;
 -   nread=fread(&(kernel_type),sizeof(int),1,modelfl);
 -
 -   {// ignore these
 -       int poly_degree;
 -       nread=fread(&(poly_degree),sizeof(int),1,modelfl);
 -
 -       double rbf_gamma;
 -       nread=fread(&(rbf_gamma),sizeof(double), 1, modelfl);
 -       double coef_lin;
 -       nread=fread(&(coef_lin),sizeof(double),1,modelfl);
 -       double coef_const;
 -       nread=fread(&(coef_const),sizeof(double),1,modelfl);
 -       int l;
 -       nread=fread(&l,sizeof(int),1,modelfl);
 -       char* custom = new char[l];
 -       nread=fread(custom,sizeof(char),l,modelfl);
 -       delete[] custom;
 -   }
 -   int totwords;
 -   nread=fread(&(totwords),sizeof(int),1,modelfl);
 -   {// ignore these
 -       int totdoc;
 -       nread=fread(&(totdoc),sizeof(int),1,modelfl);
 -       int sv_num;
 -       nread=fread(&(sv_num), sizeof(int),1,modelfl);
 -   }
 -
 -   double linearbias;
 -   nread=fread(&linearbias, sizeof(double), 1, modelfl);
 -
 -   std::vector<float> detector;
 -   detector.clear();
 -   if(kernel_type == 0) { /* linear kernel */
 -       /* save linear wts also */
 -       double *linearwt = new double[totwords+1];
 -       int length = totwords;
 -       nread = fread(linearwt, sizeof(double), totwords + 1, modelfl);
 -       if(nread != static_cast<size_t>(length) + 1)
 -           throw Exception();
 -
 -       for(int i = 0; i < length; i++)
 -           detector.push_back((float)linearwt[i]);
 -
 -       detector.push_back((float)-linearbias);
 -       setSVMDetector(detector);
 -       delete [] linearwt;
 -   } else {
 -       throw Exception();
 -   }
 -   fclose(modelfl);
 +    // read model from SVMlight format..
 +    FILE *modelfl;
 +    if ((modelfl = fopen(modelfile.c_str(), "rb")) == NULL)
 +    {
 +        String eerr("file not exist");
 +        String efile(__FILE__);
 +        String efunc(__FUNCTION__);
 +        throw Exception(Error::StsError, eerr, efile, efunc, __LINE__);
 +    }
 +    char version_buffer[10];
 +    if (!fread (&version_buffer,sizeof(char),10,modelfl))
 +    {
 +        String eerr("version?");
 +        String efile(__FILE__);
 +        String efunc(__FUNCTION__);
 +        throw Exception(Error::StsError, eerr, efile, efunc, __LINE__);
 +    }
 +    if(strcmp(version_buffer,"V6.01")) {
 +        String eerr("version doesnot match");
 +        String efile(__FILE__);
 +        String efunc(__FUNCTION__);
 +        throw Exception(Error::StsError, eerr, efile, efunc, __LINE__);
 +    }
 +    /* read version number */
 +    int version = 0;
 +    if (!fread (&version,sizeof(int),1,modelfl))
 +    { throw Exception(); }
 +    if (version < 200)
 +    {
 +        String eerr("version doesnot match");
 +        String efile(__FILE__);
 +        String efunc(__FUNCTION__);
 +        throw Exception();
 +    }
 +    int kernel_type;
 +    size_t nread;
 +    nread=fread(&(kernel_type),sizeof(int),1,modelfl);
 +
 +    {// ignore these
 +        int poly_degree;
 +        nread=fread(&(poly_degree),sizeof(int),1,modelfl);
 +
 +        double rbf_gamma;
 +        nread=fread(&(rbf_gamma),sizeof(double), 1, modelfl);
 +        double coef_lin;
 +        nread=fread(&(coef_lin),sizeof(double),1,modelfl);
 +        double coef_const;
 +        nread=fread(&(coef_const),sizeof(double),1,modelfl);
 +        int l;
 +        nread=fread(&l,sizeof(int),1,modelfl);
 +        char* custom = new char[l];
 +        nread=fread(custom,sizeof(char),l,modelfl);
 +        delete[] custom;
 +    }
 +    int totwords;
 +    nread=fread(&(totwords),sizeof(int),1,modelfl);
 +    {// ignore these
 +        int totdoc;
 +        nread=fread(&(totdoc),sizeof(int),1,modelfl);
 +        int sv_num;
 +        nread=fread(&(sv_num), sizeof(int),1,modelfl);
 +    }
 +
 +    double linearbias;
 +    nread=fread(&linearbias, sizeof(double), 1, modelfl);
 +
 +    std::vector<float> detector;
 +    detector.clear();
 +    if(kernel_type == 0) { /* linear kernel */
 +        /* save linear wts also */
 +        double *linearwt = new double[totwords+1];
 +        int length = totwords;
 +        nread = fread(linearwt, sizeof(double), totwords + 1, modelfl);
 +        if(nread != static_cast<size_t>(length) + 1)
 +            throw Exception();
 +
 +        for(int i = 0; i < length; i++)
 +            detector.push_back((float)linearwt[i]);
 +
 +        detector.push_back((float)-linearbias);
 +        setSVMDetector(detector);
 +        delete [] linearwt;
 +    } else {
 +        throw Exception();
 +    }
 +    fclose(modelfl);
  }
  
 -void HOGDescriptor::groupRectangles(vector<cv::Rect>& rectList, vector<double>& weights, int groupThreshold, double eps) const
++void HOGDescriptor::groupRectangles(std::vector<cv::Rect>& rectList, std::vector<double>& weights, int groupThreshold, double eps) const
+ {
+     if( groupThreshold <= 0 || rectList.empty() )
+     {
+         return;
+     }
+     CV_Assert(rectList.size() == weights.size());
 -    vector<int> labels;
++    std::vector<int> labels;
+     int nclasses = partition(rectList, labels, SimilarRects(eps));
 -    vector<cv::Rect_<double> > rrects(nclasses);
 -    vector<int> numInClass(nclasses, 0);
 -    vector<double> foundWeights(nclasses, DBL_MIN);
 -    vector<double> totalFactorsPerClass(nclasses, 1);
++    std::vector<cv::Rect_<double> > rrects(nclasses);
++    std::vector<int> numInClass(nclasses, 0);
++    std::vector<double> foundWeights(nclasses, DBL_MIN);
++    std::vector<double> totalFactorsPerClass(nclasses, 1);
+     int i, j, nlabels = (int)labels.size();
+     for( i = 0; i < nlabels; i++ )
+     {
+         int cls = labels[i];
+         rrects[cls].x += rectList[i].x;
+         rrects[cls].y += rectList[i].y;
+         rrects[cls].width += rectList[i].width;
+         rrects[cls].height += rectList[i].height;
+         foundWeights[cls] = max(foundWeights[cls], weights[i]);
+         numInClass[cls]++;
+     }
+     for( i = 0; i < nclasses; i++ )
+     {
+         // find the average of all ROI in the cluster
+         cv::Rect_<double> r = rrects[i];
+         double s = 1.0/numInClass[i];
+         rrects[i] = cv::Rect_<double>(cv::saturate_cast<double>(r.x*s),
+             cv::saturate_cast<double>(r.y*s),
+             cv::saturate_cast<double>(r.width*s),
+             cv::saturate_cast<double>(r.height*s));
+     }
+     rectList.clear();
+     weights.clear();
+     for( i = 0; i < nclasses; i++ )
+     {
+         cv::Rect r1 = rrects[i];
+         int n1 = numInClass[i];
+         double w1 = foundWeights[i];
+         if( n1 <= groupThreshold )
+             continue;
+         // filter out small rectangles inside large rectangles
+         for( j = 0; j < nclasses; j++ )
+         {
+             int n2 = numInClass[j];
+             if( j == i || n2 <= groupThreshold )
+                 continue;
+             cv::Rect r2 = rrects[j];
+             int dx = cv::saturate_cast<int>( r2.width * eps );
+             int dy = cv::saturate_cast<int>( r2.height * eps );
+             if( r1.x >= r2.x - dx &&
+                 r1.y >= r2.y - dy &&
+                 r1.x + r1.width <= r2.x + r2.width + dx &&
+                 r1.y + r1.height <= r2.y + r2.height + dy &&
+                 (n2 > std::max(3, n1) || n1 < 3) )
+                 break;
+         }
+         if( j == nclasses )
+         {
+             rectList.push_back(r1);
+             weights.push_back(w1);
+         }
+     }
+ }
  }
 +
Simple merge
@@@ -12,16 -12,23 +12,20 @@@ Cascade classifier class used for objec
      class CV_EXPORTS OclCascadeClassifier : public CascadeClassifier
      {
      public:
 -          OclCascadeClassifier() {};
 -          ~OclCascadeClassifier() {};
 -           CvSeq *oclHaarDetectObjects(oclMat &gimg, CvMemStorage *storage,
 -                                      double scaleFactor,int minNeighbors,
 -                                      int flags, CvSize minSize = cvSize(0, 0),
 -                                      CvSize maxSize = cvSize(0, 0));
 +            void detectMultiScale(oclMat &image, CV_OUT std::vector<cv::Rect>& faces,
 +                                              double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0,
 +                                              Size minSize = Size(), Size maxSize = Size());
      };
  
+ .. Sample code::
+    * : OCL : A face detection example using cascade classifiers can be found at opencv_source_code/samples/ocl/facedetect.cpp
  ocl::OclCascadeClassifier::oclHaarDetectObjects
  ------------------------------------------------------
 -Returns the detected objects by a list of rectangles
 +Detects objects of different sizes in the input image.
  
 -.. ocv:function:: CvSeq* ocl::OclCascadeClassifier::oclHaarDetectObjects(oclMat &gimg, CvMemStorage *storage, double scaleFactor,int minNeighbors, int flags, CvSize minSize = cvSize(0, 0), CvSize maxSize = cvSize(0, 0))
 +.. ocv:function:: void ocl::OclCascadeClassifier::detectMultiScale(oclMat &image, std::vector<cv::Rect>& faces, double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0, Size minSize = Size(), Size maxSize = Size())
  
      :param image:  Matrix of type CV_8U containing an image where objects should be detected.
  
@@@ -180,8 -88,8 +88,8 @@@ namespace c
                                        int nblocks_win_x, int nblocks_win_y);
  
                  void compute_hists(int nbins, int block_stride_x, int blovck_stride_y,
-                                    int height, int width, float sigma, const cv::ocl::oclMat &grad,
+                                    int height, int width, const cv::ocl::oclMat &grad,
 -                                   const cv::ocl::oclMat &qangle, 
 +                                   const cv::ocl::oclMat &qangle,
                                     const cv::ocl::oclMat &gauss_w_lut, cv::ocl::oclMat &block_hists);
  
                  void normalize_hists(int nbins, int block_stride_x, int block_stride_y,
@@@ -357,10 -273,10 +273,10 @@@ void cv::ocl::HOGDescriptor::computeBlo
  {
      computeGradient(img, this->grad, this->qangle);
  
 -    hog::compute_hists(nbins, block_stride.width, block_stride.height, effect_size.height, 
 +    hog::compute_hists(nbins, block_stride.width, block_stride.height, effect_size.height,
-         effect_size.width, (float)getWinSigma(), grad, qangle, gauss_w_lut, block_hists);
+         effect_size.width, grad, qangle, gauss_w_lut, block_hists);
  
 -    hog::normalize_hists(nbins, block_stride.width, block_stride.height, effect_size.height, 
 +    hog::normalize_hists(nbins, block_stride.width, block_stride.height, effect_size.height,
          effect_size.width, block_hists, (float)threshold_L2hys);
  }
  
@@@ -1705,64 -1622,70 +1621,68 @@@ void cv::ocl::device::hog::set_up_const
      cdescr_size = descr_size;
  }
  
 -void cv::ocl::device::hog::compute_hists(int nbins, 
 +void cv::ocl::device::hog::compute_hists(int nbins,
                                           int block_stride_x, int block_stride_y,
-                                          int height, int width, float sigma,
 -                                         int height, int width, 
 -                                         const cv::ocl::oclMat &grad, 
 -                                         const cv::ocl::oclMat &qangle, 
 -                                         const cv::ocl::oclMat &gauss_w_lut, 
++                                         int height, int width,
 +                                         const cv::ocl::oclMat &grad,
 +                                         const cv::ocl::oclMat &qangle,
 +                                         const cv::ocl::oclMat &gauss_w_lut,
                                           cv::ocl::oclMat &block_hists)
  {
      Context *clCxt = Context::getContext();
 -    vector< pair<size_t, const void *> > args;
 -    string kernelName = "compute_hists_lut_kernel";
 +    std::vector< std::pair<size_t, const void *> > args;
-     String kernelName = (sigma == 4.0f) ? "compute_hists_lut_kernel" :
-         "compute_hists_kernel";
++    String kernelName = "compute_hists_lut_kernel";
  
 -    int img_block_width = (width - CELLS_PER_BLOCK_X * CELL_WIDTH + block_stride_x) 
 +    int img_block_width = (width - CELLS_PER_BLOCK_X * CELL_WIDTH + block_stride_x)
          / block_stride_x;
 -    int img_block_height = (height - CELLS_PER_BLOCK_Y * CELL_HEIGHT + block_stride_y) 
 +    int img_block_height = (height - CELLS_PER_BLOCK_Y * CELL_HEIGHT + block_stride_y)
          / block_stride_y;
 -    int blocks_total = img_block_width * img_block_height;
  
      int grad_quadstep = grad.step >> 2;
      int qangle_step = qangle.step;
  
-     // Precompute gaussian spatial window parameter
-     float scale = 1.f / (2.f * sigma * sigma);
      int blocks_in_group = 4;
      size_t localThreads[3] = { blocks_in_group * 24, 2, 1 };
 -    size_t globalThreads[3] = { 
 +    size_t globalThreads[3] = {
          divUp(img_block_width * img_block_height, blocks_in_group) * localThreads[0], 2, 1 };
  
      int hists_size = (nbins * CELLS_PER_BLOCK_X * CELLS_PER_BLOCK_Y * 12) * sizeof(float);
      int final_hists_size = (nbins * CELLS_PER_BLOCK_X * CELLS_PER_BLOCK_Y) * sizeof(float);
 -    int smem = (hists_size + final_hists_size) * blocks_in_group;
 -
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&cblock_stride_x));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&cblock_stride_y));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&cnbins));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&cblock_hist_size));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&img_block_width));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&blocks_in_group));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&blocks_total));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&grad_quadstep));
 -    args.push_back( make_pair( sizeof(cl_int), (void *)&qangle_step));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&grad.data));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&qangle.data));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&gauss_w_lut.data));
 -    args.push_back( make_pair( sizeof(cl_mem), (void *)&block_hists.data));
 -    args.push_back( make_pair( smem, (void *)NULL));
 +    int smem = hists_size + final_hists_size;
 +
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&width));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&cblock_stride_x));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&cblock_stride_y));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&cnbins));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&cblock_hist_size));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&img_block_width));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&grad_quadstep));
 +    args.push_back( std::make_pair( sizeof(cl_int), (void *)&qangle_step));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&grad.data));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&qangle.data));
-     if (kernelName.compare("compute_hists_lut_kernel") == 0)
-         args.push_back( std::make_pair( sizeof(cl_mem), (void *)&gauss_w_lut.data));
-     else
-         args.push_back( std::make_pair( sizeof(cl_float), (void *)&scale));
++    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&gauss_w_lut.data));
 +    args.push_back( std::make_pair( sizeof(cl_mem), (void *)&block_hists.data));
 +    args.push_back( std::make_pair( smem, (void *)NULL));
  
-     openCLExecuteKernel2(clCxt, &objdetect_hog, kernelName, globalThreads,
-         localThreads, args, -1, -1);
+     if(hog_device_cpu)
+     {
 -        openCLExecuteKernel(clCxt, &objdetect_hog, kernelName, globalThreads, 
++        openCLExecuteKernel2(clCxt, &objdetect_hog, kernelName, globalThreads,
+             localThreads, args, -1, -1, "-D CPU");
+     }else
+     {
+         cl_kernel kernel = openCLGetKernelFromSource(clCxt, &objdetect_hog, kernelName);
+         int wave_size = queryDeviceInfo<WAVEFRONT_SIZE, int>(kernel);
+         char opt[32] = {0};
+         sprintf(opt, "-D WAVE_SIZE=%d", wave_size);
 -        openCLExecuteKernel(clCxt, &objdetect_hog, kernelName, globalThreads, 
++        openCLExecuteKernel2(clCxt, &objdetect_hog, kernelName, globalThreads,
+             localThreads, args, -1, -1, opt);
+     }
  }
  
 -void cv::ocl::device::hog::normalize_hists(int nbins, 
 +void cv::ocl::device::hog::normalize_hists(int nbins,
                                             int block_stride_x, int block_stride_y,
 -                                           int height, int width, 
 -                                           cv::ocl::oclMat &block_hists, 
 +                                           int height, int width,
 +                                           cv::ocl::oclMat &block_hists,
                                             float threshold)
  {
      Context *clCxt = Context::getContext();
  //----------------------------------------------------------------------------
  // Histogram computation
  // 12 threads for a cell, 12x4 threads per block
- // Use pre-computed gaussian and interp_weight lookup tables if sigma is 4.0f
+ // Use pre-computed gaussian and interp_weight lookup tables
  __kernel void compute_hists_lut_kernel(
      const int cblock_stride_x, const int cblock_stride_y,
--    const int cnbins, const int cblock_hist_size, const int img_block_width, 
++    const int cnbins, const int cblock_hist_size, const int img_block_width,
      const int blocks_in_group, const int blocks_total,
      const int grad_quadstep, const int qangle_step,
      __global const float* grad, __global const uchar* qangle,
      const int cell_y = lidY;
      const int cell_thread_x = lidX - cell_x * 12;
  
--    __local float* hists = smem + lp * cnbins * (CELLS_PER_BLOCK_X * 
-         CELLS_PER_BLOCK_Y * 12 + CELLS_PER_BLOCK_X * CELLS_PER_BLOCK_Y);
-     __local float* final_hist = hists + cnbins * 
-         (CELLS_PER_BLOCK_X * CELLS_PER_BLOCK_Y * 12);
-     const int offset_x = gidX * cblock_stride_x + (cell_x << 2) + cell_thread_x;
-     const int offset_y = gidY * cblock_stride_y + (cell_y << 2);
-     __global const float* grad_ptr = (gid < blocks_total) ? 
-         grad + offset_y * grad_quadstep + (offset_x << 1) : grad;
-     __global const uchar* qangle_ptr = (gid < blocks_total) ?
-         qangle + offset_y * qangle_step + (offset_x << 1) : qangle;
-     __local float* hist = hists + 12 * (cell_y * CELLS_PER_BLOCK_Y + cell_x) + 
-         cell_thread_x;
-     for (int bin_id = 0; bin_id < cnbins; ++bin_id)
-         hist[bin_id * 48] = 0.f;
-     const int dist_x = -4 + cell_thread_x - 4 * cell_x;
-     const int dist_center_x = dist_x - 4 * (1 - 2 * cell_x);
-     const int dist_y_begin = -4 - 4 * lidY;
-     for (int dist_y = dist_y_begin; dist_y < dist_y_begin + 12; ++dist_y)
-     {
-         float2 vote = (float2) (grad_ptr[0], grad_ptr[1]);
-         uchar2 bin = (uchar2) (qangle_ptr[0], qangle_ptr[1]);
-         grad_ptr += grad_quadstep;
-         qangle_ptr += qangle_step;
-         int dist_center_y = dist_y - 4 * (1 - 2 * cell_y);
-         int idx = (dist_center_y + 8) * 16 + (dist_center_x + 8);
-         float gaussian = gauss_w_lut[idx];
-         idx = (dist_y + 8) * 16 + (dist_x + 8);
-         float interp_weight = gauss_w_lut[256+idx];
-         hist[bin.x * 48] += gaussian * interp_weight * vote.x;
-         hist[bin.y * 48] += gaussian * interp_weight * vote.y;
-     }
-     barrier(CLK_LOCAL_MEM_FENCE);
-     volatile __local float* hist_ = hist;
-     for (int bin_id = 0; bin_id < cnbins; ++bin_id, hist_ += 48)
-     {
-         if (cell_thread_x < 6)
-             hist_[0] += hist_[6];
-         barrier(CLK_LOCAL_MEM_FENCE);
-         if (cell_thread_x < 3)
-             hist_[0] += hist_[3];
- #ifdef CPU
-         barrier(CLK_LOCAL_MEM_FENCE);
- #endif
-         if (cell_thread_x == 0)
-             final_hist[(cell_x * 2 + cell_y) * cnbins + bin_id] = 
-                 hist_[0] + hist_[1] + hist_[2];
-     }
- #ifdef CPU
-     barrier(CLK_LOCAL_MEM_FENCE);
- #endif
-     int tid = (cell_y * CELLS_PER_BLOCK_Y + cell_x) * 12 + cell_thread_x;
-     if ((tid < cblock_hist_size) && (gid < blocks_total))
-     {
-         __global float* block_hist = block_hists + 
-             (gidY * img_block_width + gidX) * cblock_hist_size;
-         block_hist[tid] = final_hist[tid];
-     }
- }
- //----------------------------------------------------------------------------
- // Histogram computation
- // 12 threads for a cell, 12x4 threads per block
- __kernel void compute_hists_kernel(
-     const int cblock_stride_x, const int cblock_stride_y,
-     const int cnbins, const int cblock_hist_size, const int img_block_width,
-     const int blocks_in_group, const int blocks_total,
-     const int grad_quadstep, const int qangle_step,
-     __global const float* grad, __global const uchar* qangle,
-     const float scale, __global float* block_hists, __local float* smem)
- {
-     const int lx = get_local_id(0);
-     const int lp = lx / 24; /* local group id */
-     const int gid = get_group_id(0) * blocks_in_group + lp;/* global group id */
-     const int gidY = gid / img_block_width;
-     const int gidX = gid - gidY * img_block_width;
-     const int lidX = lx - lp * 24;
-     const int lidY = get_local_id(1);
-     const int cell_x = lidX / 12;
-     const int cell_y = lidY;
-     const int cell_thread_x = lidX - cell_x * 12;
 +    __local float* hists = smem + lp * cnbins * (CELLS_PER_BLOCK_X *
          CELLS_PER_BLOCK_Y * 12 + CELLS_PER_BLOCK_X * CELLS_PER_BLOCK_Y);
 -    __local float* final_hist = hists + cnbins * 
 +    __local float* final_hist = hists + cnbins *
          (CELLS_PER_BLOCK_X * CELLS_PER_BLOCK_Y * 12);
  
      const int offset_x = gidX * cblock_stride_x + (cell_x << 2) + cell_thread_x;
  //-------------------------------------------------------------
  //  Normalization of histograms via L2Hys_norm
  //  optimized for the case of 9 bins
--__kernel void normalize_hists_36_kernel(__global float* block_hists, 
++__kernel void normalize_hists_36_kernel(__global float* block_hists,
                                          const float threshold, __local float *squares)
  {
      const int tid = get_local_id(0);
@@@ -298,24 -205,24 +205,24 @@@ float reduce_smem(volatile __local floa
      unsigned int tid = get_local_id(0);
      float sum = smem[tid];
  
--    if (size >= 512) { if (tid < 256) smem[tid] = sum = sum + smem[tid + 256]; 
++    if (size >= 512) { if (tid < 256) smem[tid] = sum = sum + smem[tid + 256];
          barrier(CLK_LOCAL_MEM_FENCE); }
--    if (size >= 256) { if (tid < 128) smem[tid] = sum = sum + smem[tid + 128]; 
++    if (size >= 256) { if (tid < 128) smem[tid] = sum = sum + smem[tid + 128];
          barrier(CLK_LOCAL_MEM_FENCE); }
--    if (size >= 128) { if (tid < 64) smem[tid] = sum = sum + smem[tid + 64]; 
++    if (size >= 128) { if (tid < 64) smem[tid] = sum = sum + smem[tid + 64];
          barrier(CLK_LOCAL_MEM_FENCE); }
  #ifdef CPU
--    if (size >= 64) { if (tid < 32) smem[tid] = sum = sum + smem[tid + 32]; 
++    if (size >= 64) { if (tid < 32) smem[tid] = sum = sum + smem[tid + 32];
          barrier(CLK_LOCAL_MEM_FENCE); }
--    if (size >= 32) { if (tid < 16) smem[tid] = sum = sum + smem[tid + 16]; 
--        barrier(CLK_LOCAL_MEM_FENCE); }       
--    if (size >= 16) { if (tid < 8) smem[tid] = sum = sum + smem[tid + 8]; 
++    if (size >= 32) { if (tid < 16) smem[tid] = sum = sum + smem[tid + 16];
          barrier(CLK_LOCAL_MEM_FENCE); }
--    if (size >= 8) { if (tid < 4) smem[tid] = sum = sum + smem[tid + 4]; 
++    if (size >= 16) { if (tid < 8) smem[tid] = sum = sum + smem[tid + 8];
          barrier(CLK_LOCAL_MEM_FENCE); }
--    if (size >= 4) { if (tid < 2) smem[tid] = sum = sum + smem[tid + 2]; 
--        barrier(CLK_LOCAL_MEM_FENCE); }               
--    if (size >= 2) { if (tid < 1) smem[tid] = sum = sum + smem[tid + 1]; 
++    if (size >= 8) { if (tid < 4) smem[tid] = sum = sum + smem[tid + 4];
++        barrier(CLK_LOCAL_MEM_FENCE); }
++    if (size >= 4) { if (tid < 2) smem[tid] = sum = sum + smem[tid + 2];
++        barrier(CLK_LOCAL_MEM_FENCE); }
++    if (size >= 2) { if (tid < 1) smem[tid] = sum = sum + smem[tid + 1];
          barrier(CLK_LOCAL_MEM_FENCE); }
  #else
      if (tid < 32)
@@@ -344,7 -251,7 +251,7 @@@ __kernel void normalize_hists_kernel
      const int gidX = get_group_id(0);
      const int gidY = get_group_id(1);
  
--    __global float* hist = block_hists + (gidY * img_block_width + gidX) * 
++    __global float* hist = block_hists + (gidY * img_block_width + gidX) *
          block_hist_size + tid;
  
      float elem = 0.f;
@@@ -385,14 -292,14 +292,14 @@@ __kernel void classify_hists_180_kernel
      const int gidX = get_group_id(0);
      const int gidY = get_group_id(1);
  
--    __global const float* hist = block_hists + (gidY * win_block_stride_y * 
++    __global const float* hist = block_hists + (gidY * win_block_stride_y *
          img_block_width + gidX * win_block_stride_x) * cblock_hist_size;
  
      float product = 0.f;
  
      for (int i = 0; i < cdescr_height; i++)
      {
--        product += coefs[i * cdescr_width + tid] * 
++        product += coefs[i * cdescr_width + tid] *
              hist[i * img_block_width * cblock_hist_size + tid];
      }
  
@@@ -458,14 -365,14 +365,14 @@@ __kernel void classify_hists_252_kernel
      const int gidX = get_group_id(0);
      const int gidY = get_group_id(1);
  
--    __global const float* hist = block_hists + (gidY * win_block_stride_y * 
++    __global const float* hist = block_hists + (gidY * win_block_stride_y *
          img_block_width + gidX * win_block_stride_x) * cblock_hist_size;
  
      float product = 0.f;
      if (tid < cdescr_width)
      {
          for (int i = 0; i < cdescr_height; i++)
--            product += coefs[i * cdescr_width + tid] * 
++            product += coefs[i * cdescr_width + tid] *
                  hist[i * img_block_width * cblock_hist_size + tid];
      }
  
        barrier(CLK_LOCAL_MEM_FENCE);
  #else
      if (tid < 32)
--    {      
++    {
          smem[tid] = product = product + smem[tid + 32];
  #if WAVE_SIZE < 32
      } barrier(CLK_LOCAL_MEM_FENCE);
@@@ -527,7 -434,7 +434,7 @@@ __kernel void classify_hists_kernel
      const int gidX = get_group_id(0);
      const int gidY = get_group_id(1);
  
--    __global const float* hist = block_hists + (gidY * win_block_stride_y * 
++    __global const float* hist = block_hists + (gidY * win_block_stride_y *
          img_block_width + gidX * win_block_stride_x) * cblock_hist_size;
  
      float product = 0.f;
      {
          int offset_y = i / cdescr_width;
          int offset_x = i - offset_y * cdescr_width;
--        product += coefs[i] * 
++        product += coefs[i] *
              hist[offset_y * img_block_width * cblock_hist_size + offset_x];
      }
  
        barrier(CLK_LOCAL_MEM_FENCE);
  #else
      if (tid < 32)
--    {       
++    {
          smem[tid] = product = product + smem[tid + 32];
  #if WAVE_SIZE < 32
      } barrier(CLK_LOCAL_MEM_FENCE);
  // Extract descriptors
  
  __kernel void extract_descrs_by_rows_kernel(
--    const int cblock_hist_size, const int descriptors_quadstep, 
--    const int cdescr_size, const int cdescr_width, const int img_block_width, 
++    const int cblock_hist_size, const int descriptors_quadstep,
++    const int cdescr_size, const int cdescr_width, const int img_block_width,
      const int win_block_stride_x, const int win_block_stride_y,
      __global const float* block_hists, __global float* descriptors)
  {
      int gidY = get_group_id(1);
  
      // Get left top corner of the window in src
--    __global const float* hist = block_hists + (gidY * win_block_stride_y * 
++    __global const float* hist = block_hists + (gidY * win_block_stride_y *
          img_block_width + gidX * win_block_stride_x) * cblock_hist_size;
  
      // Get left top corner of the window in dst
--    __global float* descriptor = descriptors + 
++    __global float* descriptor = descriptors +
          (gidY * get_num_groups(0) + gidX) * descriptors_quadstep;
  
      // Copy elements from src to dst
  
  __kernel void extract_descrs_by_cols_kernel(
      const int cblock_hist_size, const int descriptors_quadstep, const int cdescr_size,
--    const int cnblocks_win_x, const int cnblocks_win_y, const int img_block_width, 
--    const int win_block_stride_x, const int win_block_stride_y, 
++    const int cnblocks_win_x, const int cnblocks_win_y, const int img_block_width,
++    const int win_block_stride_x, const int win_block_stride_y,
      __global const float* block_hists, __global float* descriptors)
  {
      int tid = get_local_id(0);
      int gidY = get_group_id(1);
  
      // Get left top corner of the window in src
--    __global const float* hist = block_hists +  (gidY * win_block_stride_y * 
++    __global const float* hist = block_hists +  (gidY * win_block_stride_y *
          img_block_width + gidX * win_block_stride_x) * cblock_hist_size;
  
      // Get left top corner of the window in dst
--    __global float* descriptor = descriptors + 
++    __global float* descriptor = descriptors +
          (gidY * get_num_groups(0) + gidX) * descriptors_quadstep;
  
      // Copy elements from src to dst
          int y = block_idx / cnblocks_win_x;
          int x = block_idx - y * cnblocks_win_x;
  
--        descriptor[(x * cnblocks_win_y + y) * cblock_hist_size + idx_in_block] = 
++        descriptor[(x * cnblocks_win_y + y) * cblock_hist_size + idx_in_block] =
              hist[(y * img_block_width  + x) * cblock_hist_size + idx_in_block];
      }
  }
  // Gradients computation
  
  __kernel void compute_gradients_8UC4_kernel(
--    const int height, const int width, 
++    const int height, const int width,
      const int img_step, const int grad_quadstep, const int qangle_step,
      const __global uchar4 * img, __global float * grad, __global uchar * qangle,
      const float angle_scale, const char correct_gamma, const int cnbins)
      barrier(CLK_LOCAL_MEM_FENCE);
      if (x < width)
      {
--        float3 a = (float3) (sh_row[tid], sh_row[tid + (NTHREADS + 2)], 
++        float3 a = (float3) (sh_row[tid], sh_row[tid + (NTHREADS + 2)],
              sh_row[tid + 2 * (NTHREADS + 2)]);
--        float3 b = (float3) (sh_row[tid + 2], sh_row[tid + 2 + (NTHREADS + 2)], 
++        float3 b = (float3) (sh_row[tid + 2], sh_row[tid + 2 + (NTHREADS + 2)],
              sh_row[tid + 2 + 2 * (NTHREADS + 2)]);
  
          float3 dx;
  }
  
  __kernel void compute_gradients_8UC1_kernel(
--    const int height, const int width, 
++    const int height, const int width,
      const int img_step, const int grad_quadstep, const int qangle_step,
      __global const uchar * img, __global float * grad, __global uchar * qangle,
      const float angle_scale, const char correct_gamma, const int cnbins)
          grad[ (gidY * grad_quadstep + x) << 1 ]       = mag * (1.f - ang);
          grad[ ((gidY * grad_quadstep + x) << 1) + 1 ]   = mag * ang;
      }
--}
++}
@@@ -30,3 -31,9 +30,9 @@@ Restores the selected region in an imag
  The function reconstructs the selected image area from the pixel near the area boundary. The function may be used to remove dust and scratches from a scanned photo, or to remove undesirable objects from still images or video. See
  http://en.wikipedia.org/wiki/Inpainting
  for more details.
 -   * : PYTHON : An example using the inpainting technique can be found at opencv_source_code/samples/python2/inpaint.py
+ .. Sample code::
+    * : An example using the inpainting technique can be found at opencv_source_code/samples/cpp/inpaint.cpp
++   * : PYTHON : An example using the inpainting technique can be found at opencv_source_code/samples/python2/inpaint.py
Simple merge
@@@ -44,9 -44,8 +44,8 @@@
  
  #ifdef HAVE_OPENCL
  
 -#include "opencv2/ocl/ocl.hpp"
 +#include "opencv2/ocl.hpp"
  using namespace std;
- using namespace std::tr1;
  using namespace testing;
  using namespace perf;
  using namespace cv;
@@@ -909,4 -910,78 +909,78 @@@ Ptr<DenseOpticalFlowExt> cv::superres::
      return new DualTVL1_OCL;
  }
  
 -#endif
+ ///////////////////////////////////////////////////////////////////
+ // FarneBack
+ namespace
+ {
+     class FarneBack_OCL : public oclOpticalFlow
+     {
+     public:
+         AlgorithmInfo* info() const;
+         FarneBack_OCL();
+         void collectGarbage();
+     protected:
+         void impl(const cv::ocl::oclMat& input0, const cv::ocl::oclMat& input1, cv::ocl::oclMat& dst1, cv::ocl::oclMat& dst2);
+     private:
+         double pyrScale_;
+         int numLevels_;
+         int winSize_;
+         int numIters_;
+         int polyN_;
+         double polySigma_;
+         int flags_;
+         ocl::FarnebackOpticalFlow alg_;
+     };
+     CV_INIT_ALGORITHM(FarneBack_OCL, "DenseOpticalFlowExt.FarneBack_OCL",
+         obj.info()->addParam(obj, "pyrScale", obj.pyrScale_);
+     obj.info()->addParam(obj, "numLevels", obj.numLevels_);
+     obj.info()->addParam(obj, "winSize", obj.winSize_);
+     obj.info()->addParam(obj, "numIters", obj.numIters_);
+     obj.info()->addParam(obj, "polyN", obj.polyN_);
+     obj.info()->addParam(obj, "polySigma", obj.polySigma_);
+     obj.info()->addParam(obj, "flags", obj.flags_));
+     FarneBack_OCL::FarneBack_OCL() : oclOpticalFlow(CV_8UC1)
+     {
+         pyrScale_ = alg_.pyrScale;
+         numLevels_ = alg_.numLevels;
+         winSize_ = alg_.winSize;
+         numIters_ = alg_.numIters;
+         polyN_ = alg_.polyN;
+         polySigma_ = alg_.polySigma;
+         flags_ = alg_.flags;
+     }
+     void FarneBack_OCL::impl(const cv::ocl::oclMat& input0, const cv::ocl::oclMat& input1, cv::ocl::oclMat& dst1, cv::ocl::oclMat& dst2)
+     {
+         alg_.pyrScale = pyrScale_;
+         alg_.numLevels = numLevels_;
+         alg_.winSize = winSize_;
+         alg_.numIters = numIters_;
+         alg_.polyN = polyN_;
+         alg_.polySigma = polySigma_;
+         alg_.flags = flags_;
+         alg_(input0, input1, dst1, dst2);
+     }
+     void FarneBack_OCL::collectGarbage()
+     {
+         alg_.releaseMemory();
+         oclOpticalFlow::collectGarbage();
+     }
+ }
+ Ptr<DenseOpticalFlowExt> cv::superres::createOptFlow_Farneback_OCL()
+ {
+     return new FarneBack_OCL;
+ }
 +#endif
index f41b421,0000000..b53f759
mode 100644,000000..100644
--- /dev/null
@@@ -1,563 -1,0 +1,567 @@@
 +#ifndef __OPENCV_GTESTCV_HPP__
 +#define __OPENCV_GTESTCV_HPP__
 +
 +#include "opencv2/core/cvdef.h"
 +#include <stdarg.h> // for va_list
 +
 +#include "cvconfig.h"
 +
 +#ifndef GTEST_CREATE_SHARED_LIBRARY
 +#ifdef BUILD_SHARED_LIBS
 +#define GTEST_LINKED_AS_SHARED_LIBRARY 1
 +#endif
 +#endif
 +
++#ifdef HAVE_WINRT
++    #pragma warning(disable:4447) // Disable warning 'main' signature found without threading model
++#endif
++
 +#ifdef _MSC_VER
 +#pragma warning( disable: 4127 )
 +#endif
 +
 +#define GTEST_DONT_DEFINE_FAIL      0
 +#define GTEST_DONT_DEFINE_SUCCEED   0
 +#define GTEST_DONT_DEFINE_ASSERT_EQ 0
 +#define GTEST_DONT_DEFINE_ASSERT_NE 0
 +#define GTEST_DONT_DEFINE_ASSERT_LE 0
 +#define GTEST_DONT_DEFINE_ASSERT_LT 0
 +#define GTEST_DONT_DEFINE_ASSERT_GE 0
 +#define GTEST_DONT_DEFINE_ASSERT_GT 0
 +#define GTEST_DONT_DEFINE_TEST      0
 +
 +#include "opencv2/ts/ts_gtest.h"
 +
 +#ifndef GTEST_USES_SIMPLE_RE
 +#  define GTEST_USES_SIMPLE_RE 0
 +#endif
 +#ifndef GTEST_USES_POSIX_RE
 +#  define GTEST_USES_POSIX_RE 0
 +#endif
 +
 +#include "opencv2/core.hpp"
 +#include "opencv2/core/utility.hpp"
 +
 +namespace cvtest
 +{
 +
 +using std::vector;
 +using std::string;
 +using cv::RNG;
 +using cv::Mat;
 +using cv::Scalar;
 +using cv::Size;
 +using cv::Point;
 +using cv::Rect;
 +
 +class CV_EXPORTS TS;
 +
 +CV_EXPORTS int64 readSeed(const char* str);
 +
 +CV_EXPORTS void randUni( RNG& rng, Mat& a, const Scalar& param1, const Scalar& param2 );
 +
 +inline unsigned randInt( RNG& rng )
 +{
 +    return (unsigned)rng;
 +}
 +
 +inline  double randReal( RNG& rng )
 +{
 +    return (double)rng;
 +}
 +
 +
 +CV_EXPORTS const char* getTypeName( int type );
 +CV_EXPORTS int typeByName( const char* type_name );
 +
 +CV_EXPORTS string vec2str(const string& sep, const int* v, size_t nelems);
 +
 +inline int clipInt( int val, int min_val, int max_val )
 +{
 +    if( val < min_val )
 +        val = min_val;
 +    if( val > max_val )
 +        val = max_val;
 +    return val;
 +}
 +
 +CV_EXPORTS double getMinVal(int depth);
 +CV_EXPORTS double getMaxVal(int depth);
 +
 +CV_EXPORTS Size randomSize(RNG& rng, double maxSizeLog);
 +CV_EXPORTS void randomSize(RNG& rng, int minDims, int maxDims, double maxSizeLog, vector<int>& sz);
 +CV_EXPORTS int randomType(RNG& rng, int typeMask, int minChannels, int maxChannels);
 +CV_EXPORTS Mat randomMat(RNG& rng, Size size, int type, double minVal, double maxVal, bool useRoi);
 +CV_EXPORTS Mat randomMat(RNG& rng, const vector<int>& size, int type, double minVal, double maxVal, bool useRoi);
 +CV_EXPORTS void add(const Mat& a, double alpha, const Mat& b, double beta,
 +                      Scalar gamma, Mat& c, int ctype, bool calcAbs=false);
 +CV_EXPORTS void multiply(const Mat& a, const Mat& b, Mat& c, double alpha=1);
 +CV_EXPORTS void divide(const Mat& a, const Mat& b, Mat& c, double alpha=1);
 +
 +CV_EXPORTS void convert(const Mat& src, cv::OutputArray dst, int dtype, double alpha=1, double beta=0);
 +CV_EXPORTS void copy(const Mat& src, Mat& dst, const Mat& mask=Mat(), bool invertMask=false);
 +CV_EXPORTS void set(Mat& dst, const Scalar& gamma, const Mat& mask=Mat());
 +
 +// working with multi-channel arrays
 +CV_EXPORTS void extract( const Mat& a, Mat& plane, int coi );
 +CV_EXPORTS void insert( const Mat& plane, Mat& a, int coi );
 +
 +// checks that the array does not have NaNs and/or Infs and all the elements are
 +// within [min_val,max_val). idx is the index of the first "bad" element.
 +CV_EXPORTS int check( const Mat& data, double min_val, double max_val, vector<int>* idx );
 +
 +// modifies values that are close to zero
 +CV_EXPORTS void  patchZeros( Mat& mat, double level );
 +
 +CV_EXPORTS void transpose(const Mat& src, Mat& dst);
 +CV_EXPORTS void erode(const Mat& src, Mat& dst, const Mat& _kernel, Point anchor=Point(-1,-1),
 +                      int borderType=0, const Scalar& borderValue=Scalar());
 +CV_EXPORTS void dilate(const Mat& src, Mat& dst, const Mat& _kernel, Point anchor=Point(-1,-1),
 +                       int borderType=0, const Scalar& borderValue=Scalar());
 +CV_EXPORTS void filter2D(const Mat& src, Mat& dst, int ddepth, const Mat& kernel,
 +                         Point anchor, double delta, int borderType,
 +                         const Scalar& borderValue=Scalar());
 +CV_EXPORTS void copyMakeBorder(const Mat& src, Mat& dst, int top, int bottom, int left, int right,
 +                               int borderType, const Scalar& borderValue=Scalar());
 +CV_EXPORTS Mat calcSobelKernel2D( int dx, int dy, int apertureSize, int origin=0 );
 +CV_EXPORTS Mat calcLaplaceKernel2D( int aperture_size );
 +
 +CV_EXPORTS void initUndistortMap( const Mat& a, const Mat& k, Size sz, Mat& mapx, Mat& mapy );
 +
 +CV_EXPORTS void minMaxLoc(const Mat& src, double* minval, double* maxval,
 +                          vector<int>* minloc, vector<int>* maxloc, const Mat& mask=Mat());
 +CV_EXPORTS double norm(const Mat& src, int normType, const Mat& mask=Mat());
 +CV_EXPORTS double norm(const Mat& src1, const Mat& src2, int normType, const Mat& mask=Mat());
 +CV_EXPORTS Scalar mean(const Mat& src, const Mat& mask=Mat());
 +
 +CV_EXPORTS bool cmpUlps(const Mat& data, const Mat& refdata, int expMaxDiff, double* realMaxDiff, vector<int>* idx);
 +
 +// compares two arrays. max_diff is the maximum actual difference,
 +// success_err_level is maximum allowed difference, idx is the index of the first
 +// element for which difference is >success_err_level
 +// (or index of element with the maximum difference)
 +CV_EXPORTS int cmpEps( const Mat& data, const Mat& refdata, double* max_diff,
 +                       double success_err_level, vector<int>* idx,
 +                       bool element_wise_relative_error );
 +
 +// a wrapper for the previous function. in case of error prints the message to log file.
 +CV_EXPORTS int cmpEps2( TS* ts, const Mat& data, const Mat& refdata, double success_err_level,
 +                        bool element_wise_relative_error, const char* desc );
 +
 +CV_EXPORTS int cmpEps2_64f( TS* ts, const double* val, const double* refval, int len,
 +                        double eps, const char* param_name );
 +
 +CV_EXPORTS void logicOp(const Mat& src1, const Mat& src2, Mat& dst, char c);
 +CV_EXPORTS void logicOp(const Mat& src, const Scalar& s, Mat& dst, char c);
 +CV_EXPORTS void min(const Mat& src1, const Mat& src2, Mat& dst);
 +CV_EXPORTS void min(const Mat& src, double s, Mat& dst);
 +CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst);
 +CV_EXPORTS void max(const Mat& src, double s, Mat& dst);
 +
 +CV_EXPORTS void compare(const Mat& src1, const Mat& src2, Mat& dst, int cmpop);
 +CV_EXPORTS void compare(const Mat& src, double s, Mat& dst, int cmpop);
 +CV_EXPORTS void gemm(const Mat& src1, const Mat& src2, double alpha,
 +                     const Mat& src3, double beta, Mat& dst, int flags);
 +    CV_EXPORTS void transform( const Mat& src, Mat& dst, const Mat& transmat, const Mat& shift );
 +CV_EXPORTS double crossCorr(const Mat& src1, const Mat& src2);
 +
 +struct CV_EXPORTS MatInfo
 +{
 +    MatInfo(const Mat& _m) : m(&_m) {}
 +    const Mat* m;
 +};
 +
 +CV_EXPORTS std::ostream& operator << (std::ostream& out, const MatInfo& m);
 +
 +struct CV_EXPORTS MatComparator
 +{
 +public:
 +    MatComparator(double maxdiff, int context);
 +
 +    ::testing::AssertionResult operator()(const char* expr1, const char* expr2,
 +                                          const Mat& m1, const Mat& m2);
 +
 +    double maxdiff;
 +    double realmaxdiff;
 +    vector<int> loc0;
 +    int context;
 +};
 +
 +
 +
 +class BaseTest;
 +class TS;
 +
 +class CV_EXPORTS BaseTest
 +{
 +public:
 +    // constructor(s) and destructor
 +    BaseTest();
 +    virtual ~BaseTest();
 +
 +    // the main procedure of the test
 +    virtual void run( int start_from );
 +
 +    // the wrapper for run that cares of exceptions
 +    virtual void safe_run( int start_from=0 );
 +
 +    const string& get_name() const { return name; }
 +
 +    // returns true if and only if the different test cases do not depend on each other
 +    // (so that test system could get right to a problematic test case)
 +    virtual bool can_do_fast_forward();
 +
 +    // deallocates all the memory.
 +    // called by init() (before initialization) and by the destructor
 +    virtual void clear();
 +
 +protected:
 +    int test_case_count; // the total number of test cases
 +
 +    // read test params
 +    virtual int read_params( CvFileStorage* fs );
 +
 +    // returns the number of tests or -1 if it is unknown a-priori
 +    virtual int get_test_case_count();
 +
 +    // prepares data for the next test case. rng seed is updated by the function
 +    virtual int prepare_test_case( int test_case_idx );
 +
 +    // checks if the test output is valid and accurate
 +    virtual int validate_test_results( int test_case_idx );
 +
 +    // calls the tested function. the method is called from run_test_case()
 +    virtual void run_func(); // runs tested func(s)
 +
 +    // updates progress bar
 +    virtual int update_progress( int progress, int test_case_idx, int count, double dt );
 +
 +    // finds test parameter
 +    const CvFileNode* find_param( CvFileStorage* fs, const char* param_name );
 +
 +    // name of the test (it is possible to locate a test by its name)
 +    string name;
 +
 +    // pointer to the system that includes the test
 +    TS* ts;
 +};
 +
 +
 +/*****************************************************************************************\
 +*                               Information about a failed test                           *
 +\*****************************************************************************************/
 +
 +struct TestInfo
 +{
 +    TestInfo();
 +
 +    // pointer to the test
 +    BaseTest* test;
 +
 +    // failure code (CV_FAIL*)
 +    int code;
 +
 +    // seed value right before the data for the failed test case is prepared.
 +    uint64 rng_seed;
 +
 +    // seed value right before running the test
 +    uint64 rng_seed0;
 +
 +    // index of test case, can be then passed to BaseTest::proceed_to_test_case()
 +    int test_case_idx;
 +};
 +
 +/*****************************************************************************************\
 +*                                 Base Class for test system                              *
 +\*****************************************************************************************/
 +
 +// common parameters:
 +struct CV_EXPORTS TSParams
 +{
 +    TSParams();
 +
 +    // RNG seed, passed to and updated by every test executed.
 +    uint64 rng_seed;
 +
 +    // whether to use IPP, MKL etc. or not
 +    bool use_optimized;
 +
 +    // extensivity of the tests, scale factor for test_case_count
 +    double test_case_count_scale;
 +};
 +
 +
 +class CV_EXPORTS TS
 +{
 +public:
 +    // constructor(s) and destructor
 +    TS();
 +    virtual ~TS();
 +
 +    enum
 +    {
 +        NUL=0,
 +        SUMMARY_IDX=0,
 +        SUMMARY=1 << SUMMARY_IDX,
 +        LOG_IDX=1,
 +        LOG=1 << LOG_IDX,
 +        CSV_IDX=2,
 +        CSV=1 << CSV_IDX,
 +        CONSOLE_IDX=3,
 +        CONSOLE=1 << CONSOLE_IDX,
 +        MAX_IDX=4
 +    };
 +
 +    static TS* ptr();
 +
 +    // initialize test system before running the first test
 +    virtual void init( const string& modulename );
 +
 +    // low-level printing functions that are used by individual tests and by the system itself
 +    virtual void printf( int streams, const char* fmt, ... );
 +    virtual void vprintf( int streams, const char* fmt, va_list arglist );
 +
 +    // updates the context: current test, test case, rng state
 +    virtual void update_context( BaseTest* test, int test_case_idx, bool update_ts_context );
 +
 +    const TestInfo* get_current_test_info() { return &current_test_info; }
 +
 +    // sets information about a failed test
 +    virtual void set_failed_test_info( int fail_code );
 +
 +    virtual void set_gtest_status();
 +
 +    // test error codes
 +    enum
 +    {
 +        // everything is Ok
 +        OK=0,
 +
 +        // generic error: stub value to be used
 +        // temporarily if the error's cause is unknown
 +        FAIL_GENERIC=-1,
 +
 +        // the test is missing some essential data to proceed further
 +        FAIL_MISSING_TEST_DATA=-2,
 +
 +        // the tested function raised an error via cxcore error handler
 +        FAIL_ERROR_IN_CALLED_FUNC=-3,
 +
 +        // an exception has been raised;
 +        // for memory and arithmetic exception
 +        // there are two specialized codes (see below...)
 +        FAIL_EXCEPTION=-4,
 +
 +        // a memory exception
 +        // (access violation, access to missed page, stack overflow etc.)
 +        FAIL_MEMORY_EXCEPTION=-5,
 +
 +        // arithmetic exception (overflow, division by zero etc.)
 +        FAIL_ARITHM_EXCEPTION=-6,
 +
 +        // the tested function corrupted memory (no exception have been raised)
 +        FAIL_MEMORY_CORRUPTION_BEGIN=-7,
 +        FAIL_MEMORY_CORRUPTION_END=-8,
 +
 +        // the tested function (or test ifself) do not deallocate some memory
 +        FAIL_MEMORY_LEAK=-9,
 +
 +        // the tested function returned invalid object, e.g. matrix, containing NaNs,
 +        // structure with NULL or out-of-range fields (while it should not)
 +        FAIL_INVALID_OUTPUT=-10,
 +
 +        // the tested function returned valid object, but it does not match to
 +        // the original (or produced by the test) object
 +        FAIL_MISMATCH=-11,
 +
 +        // the tested function returned valid object (a single number or numerical array),
 +        // but it differs too much from the original (or produced by the test) object
 +        FAIL_BAD_ACCURACY=-12,
 +
 +        // the tested function hung. Sometimes, can be determined by unexpectedly long
 +        // processing time (in this case there should be possibility to interrupt such a function
 +        FAIL_HANG=-13,
 +
 +        // unexpected responce on passing bad arguments to the tested function
 +        // (the function crashed, proceed succesfully (while it should not), or returned
 +        // error code that is different from what is expected)
 +        FAIL_BAD_ARG_CHECK=-14,
 +
 +        // the test data (in whole or for the particular test case) is invalid
 +        FAIL_INVALID_TEST_DATA=-15,
 +
 +        // the test has been skipped because it is not in the selected subset of the tests to run,
 +        // because it has been run already within the same run with the same parameters, or because
 +        // of some other reason and this is not considered as an error.
 +        // Normally TS::run() (or overrided method in the derived class) takes care of what
 +        // needs to be run, so this code should not occur.
 +        SKIPPED=1
 +    };
 +
 +    // get file storage
 +    CvFileStorage* get_file_storage();
 +
 +    // get RNG to generate random input data for a test
 +    RNG& get_rng() { return rng; }
 +
 +    // returns the current error code
 +    int get_err_code() { return current_test_info.code; }
 +
 +    // returns the test extensivity scale
 +    double get_test_case_count_scale() { return params.test_case_count_scale; }
 +
 +    const string& get_data_path() const { return data_path; }
 +
 +    // returns textual description of failure code
 +    static string str_from_code( int code );
 +
 +protected:
 +
 +    // these are allocated within a test to try keep them valid in case of stack corruption
 +    RNG rng;
 +
 +    // information about the current test
 +    TestInfo current_test_info;
 +
 +    // the path to data files used by tests
 +    string data_path;
 +
 +    TSParams params;
 +    std::string output_buf[MAX_IDX];
 +};
 +
 +
 +/*****************************************************************************************\
 +*            Subclass of BaseTest for testing functions that process dense arrays           *
 +\*****************************************************************************************/
 +
 +class CV_EXPORTS ArrayTest : public BaseTest
 +{
 +public:
 +    // constructor(s) and destructor
 +    ArrayTest();
 +    virtual ~ArrayTest();
 +
 +    virtual void clear();
 +
 +protected:
 +
 +    virtual int read_params( CvFileStorage* fs );
 +    virtual int prepare_test_case( int test_case_idx );
 +    virtual int validate_test_results( int test_case_idx );
 +
 +    virtual void prepare_to_validation( int test_case_idx );
 +    virtual void get_test_array_types_and_sizes( int test_case_idx, vector<vector<Size> >& sizes, vector<vector<int> >& types );
 +    virtual void fill_array( int test_case_idx, int i, int j, Mat& arr );
 +    virtual void get_minmax_bounds( int i, int j, int type, Scalar& low, Scalar& high );
 +    virtual double get_success_error_level( int test_case_idx, int i, int j );
 +
 +    bool cvmat_allowed;
 +    bool iplimage_allowed;
 +    bool optional_mask;
 +    bool element_wise_relative_error;
 +
 +    int min_log_array_size;
 +    int max_log_array_size;
 +
 +    enum { INPUT, INPUT_OUTPUT, OUTPUT, REF_INPUT_OUTPUT, REF_OUTPUT, TEMP, MASK, MAX_ARR };
 +
 +    vector<vector<void*> > test_array;
 +    vector<vector<Mat> > test_mat;
 +    float buf[4];
 +};
 +
 +
 +class CV_EXPORTS BadArgTest : public BaseTest
 +{
 +public:
 +    // constructor(s) and destructor
 +    BadArgTest();
 +    virtual ~BadArgTest();
 +
 +protected:
 +    virtual int run_test_case( int expected_code, const string& descr );
 +    virtual void run_func(void) = 0;
 +    int test_case_idx;
 +
 +    template<class F>
 +    int run_test_case( int expected_code, const string& _descr, F f)
 +    {
 +        int errcount = 0;
 +        bool thrown = false;
 +        const char* descr = _descr.c_str() ? _descr.c_str() : "";
 +
 +        try
 +        {
 +            f();
 +        }
 +        catch(const cv::Exception& e)
 +        {
 +            thrown = true;
 +            if( e.code != expected_code )
 +            {
 +                ts->printf(TS::LOG, "%s (test case #%d): the error code %d is different from the expected %d\n",
 +                    descr, test_case_idx, e.code, expected_code);
 +                errcount = 1;
 +            }
 +        }
 +        catch(...)
 +        {
 +            thrown = true;
 +            ts->printf(TS::LOG, "%s  (test case #%d): unknown exception was thrown (the function has likely crashed)\n",
 +                       descr, test_case_idx);
 +            errcount = 1;
 +        }
 +        if(!thrown)
 +        {
 +            ts->printf(TS::LOG, "%s  (test case #%d): no expected exception was thrown\n",
 +                       descr, test_case_idx);
 +            errcount = 1;
 +        }
 +        test_case_idx++;
 +
 +        return errcount;
 +    }
 +};
 +
 +struct CV_EXPORTS DefaultRngAuto
 +{
 +    const uint64 old_state;
 +
 +    DefaultRngAuto() : old_state(cv::theRNG().state) { cv::theRNG().state = (uint64)-1; }
 +    ~DefaultRngAuto() { cv::theRNG().state = old_state; }
 +
 +    DefaultRngAuto& operator=(const DefaultRngAuto&);
 +};
 +
 +}
 +
 +namespace cvtest
 +{
 +
 +// test images generation functions
 +CV_EXPORTS void fillGradient(Mat& img, int delta = 5);
 +CV_EXPORTS void smoothBorder(Mat& img, const Scalar& color, int delta = 3);
 +
 +CV_EXPORTS void printVersionInfo(bool useStdOut = true);
 +} //namespace cvtest
 +
 +#define CV_TEST_MAIN(resourcesubdir) \
 +int main(int argc, char **argv) \
 +{ \
 +    cvtest::TS::ptr()->init(resourcesubdir); \
 +    ::testing::InitGoogleTest(&argc, argv); \
 +    cvtest::printVersionInfo();\
 +    return RUN_ALL_TESTS(); \
 +}
 +
 +// This usually only makes sense in perf tests with several implementations,
 +// some of which are not available.
 +#define CV_TEST_FAIL_NO_IMPL() do { \
 +    ::testing::Test::RecordProperty("custom_status", "noimpl"); \
 +    FAIL() << "No equivalent implementation."; \
 +} while (0)
 +
 +#endif
 +
 +#include "opencv2/ts/ts_perf.hpp"
index 223016f,0000000..41b875b
mode 100644,000000..100644
--- /dev/null
@@@ -1,72 -1,0 +1,64 @@@
- #  undef PACKAGE
- #  undef PACKAGE_BUGREPORT
- #  undef PACKAGE_NAME
- #  undef PACKAGE_STRING
- #  undef PACKAGE_TARNAME
- #  undef PACKAGE_VERSION
- #  undef VERSION
 +/*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-2011, 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_VIDEOSTAB_CLP_HPP__
 +#define __OPENCV_VIDEOSTAB_CLP_HPP__
 +
 +#ifdef HAVE_CLP
 +#  define COIN_BIG_INDEX 0
 +#  define DEBUG_COIN 0
 +#  define PRESOLVE_DEBUG 0
 +#  define PRESOLVE_CONSISTENCY 0
 +
 +#  include "ClpSimplex.hpp"
 +#  include "ClpPresolve.hpp"
 +#  include "ClpPrimalColumnSteepest.hpp"
 +#  include "ClpDualRowSteepest.hpp"
 +#  define INF 1e10
 +#endif
 +
 +// Clp replaces min and max with ?: globally, we can't use std::min and std::max in case
 +// when HAVE_CLP is true. We create the defines by ourselves when HAVE_CLP == 0.
 +#undef min
 +#undef max
 +
 +#endif