From 5c01d13f38c7826e5d03ea9944a818c8c9937126 Mon Sep 17 00:00:00 2001
From: Andrey Kamaev <andrey.kamaev@itseez.com>
Date: Mon, 27 Aug 2012 16:48:09 +0400
Subject: [PATCH 01/27] Pass list of modules to javadoc generator

Previously the generator always uses hardcoded list of modules.
This fix replaces hardcoded list with actual set of modules coming from cmake.
---
 modules/java/CMakeLists.txt           |  4 +-
 modules/java/generator/gen_javadoc.py | 59 +++++++++++++++++----------
 2 files changed, 39 insertions(+), 24 deletions(-)

diff --git a/modules/java/CMakeLists.txt b/modules/java/CMakeLists.txt
index 86c77b88d..39c90d354 100644
--- a/modules/java/CMakeLists.txt
+++ b/modules/java/CMakeLists.txt
@@ -108,10 +108,10 @@ file(GLOB_RECURSE refman_rst_headers "${CMAKE_CURRENT_SOURCE_DIR}/../*.rst")
 set(java_documented_headers_deps ${handwrittren_java_sources} ${generated_java_sources} ${java_hdr_deps} ${refman_rst_headers}
   "${GEN_JAVADOC}" "${RST_PARSER}" "${GEN_JAVA}" "${HDR_PARSER}")
 
-#TODO: pass list of modules
+string(REPLACE ";" "," OPENCV_JAVA_MODULES_STR "${OPENCV_JAVA_MODULES}")
 add_custom_command(
     OUTPUT ${documented_java_files}
-    COMMAND ${PYTHON_EXECUTABLE} "${GEN_JAVADOC}" "${CMAKE_CURRENT_SOURCE_DIR}/generator/src/java" "${CMAKE_CURRENT_BINARY_DIR}" 2>"${CMAKE_CURRENT_BINARY_DIR}/get_javadoc_errors.log"
+    COMMAND ${PYTHON_EXECUTABLE} "${GEN_JAVADOC}" --modules ${OPENCV_JAVA_MODULES_STR} "${CMAKE_CURRENT_SOURCE_DIR}/generator/src/java" "${CMAKE_CURRENT_BINARY_DIR}" 2>"${CMAKE_CURRENT_BINARY_DIR}/get_javadoc_errors.log"
     WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
     DEPENDS ${java_documented_headers_deps}
 )
diff --git a/modules/java/generator/gen_javadoc.py b/modules/java/generator/gen_javadoc.py
index 5d4c5cfd8..ecf6f3c55 100644
--- a/modules/java/generator/gen_javadoc.py
+++ b/modules/java/generator/gen_javadoc.py
@@ -1,17 +1,18 @@
 import os, sys, re, string, glob
-allmodules = ["core", "flann", "imgproc", "ml", "highgui", "video", "features2d", "calib3d", "objdetect", "legacy", "contrib", "gpu", "androidcamera", "haartraining", "java", "python", "stitching", "traincascade", "ts", "photo", "videostab"]
-verbose = False
-show_warnings = True
-show_errors = True
+from optparse import OptionParser
 
 class JavadocGenerator(object):
-    def __init__(self, definitions = {}, javadoc_marker = "//javadoc:"):
+    def __init__(self, definitions = {}, modules= [], javadoc_marker = "//javadoc:"):
         self.definitions = definitions
         self.javadoc_marker = javadoc_marker
         self.markers_processed = 0
         self.markers_documented = 0
         self.params_documented = 0
         self.params_undocumented = 0
+        self.known_modules = modules
+        self.verbose = False
+        self.show_warnings = True
+        self.show_errors = True
 
     def parceJavadocMarker(self, line):
         assert line.lstrip().startswith(self.javadoc_marker)
@@ -35,7 +36,7 @@ class JavadocGenerator(object):
         inf = open(infile, "rt")
         outf = open(outfile, "wt")
         module = os.path.splitext(os.path.basename(infile))[0].split("+")[0]
-        if module not in allmodules:
+        if module not in self.known_modules:
             module = "unknown"
         try:
             for l in inf.readlines():
@@ -47,14 +48,14 @@ class JavadocGenerator(object):
                     decl = self.definitions.get(marker[0],None)
                     if decl:
                         javadoc = self.makeJavadoc(decl, marker[2])
-                        if verbose:
+                        if self.verbose:
                             print
                             print "Javadoc for \"%s\" File: %s (line %s)" % (decl["name"], decl["file"], decl["line"])
                             print javadoc
                         for line in javadoc.split("\n"):
                             outf.write(marker[1] + line + "\n")
                         self.markers_documented += 1
-                    elif show_errors:
+                    elif self.show_errors:
                         print >> sys.stderr, "gen_javadoc error: could not find documentation for %s (module: %s)" % (l.lstrip()[len(self.javadoc_marker):-1].strip(), module)
                 else:
                     outf.write(org.replace("\t", "    ").rstrip()+"\n")
@@ -176,11 +177,11 @@ class JavadocGenerator(object):
             doc += prefix + self.ReformatForJavadoc(decl["brief"])
             prefix = " *\n"
         elif "long" not in decl:
-            if show_warnings:
+            if self.show_warnings:
                 print >> sys.stderr, "gen_javadoc warning: no description for " + decl_type + " \"%s\" File: %s (line %s)" % (func["name"], func["file"], func["line"])
             doc += prefix + self.ReformatForJavadoc("This " + decl_type + " is undocumented")
             prefix = " *\n"
-    
+
         # long goes after brief
         if "long" in decl:
             doc += prefix  + self.ReformatForJavadoc(decl["long"])
@@ -193,7 +194,7 @@ class JavadocGenerator(object):
                 arg_doc = documented_params.get(arg, None)
                 if not arg_doc:
                     arg_doc = "a " + arg
-                    if show_warnings:
+                    if self.show_warnings:
                         print >> sys.stderr, "gen_javadoc warning: parameter \"%s\" of \"%s\" is undocumented. File: %s (line %s)" % (arg, decl["name"], decl["file"], decl["line"])
                     self.params_undocumented += 1
                 else:
@@ -233,29 +234,43 @@ class JavadocGenerator(object):
         print
 
 if __name__ == "__main__":
-    if len(sys.argv) < 2:
-        print "Usage:\n", os.path.basename(sys.argv[0]), " <input dir1> [<input dir2> [...]]"
-        exit(0)
-   
+
     selfpath = os.path.dirname(os.path.abspath(sys.argv[0]))
     hdr_parser_path = os.path.join(selfpath, "../../python/src2")
-    
+
     sys.path.append(selfpath)
     sys.path.append(hdr_parser_path)
     import hdr_parser
     import rst_parser
 
+    parser = OptionParser()
+    parser.add_option("-v", "--verbose", dest="verbose", help="Print verbose log to stdout", action="store_true", default=False)
+    parser.add_option("", "--no-warnings", dest="warnings", help="Hide warning messages", action="store_false", default=True)
+    parser.add_option("", "--no-errors", dest="errors", help="Hide error messages", action="store_false", default=True)
+    parser.add_option("", "--modules", dest="modules", help="comma-separated list of modules to generate comments", metavar="MODS", default=",".join(rst_parser.allmodules))
+
+    (options, args) = parser.parse_args(sys.argv)
+    options.modules = options.modules.split(",")
+
+    if len(args) < 2 or len(options.modules) < 1:
+        parser.print_help()
+        exit(0)
+
     print "Parsing documentation..."
     parser = rst_parser.RstParser(hdr_parser.CppHeaderParser())
-    for m in allmodules:
+    for m in options.modules:
         parser.parse(m, os.path.join(selfpath, "../../" + m))
-        
+
     parser.printSummary()
 
-    print "Generating javadoc comments..."
-    generator = JavadocGenerator(parser.definitions)
-    for i in range(1, len(sys.argv)):
-        folder = os.path.abspath(sys.argv[i])
+    generator = JavadocGenerator(parser.definitions, options.modules)
+    generator.verbose = options.verbose
+    generator.show_warnings = options.warnings
+    generator.show_errors = options.errors
+
+    print "Generating javadoc comments for " + ", ".join(options.modules)
+    for path in args:
+        folder = os.path.abspath(path)
         for jfile in [f for f in glob.glob(os.path.join(folder,"*.java")) if not f.endswith("-jdoc.java")]:
             outfile = os.path.abspath(os.path.basename(jfile).replace(".java", "-jdoc.java"))
             generator.document(jfile, outfile)

From bcf8dd510f738a121b9db8d5a93559fd35cc360d Mon Sep 17 00:00:00 2001
From: Andrey Kamaev <andrey.kamaev@itseez.com>
Date: Mon, 27 Aug 2012 18:22:00 +0400
Subject: [PATCH 02/27] Added CCache support to Android build

To speed up rebuilds, define the NDK_CCACHE environment or CMake variable
to the path to your ccache binary. When declared, the android.cmake.toolchain
automatically uses CCache when compiling any C/C++ source file. For example:

export NDK_CCACHE=ccache
---
 CMakeLists.txt                      |  4 ++--
 android/android.toolchain.cmake     | 25 ++++++++++++++++++++++---
 cmake/OpenCVDetectCXXCompiler.cmake |  4 ++--
 3 files changed, 26 insertions(+), 7 deletions(-)

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 0d38deb1e..c87d6fbf9 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -517,10 +517,10 @@ endif()
 status("")
 status("  C/C++:")
 status("    Built as dynamic libs?:" BUILD_SHARED_LIBS THEN YES ELSE NO)
-status("    C++ Compiler:"           CMAKE_COMPILER_IS_GNUCXX THEN "${CMAKE_CXX_COMPILER} (ver ${CMAKE_GCC_REGEX_VERSION})" ELSE "${CMAKE_CXX_COMPILER}" )
+status("    C++ Compiler:"           CMAKE_COMPILER_IS_GNUCXX THEN "${CMAKE_CXX_COMPILER} ${CMAKE_CXX_COMPILER_ARG1} (ver ${CMAKE_GCC_REGEX_VERSION})" ELSE "${CMAKE_CXX_COMPILER}" )
 status("    C++ flags (Release):"    ${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_RELEASE})
 status("    C++ flags (Debug):"      ${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_DEBUG})
-status("    C Compiler:"             ${CMAKE_C_COMPILER})
+status("    C Compiler:"             ${CMAKE_C_COMPILER} ${CMAKE_C_COMPILER_ARG1})
 status("    C flags (Release):"      ${CMAKE_C_FLAGS} ${CMAKE_C_FLAGS_RELEASE})
 status("    C flags (Debug):"        ${CMAKE_C_FLAGS} ${CMAKE_C_FLAGS_DEBUG})
 if(WIN32)
diff --git a/android/android.toolchain.cmake b/android/android.toolchain.cmake
index 37c9ad15f..97b9f390b 100644
--- a/android/android.toolchain.cmake
+++ b/android/android.toolchain.cmake
@@ -187,6 +187,7 @@
 #     [+] updated for NDK r8b
 #     [~] all intermediate files generated by toolchain are moved into CMakeFiles
 #     [~] libstdc++ and libsupc are removed from explicit link libraries
+#     [+] added ccache support (via NDK_CCACHE environment or cmake variable)
 # ------------------------------------------------------------------------------
 
 cmake_minimum_required( VERSION 2.6.3 )
@@ -686,9 +687,25 @@ if( BUILD_WITH_ANDROID_NDK )
  endif()
 endif()
 
+# ccache support
+__INIT_VARIABLE( NDK_CCACHE ENV_NDK_CCACHE )
+if( NDK_CCACHE )
+ get_filename_component(NDK_CCACHE "${NDK_CCACHE}" ABSOLUTE)
+ set( NDK_CCACHE "${NDK_CCACHE}" CACHE PATH "The path to ccache binary" FORCE )
+else()
+ unset( NDK_CCACHE )
+endif()
+
 # specify the cross compiler
-set( CMAKE_C_COMPILER   "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-gcc${TOOL_OS_SUFFIX}"     CACHE PATH "gcc" )
-set( CMAKE_CXX_COMPILER "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-g++${TOOL_OS_SUFFIX}"     CACHE PATH "g++" )
+if( NDK_CCACHE )
+ set( CMAKE_C_COMPILER   "${NDK_CCACHE}" CACHE PATH "ccache as C compiler" )
+ set( CMAKE_CXX_COMPILER "${NDK_CCACHE}" CACHE PATH "ccache as C++ compiler" )
+ set( CMAKE_C_COMPILER_ARG1 "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-gcc${TOOL_OS_SUFFIX}"   CACHE PATH "gcc")
+ set( CMAKE_CXX_COMPILER_ARG1 "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-g++${TOOL_OS_SUFFIX}" CACHE PATH "g++")
+else()
+ set( CMAKE_C_COMPILER   "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-gcc${TOOL_OS_SUFFIX}"    CACHE PATH "gcc" )
+ set( CMAKE_CXX_COMPILER "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-g++${TOOL_OS_SUFFIX}"    CACHE PATH "g++" )
+endif()
 set( CMAKE_ASM_COMPILER "${ANDROID_TOOLCHAIN_ROOT}/bin/${ANDROID_TOOLCHAIN_MACHINE_NAME}-gcc${TOOL_OS_SUFFIX}"     CACHE PATH "Assembler" )
 if( CMAKE_VERSION VERSION_LESS 2.8.5 )
  set( CMAKE_ASM_COMPILER_ARG1 "-c" )
@@ -1039,7 +1056,9 @@ endmacro()
 # export toolchain settings for the try_compile() command
 if( NOT PROJECT_NAME STREQUAL "CMAKE_TRY_COMPILE" )
  set( __toolchain_config "")
- foreach( __var ANDROID_ABI ANDROID_FORCE_ARM_BUILD ANDROID_NATIVE_API_LEVEL ANDROID_NO_UNDEFINED ANDROID_SO_UNDEFINED ANDROID_SET_OBSOLETE_VARIABLES LIBRARY_OUTPUT_PATH_ROOT ANDROID_USE_STLPORT ANDROID_FORBID_SYGWIN ANDROID_NDK ANDROID_STANDALONE_TOOLCHAIN ANDROID_FUNCTION_LEVEL_LINKING __ndklibspath )
+ foreach( __var NDK_CCACHE ANDROID_ABI ANDROID_FORCE_ARM_BUILD ANDROID_NATIVE_API_LEVEL ANDROID_NO_UNDEFINED
+                ANDROID_SO_UNDEFINED ANDROID_SET_OBSOLETE_VARIABLES LIBRARY_OUTPUT_PATH_ROOT ANDROID_USE_STLPORT
+                ANDROID_FORBID_SYGWIN ANDROID_NDK ANDROID_STANDALONE_TOOLCHAIN ANDROID_FUNCTION_LEVEL_LINKING __ndklibspath )
   if( DEFINED ${__var} )
    if( "${__var}" MATCHES " ")
     set( __toolchain_config "${__toolchain_config}set( ${__var} \"${${__var}}\" CACHE INTERNAL \"\" )\n" )
diff --git a/cmake/OpenCVDetectCXXCompiler.cmake b/cmake/OpenCVDetectCXXCompiler.cmake
index 987f311dd..5ce90ce6f 100644
--- a/cmake/OpenCVDetectCXXCompiler.cmake
+++ b/cmake/OpenCVDetectCXXCompiler.cmake
@@ -54,11 +54,11 @@ endif()
 # Detect GNU version:
 # ----------------------------------------------------------------------------
 if(CMAKE_COMPILER_IS_GNUCXX)
-    execute_process(COMMAND ${CMAKE_CXX_COMPILER} --version
+    execute_process(COMMAND ${CMAKE_CXX_COMPILER} ${CMAKE_CXX_COMPILER_ARG1} --version
                   OUTPUT_VARIABLE CMAKE_OPENCV_GCC_VERSION_FULL
                   OUTPUT_STRIP_TRAILING_WHITESPACE)
 
-    execute_process(COMMAND ${CMAKE_CXX_COMPILER} -v
+    execute_process(COMMAND ${CMAKE_CXX_COMPILER} ${CMAKE_CXX_COMPILER_ARG1} -v
                   ERROR_VARIABLE CMAKE_OPENCV_GCC_INFO_FULL
                   OUTPUT_STRIP_TRAILING_WHITESPACE)
 

From c0786e9d338664d2d932aa76ade99030181cf9ea Mon Sep 17 00:00:00 2001
From: Andrey Kamaev <andrey.kamaev@itseez.com>
Date: Mon, 27 Aug 2012 19:45:24 +0400
Subject: [PATCH 03/27] Support for the gold linker (NDK r8b is required)

---
 android/android.toolchain.cmake | 19 ++++++++++++++++---
 1 file changed, 16 insertions(+), 3 deletions(-)

diff --git a/android/android.toolchain.cmake b/android/android.toolchain.cmake
index 97b9f390b..1b42f017c 100644
--- a/android/android.toolchain.cmake
+++ b/android/android.toolchain.cmake
@@ -187,7 +187,8 @@
 #     [+] updated for NDK r8b
 #     [~] all intermediate files generated by toolchain are moved into CMakeFiles
 #     [~] libstdc++ and libsupc are removed from explicit link libraries
-#     [+] added ccache support (via NDK_CCACHE environment or cmake variable)
+#     [+] added CCache support (via NDK_CCACHE environment or cmake variable)
+#     [+] added gold linker support for NDK r8b
 # ------------------------------------------------------------------------------
 
 cmake_minimum_required( VERSION 2.6.3 )
@@ -941,7 +942,7 @@ if( ANDROID_SO_UNDEFINED )
 endif()
 
 __INIT_VARIABLE( ANDROID_FUNCTION_LEVEL_LINKING VALUES ON )
-set( ANDROID_FUNCTION_LEVEL_LINKING ON CACHE BOOL "Allows or disallows undefined symbols in shared libraries" FORCE )
+set( ANDROID_FUNCTION_LEVEL_LINKING ${ANDROID_FUNCTION_LEVEL_LINKING} CACHE BOOL "Allows or disallows undefined symbols in shared libraries" FORCE )
 mark_as_advanced( ANDROID_FUNCTION_LEVEL_LINKING )
 if( ANDROID_FUNCTION_LEVEL_LINKING )
  set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fdata-sections -ffunction-sections" )
@@ -954,6 +955,15 @@ if( ARMEABI_V7A )
  set( ANDROID_LINKER_FLAGS "-Wl,--fix-cortex-a8 ${ANDROID_LINKER_FLAGS}" )
 endif()
 
+if( CMAKE_HOST_UNIX AND ANDROID_COMPILER_VERSION VERSION_EQUAL "4.6" AND (ARMEABI_V7A OR X86) )
+ __INIT_VARIABLE( ANDROID_USE_GOLD_LINKER VALUES ON )
+ set( ANDROID_USE_GOLD_LINKER ${ANDROID_USE_GOLD_LINKER} CACHE BOOL "Enables gold linker" FORCE )
+ mark_as_advanced( ANDROID_USE_GOLD_LINKER )
+ if( ANDROID_USE_GOLD_LINKER )
+  set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} -fuse-ld=gold" )
+ endif()
+endif()
+
 # cache flags
 set( CMAKE_CXX_FLAGS "${_CMAKE_CXX_FLAGS}" CACHE STRING "c++ flags" )
 set( CMAKE_C_FLAGS "${_CMAKE_C_FLAGS}" CACHE STRING "c flags" )
@@ -1058,7 +1068,8 @@ if( NOT PROJECT_NAME STREQUAL "CMAKE_TRY_COMPILE" )
  set( __toolchain_config "")
  foreach( __var NDK_CCACHE ANDROID_ABI ANDROID_FORCE_ARM_BUILD ANDROID_NATIVE_API_LEVEL ANDROID_NO_UNDEFINED
                 ANDROID_SO_UNDEFINED ANDROID_SET_OBSOLETE_VARIABLES LIBRARY_OUTPUT_PATH_ROOT ANDROID_USE_STLPORT
-                ANDROID_FORBID_SYGWIN ANDROID_NDK ANDROID_STANDALONE_TOOLCHAIN ANDROID_FUNCTION_LEVEL_LINKING __ndklibspath )
+                ANDROID_FORBID_SYGWIN ANDROID_NDK ANDROID_STANDALONE_TOOLCHAIN ANDROID_FUNCTION_LEVEL_LINKING
+                ANDROID_USE_GOLD_LINKER __ndklibspath )
   if( DEFINED ${__var} )
    if( "${__var}" MATCHES " ")
     set( __toolchain_config "${__toolchain_config}set( ${__var} \"${${__var}}\" CACHE INTERNAL \"\" )\n" )
@@ -1092,9 +1103,11 @@ endif()
 #   ANDROID_NO_UNDEFINED : ON/OFF
 #   ANDROID_SO_UNDEFINED : OFF/ON  (default depends on NDK version)
 #   ANDROID_FUNCTION_LEVEL_LINKING : ON/OFF
+#   ANDROID_USE_GOLD_LINKER : ON/OFF   (default depends on NDK version and host & target platforms)
 # Variables that takes effect only at first run:
 #   ANDROID_FORCE_ARM_BUILD : ON/OFF
 #   LIBRARY_OUTPUT_PATH_ROOT : <any valid path>
+#   NDK_CCACHE : <path to your ccache executable>
 # Can be set only at the first run:
 #   ANDROID_NDK
 #   ANDROID_STANDALONE_TOOLCHAIN

From bbbe77e05e7f1bdccb8f58ce347d4f314ac3f140 Mon Sep 17 00:00:00 2001
From: Andrey Kamaev <andrey.kamaev@itseez.com>
Date: Mon, 27 Aug 2012 20:16:54 +0400
Subject: [PATCH 04/27] Fix Android build for mips platform

---
 android/android.toolchain.cmake                 | 5 +++--
 modules/contrib/src/detection_based_tracker.cpp | 1 +
 2 files changed, 4 insertions(+), 2 deletions(-)

diff --git a/android/android.toolchain.cmake b/android/android.toolchain.cmake
index 1b42f017c..8e653a007 100644
--- a/android/android.toolchain.cmake
+++ b/android/android.toolchain.cmake
@@ -189,6 +189,7 @@
 #     [~] libstdc++ and libsupc are removed from explicit link libraries
 #     [+] added CCache support (via NDK_CCACHE environment or cmake variable)
 #     [+] added gold linker support for NDK r8b
+#     [~] fixed mips linker flags for NDK r8b
 # ------------------------------------------------------------------------------
 
 cmake_minimum_required( VERSION 2.6.3 )
@@ -810,7 +811,7 @@ elseif( X86 )
  set( _CMAKE_C_FLAGS "-funwind-tables" )
 elseif( MIPS )
  set( _CMAKE_CXX_FLAGS "-fpic -Wno-psabi -fno-strict-aliasing -finline-functions -ffunction-sections -funwind-tables -fmessage-length=0 -fno-inline-functions-called-once -fgcse-after-reload -frerun-cse-after-loop -frename-registers" )
- set( _CMAKE_CXX_FLAGS "-fpic -Wno-psabi -fno-strict-aliasing -finline-functions -ffunction-sections -funwind-tables -fmessage-length=0 -fno-inline-functions-called-once -fgcse-after-reload -frerun-cse-after-loop -frename-registers" )
+ set( _CMAKE_C_FLAGS "-fpic -Wno-psabi -fno-strict-aliasing -finline-functions -ffunction-sections -funwind-tables -fmessage-length=0 -fno-inline-functions-called-once -fgcse-after-reload -frerun-cse-after-loop -frename-registers" )
  set( ANDROID_CXX_FLAGS "${ANDROID_CXX_FLAGS} -fsigned-char" )
 else()
  set( _CMAKE_CXX_FLAGS "" )
@@ -983,7 +984,7 @@ set( ANDROID_CXX_FLAGS    "${ANDROID_CXX_FLAGS}"    CACHE INTERNAL "Extra Androi
 set( ANDROID_LINKER_FLAGS "${ANDROID_LINKER_FLAGS}" CACHE INTERNAL "Extra Android linker flags")
 set( CMAKE_CXX_FLAGS           "${ANDROID_CXX_FLAGS} ${CMAKE_CXX_FLAGS}" )
 set( CMAKE_C_FLAGS             "${ANDROID_CXX_FLAGS} ${CMAKE_C_FLAGS}" )
-if( MIPS AND BUILD_WITH_ANDROID_NDK )
+if( MIPS AND BUILD_WITH_ANDROID_NDK AND ANDROID_NDK MATCHES "-r8$" )
  set( CMAKE_SHARED_LINKER_FLAGS "-Wl,-T,${ANDROID_NDK}/toolchains/${ANDROID_TOOLCHAIN_NAME}/mipself.xsc ${ANDROID_LINKER_FLAGS} ${CMAKE_SHARED_LINKER_FLAGS}" )
  set( CMAKE_MODULE_LINKER_FLAGS "-Wl,-T,${ANDROID_NDK}/toolchains/${ANDROID_TOOLCHAIN_NAME}/mipself.xsc ${ANDROID_LINKER_FLAGS} ${CMAKE_MODULE_LINKER_FLAGS}" )
  set( CMAKE_EXE_LINKER_FLAGS    "-Wl,-T,${ANDROID_NDK}/toolchains/${ANDROID_TOOLCHAIN_NAME}/mipself.x ${ANDROID_LINKER_FLAGS} ${CMAKE_EXE_LINKER_FLAGS}" )
diff --git a/modules/contrib/src/detection_based_tracker.cpp b/modules/contrib/src/detection_based_tracker.cpp
index 8c477a96d..84a779b0a 100644
--- a/modules/contrib/src/detection_based_tracker.cpp
+++ b/modules/contrib/src/detection_based_tracker.cpp
@@ -5,6 +5,7 @@
 
 #ifdef ANDROID
 #include <android/log.h>
+#include <pthread.h>
 #define LOG_TAG "OBJECT_DETECTOR"
 #define LOGD0(...) ((void)__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__))
 #define LOGI0(...) ((void)__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__))

From d421ec26e2c34912cb2d8f85e729cd226ba4fe0d Mon Sep 17 00:00:00 2001
From: Andrey Kamaev <andrey.kamaev@itseez.com>
Date: Tue, 28 Aug 2012 13:26:57 +0400
Subject: [PATCH 05/27] Android toolchain: fixed ccache search

---
 android/android.toolchain.cmake | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/android/android.toolchain.cmake b/android/android.toolchain.cmake
index 8e653a007..47918ade5 100644
--- a/android/android.toolchain.cmake
+++ b/android/android.toolchain.cmake
@@ -692,8 +692,7 @@ endif()
 # ccache support
 __INIT_VARIABLE( NDK_CCACHE ENV_NDK_CCACHE )
 if( NDK_CCACHE )
- get_filename_component(NDK_CCACHE "${NDK_CCACHE}" ABSOLUTE)
- set( NDK_CCACHE "${NDK_CCACHE}" CACHE PATH "The path to ccache binary" FORCE )
+ find_program(NDK_CCACHE "${NDK_CCACHE}" DOC "The path to ccache binary")
 else()
  unset( NDK_CCACHE )
 endif()

From 95d54196dbe8a3562feef3cd251e03a7878fec93 Mon Sep 17 00:00:00 2001
From: Andrey Kamaev <andrey.kamaev@itseez.com>
Date: Tue, 28 Aug 2012 13:30:11 +0400
Subject: [PATCH 06/27] Android camera: fix logging macro

---
 modules/androidcamera/src/camera_activity.cpp | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)

diff --git a/modules/androidcamera/src/camera_activity.cpp b/modules/androidcamera/src/camera_activity.cpp
index 23b39a1af..6954e49a5 100644
--- a/modules/androidcamera/src/camera_activity.cpp
+++ b/modules/androidcamera/src/camera_activity.cpp
@@ -6,10 +6,15 @@
 #include "camera_activity.hpp"
 #include "camera_wrapper.h"
 
-#define LOG_TAG "CAMERA_ACTIVITY"
+#undef LOG_TAG
+#undef LOGE
+#undef LOGD
+#undef LOGI
+
+#define LOG_TAG "OpenCV::camera"
+#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__))
 #define LOGD(...) ((void)__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__))
 #define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__))
-#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__))
 
 ///////
 // Debug

From 0bd68a70f141d4f98dbe75339740ef2ad83ff74f Mon Sep 17 00:00:00 2001
From: Vadim Pisarevsky <vadim.pisarevsky@itseez.com>
Date: Tue, 28 Aug 2012 13:45:35 +0400
Subject: [PATCH 07/27] fixed #2297, #2300; fixed several warnings

---
 modules/core/include/opencv2/core/mat.hpp           |  2 +-
 modules/core/include/opencv2/core/operations.hpp    | 13 +++++++------
 modules/core/src/array.cpp                          |  2 +-
 modules/core/src/cmdparser.cpp                      |  4 +++-
 modules/core/src/opengl_interop.cpp                 |  4 ++--
 modules/core/src/persistence.cpp                    |  2 +-
 modules/core/test/test_ds.cpp                       |  8 ++++----
 modules/core/test/test_rand.cpp                     |  2 +-
 modules/flann/include/opencv2/flann/lsh_index.h     |  4 ++--
 .../photo/src/fast_nlmeans_denoising_invoker.hpp    |  2 +-
 .../src/fast_nlmeans_multi_denoising_invoker.hpp    |  2 +-
 modules/ts/src/ts_gtest.cpp                         |  4 +++-
 12 files changed, 27 insertions(+), 22 deletions(-)

diff --git a/modules/core/include/opencv2/core/mat.hpp b/modules/core/include/opencv2/core/mat.hpp
index ccc02571e..92301cf3b 100644
--- a/modules/core/include/opencv2/core/mat.hpp
+++ b/modules/core/include/opencv2/core/mat.hpp
@@ -404,7 +404,7 @@ inline bool Mat::empty() const { return data == 0 || total() == 0; }
 inline size_t Mat::total() const
 {
     if( dims <= 2 )
-        return rows*cols;
+        return (size_t)rows*cols;
     size_t p = 1;
     for( int i = 0; i < dims; i++ )
         p *= size[i];
diff --git a/modules/core/include/opencv2/core/operations.hpp b/modules/core/include/opencv2/core/operations.hpp
index 932d9fbd8..af89bbf3a 100644
--- a/modules/core/include/opencv2/core/operations.hpp
+++ b/modules/core/include/opencv2/core/operations.hpp
@@ -866,7 +866,7 @@ template<typename _Tp, int m, int n> struct CV_EXPORTS Matx_FastSolveOp
 template<typename _Tp> struct CV_EXPORTS Matx_FastSolveOp<_Tp, 2, 1>
 {
     bool operator()(const Matx<_Tp, 2, 2>& a, const Matx<_Tp, 2, 1>& b,
-                    Matx<_Tp, 2, 1>& x, int method) const
+                    Matx<_Tp, 2, 1>& x, int) const
     {
         _Tp d = determinant(a);
         if( d == 0 )
@@ -1244,7 +1244,7 @@ template<> inline Vec<double, 4> Vec<double, 4>::conj() const
     return conjugate(*this);
 }
 
-template<typename _Tp, int cn> inline Vec<_Tp, cn> Vec<_Tp, cn>::cross(const Vec<_Tp, cn>& v) const
+template<typename _Tp, int cn> inline Vec<_Tp, cn> Vec<_Tp, cn>::cross(const Vec<_Tp, cn>&) const
 {
     CV_Error(CV_StsError, "for arbitrary-size vector there is no cross-product defined");
     return Vec<_Tp, cn>();
@@ -2466,7 +2466,8 @@ dot(const Vector<_Tp>& v1, const Vector<_Tp>& v2)
     {
         const _Tp *ptr1 = &v1[0], *ptr2 = &v2[0];
      #if CV_ENABLE_UNROLLED
-        for(; i <= n - 4; i += 4 )
+        const size_t n2 = (n > 4) ? n : 4;
+        for(; i <= n2 - 4; i += 4 )
             s += (_Tw)ptr1[i]*ptr2[i] + (_Tw)ptr1[i+1]*ptr2[i+1] +
                 (_Tw)ptr1[i+2]*ptr2[i+2] + (_Tw)ptr1[i+3]*ptr2[i+3];
     #endif
@@ -2500,7 +2501,7 @@ inline RNG::operator double()
     unsigned t = next();
     return (((uint64)t << 32) | next())*5.4210108624275221700372640043497e-20;
 }
-inline int RNG::uniform(int a, int b) { return a == b ? a : next()%(b - a) + a; }
+inline int RNG::uniform(int a, int b) { return a == b ? a : (int)(next()%(b - a) + a); }
 inline float RNG::uniform(float a, float b) { return ((float)*this)*(b - a) + a; }
 inline double RNG::uniform(double a, double b) { return ((double)*this)*(b - a) + a; }
 
@@ -2937,8 +2938,8 @@ inline bool FileNode::isNamed() const { return !node ? false : (node->tag & NAME
 inline size_t FileNode::size() const
 {
     int t = type();
-    return t == MAP ? ((CvSet*)node->data.map)->active_count :
-        t == SEQ ? node->data.seq->total : (size_t)!isNone();
+    return t == MAP ? (size_t)((CvSet*)node->data.map)->active_count :
+        t == SEQ ? (size_t)node->data.seq->total : (size_t)!isNone();
 }
 
 inline CvFileNode* FileNode::operator *() { return (CvFileNode*)node; }
diff --git a/modules/core/src/array.cpp b/modules/core/src/array.cpp
index f065a1e41..c9060bf6d 100644
--- a/modules/core/src/array.cpp
+++ b/modules/core/src/array.cpp
@@ -861,7 +861,7 @@ cvCreateData( CvArr* arr )
         if( CV_IS_MAT_CONT( mat->type ))
         {
             total_size = (size_t)mat->dim[0].size*(mat->dim[0].step != 0 ?
-                         mat->dim[0].step : total_size);
+                         (size_t)mat->dim[0].step : total_size);
         }
         else
         {
diff --git a/modules/core/src/cmdparser.cpp b/modules/core/src/cmdparser.cpp
index b5c838c9d..d7be05418 100644
--- a/modules/core/src/cmdparser.cpp
+++ b/modules/core/src/cmdparser.cpp
@@ -7,7 +7,8 @@ using namespace std;
 using namespace cv;
 
 namespace {
-void helpParser()
+#if 0
+static void helpParser()
 {
     printf("\nThe CommandLineParser class is designed for command line arguments parsing\n"
            "Keys map: \n"
@@ -50,6 +51,7 @@ void helpParser()
            "                          It also works with 'unsigned int', 'double', and 'float' types \n"
            );
 }
+#endif
 
 vector<string> split_string(const string& str, const string& delimiters)
 {
diff --git a/modules/core/src/opengl_interop.cpp b/modules/core/src/opengl_interop.cpp
index bf9deaadb..5895363cd 100644
--- a/modules/core/src/opengl_interop.cpp
+++ b/modules/core/src/opengl_interop.cpp
@@ -113,13 +113,13 @@ namespace
 
     const CvOpenGlFuncTab* g_glFuncTab = 0;
 
-//#ifdef HAVE_CUDA
+#if defined HAVE_CUDA || defined HAVE_OPENGL
     const CvOpenGlFuncTab* glFuncTab()
     {
         static EmptyGlFuncTab empty;
         return g_glFuncTab ? g_glFuncTab : &empty;
     }
-//#endif
+#endif
 }
 
 CvOpenGlFuncTab::~CvOpenGlFuncTab()
diff --git a/modules/core/src/persistence.cpp b/modules/core/src/persistence.cpp
index 049b7fb7d..d060ac3b0 100644
--- a/modules/core/src/persistence.cpp
+++ b/modules/core/src/persistence.cpp
@@ -2793,7 +2793,7 @@ cvOpenFileStorage( const char* filename, CvMemStorage* dststorage, int flags, co
         fs->buffer_end = fs->buffer_start + buf_size;
         if( fs->fmt == CV_STORAGE_FORMAT_XML )
         {
-            size_t file_size = fs->file ? ftell( fs->file ) : (size_t)0;
+            size_t file_size = fs->file ? (size_t)ftell( fs->file ) : (size_t)0;
             fs->strstorage = cvCreateChildMemStorage( fs->memstorage );
             if( !append || file_size == 0 )
             {
diff --git a/modules/core/test/test_ds.cpp b/modules/core/test/test_ds.cpp
index 7a5c6f182..d79786054 100644
--- a/modules/core/test/test_ds.cpp
+++ b/modules/core/test/test_ds.cpp
@@ -845,7 +845,7 @@ int  Core_SeqBaseTest::test_seq_ops( int iters )
                 cvtest::randUni( rng, elem_mat, cvScalarAll(0), cvScalarAll(255) );
 
                 whence = op - 7;
-                pos = whence < 0 ? 0 : whence > 0 ? sseq->count : cvtest::randInt(rng) % (sseq->count+1);
+                pos = whence < 0 ? 0 : whence > 0 ? sseq->count : (int)(cvtest::randInt(rng) % (sseq->count+1));
                 if( whence != 0 )
                 {
                      cvSeqPushMulti( seq, elem, count, whence < 0 );
@@ -866,8 +866,8 @@ int  Core_SeqBaseTest::test_seq_ops( int iters )
                 if( sseq->count > 0 )
                 {
                     // choose the random element among the added
-                    pos = count > 0 ? cvtest::randInt(rng) % count + pos : MAX(pos-1,0);
-                     elem2 = cvGetSeqElem( seq, pos );
+                    pos = count > 0 ? (int)(cvtest::randInt(rng) % count + pos) : MAX(pos-1,0);
+                    elem2 = cvGetSeqElem( seq, pos );
                     CV_TS_SEQ_CHECK_CONDITION( elem2 != 0, "multi push operation doesn't add elements" );
                     CV_TS_SEQ_CHECK_CONDITION( seq->total == sseq->count &&
                                               memcmp( elem2, cvTsSimpleSeqElem(sseq,pos), elem_size) == 0,
@@ -889,7 +889,7 @@ int  Core_SeqBaseTest::test_seq_ops( int iters )
                 count = cvtest::randInt(rng) % (sseq->count+1);
                 whence = op - 10;
                 pos = whence < 0 ? 0 : whence > 0 ? sseq->count - count :
-                cvtest::randInt(rng) % (sseq->count - count + 1);
+                    (int)(cvtest::randInt(rng) % (sseq->count - count + 1));
 
                 if( whence != 0 )
                 {
diff --git a/modules/core/test/test_rand.cpp b/modules/core/test/test_rand.cpp
index 8fab1656b..e93415b3b 100644
--- a/modules/core/test/test_rand.cpp
+++ b/modules/core/test/test_rand.cpp
@@ -168,7 +168,7 @@ void Core_RandTest::run( int )
             int sz = 0, dsz = 0, slice;
             for( slice = 0; slice < maxSlice; slice++, sz += dsz )
             {
-                dsz = slice+1 < maxSlice ? cvtest::randInt(rng) % (SZ - sz + 1) : SZ - sz;
+                dsz = slice+1 < maxSlice ? (int)(cvtest::randInt(rng) % (SZ - sz + 1)) : SZ - sz;
                 Mat aslice = arr[k].colRange(sz, sz + dsz);
                 tested_rng.fill(aslice, dist_type, A, B);
             }
diff --git a/modules/flann/include/opencv2/flann/lsh_index.h b/modules/flann/include/opencv2/flann/lsh_index.h
index fc4cebb63..13627cabc 100644
--- a/modules/flann/include/opencv2/flann/lsh_index.h
+++ b/modules/flann/include/opencv2/flann/lsh_index.h
@@ -260,8 +260,8 @@ private:
      * @param k_nn the number of nearest neighbors
      * @param checked_average used for debugging
      */
-    void getNeighbors(const ElementType* vec, bool do_radius, float radius, bool do_k, unsigned int k_nn,
-                      float& checked_average)
+    void getNeighbors(const ElementType* vec, bool /*do_radius*/, float radius, bool do_k, unsigned int k_nn,
+                      float& /*checked_average*/)
     {
         static std::vector<ScoreIndexPair> score_index_heap;
 
diff --git a/modules/photo/src/fast_nlmeans_denoising_invoker.hpp b/modules/photo/src/fast_nlmeans_denoising_invoker.hpp
index 6724e8272..82839c98b 100644
--- a/modules/photo/src/fast_nlmeans_denoising_invoker.hpp
+++ b/modules/photo/src/fast_nlmeans_denoising_invoker.hpp
@@ -62,7 +62,7 @@ struct FastNlMeansDenoisingInvoker {
 
         void operator() (const BlockedRange& range) const;
 
-		void operator= (const FastNlMeansDenoisingInvoker& invoker) {
+		void operator= (const FastNlMeansDenoisingInvoker&) {
 			CV_Error(CV_StsNotImplemented, "Assigment operator is not implemented");
 		}
 
diff --git a/modules/photo/src/fast_nlmeans_multi_denoising_invoker.hpp b/modules/photo/src/fast_nlmeans_multi_denoising_invoker.hpp
index 602007e32..f8d387ce7 100644
--- a/modules/photo/src/fast_nlmeans_multi_denoising_invoker.hpp
+++ b/modules/photo/src/fast_nlmeans_multi_denoising_invoker.hpp
@@ -63,7 +63,7 @@ struct FastNlMeansMultiDenoisingInvoker {
 
         void operator() (const BlockedRange& range) const;
 
-		void operator= (const FastNlMeansMultiDenoisingInvoker& invoker) {
+		void operator= (const FastNlMeansMultiDenoisingInvoker&) {
 			CV_Error(CV_StsNotImplemented, "Assigment operator is not implemented");
 		}
 
diff --git a/modules/ts/src/ts_gtest.cpp b/modules/ts/src/ts_gtest.cpp
index f2cd000a2..2a46570cf 100644
--- a/modules/ts/src/ts_gtest.cpp
+++ b/modules/ts/src/ts_gtest.cpp
@@ -5896,7 +5896,7 @@ bool SkipPrefix(const char* prefix, const char** pstr) {
 // part can be omitted.
 //
 // Returns the value of the flag, or NULL if the parsing failed.
-const char* ParseFlagValue(const char* str,
+static const char* ParseFlagValue(const char* str,
                            const char* flag,
                            bool def_optional) {
   // str and flag must not be NULL.
@@ -7221,12 +7221,14 @@ void StackLowerThanAddress(const void* ptr, bool* result) {
   *result = (&dummy < ptr);
 }
 
+#if GTEST_HAS_CLONE    
 static bool StackGrowsDown() {
   int dummy;
   bool result;
   StackLowerThanAddress(&dummy, &result);
   return result;
 }
+#endif
 
 // Spawns a child process with the same executable as the current process in
 // a thread-safe manner and instructs it to run the death test.  The

From e2c9e7c3fbd0d95f78f2e61b41c138daa1f00dc8 Mon Sep 17 00:00:00 2001
From: Vadim Pisarevsky <vadim.pisarevsky@itseez.com>
Date: Tue, 28 Aug 2012 14:19:34 +0400
Subject: [PATCH 08/27] applied patches from #2311

---
 modules/highgui/src/cap_libv4l.cpp | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/modules/highgui/src/cap_libv4l.cpp b/modules/highgui/src/cap_libv4l.cpp
index c27224d9e..6dcc567ca 100644
--- a/modules/highgui/src/cap_libv4l.cpp
+++ b/modules/highgui/src/cap_libv4l.cpp
@@ -956,6 +956,7 @@ static int _capture_V4L (CvCaptureCAM_V4L *capture, char *deviceName)
      if (capture->memoryMap == MAP_FAILED) {
         fprintf( stderr, "HIGHGUI ERROR: V4L: Mapping Memmory from video source error: %s\n", strerror(errno));
         icvCloseCAM_V4L(capture);
+        return -1;
      }
 
      /* Set up video_mmap structure pointing to this memory mapped area so each image may be
@@ -1709,6 +1710,7 @@ static void icvCloseCAM_V4L( CvCaptureCAM_V4L* capture ){
      }
 #endif
 
+     free(capture->deviceName);
      //v4l2_free_ranges(capture);
      //cvFree((void **)capture);
    }

From a07e33609b737bebae3fb64ddc4c1c37ff9213b1 Mon Sep 17 00:00:00 2001
From: "marina.kolpakova" <marina.kolpakova@itseez.com>
Date: Tue, 28 Aug 2012 14:45:45 +0400
Subject: [PATCH 09/27] added test for caltech images

---
 modules/gpu/perf/perf_objdetect.cpp | 41 +++++++++++++++++++++++
 modules/gpu/test/test_objdetect.cpp | 51 ++++++++++++++++++++++++++++-
 2 files changed, 91 insertions(+), 1 deletion(-)

diff --git a/modules/gpu/perf/perf_objdetect.cpp b/modules/gpu/perf/perf_objdetect.cpp
index 0c4cd5e4c..ec12100a9 100644
--- a/modules/gpu/perf/perf_objdetect.cpp
+++ b/modules/gpu/perf/perf_objdetect.cpp
@@ -45,6 +45,47 @@ PERF_TEST_P(Image, ObjDetect_HOG, Values<string>("gpu/hog/road.png"))
     }
 }
 
+//===========test for CalTech data =============//
+DEF_PARAM_TEST_1(HOG, string);
+
+PERF_TEST_P(HOG, CalTech, Values<string>("gpu/caltech/image_00000009_0.png", "gpu/caltech/image_00000032_0.png",
+    "gpu/caltech/image_00000165_0.png", "gpu/caltech/image_00000261_0.png", "gpu/caltech/image_00000469_0.png",
+    "gpu/caltech/image_00000527_0.png", "gpu/caltech/image_00000574_0.png"))
+{
+    cv::Mat img = readImage(GetParam(), cv::IMREAD_GRAYSCALE);
+    ASSERT_FALSE(img.empty());
+
+    std::vector<cv::Rect> found_locations;
+
+    if (runOnGpu)
+    {
+        cv::gpu::GpuMat d_img(img);
+
+        cv::gpu::HOGDescriptor d_hog;
+        d_hog.setSVMDetector(cv::gpu::HOGDescriptor::getDefaultPeopleDetector());
+
+        d_hog.detectMultiScale(d_img, found_locations);
+
+        TEST_CYCLE()
+        {
+            d_hog.detectMultiScale(d_img, found_locations);
+        }
+    }
+    else
+    {
+        cv::HOGDescriptor hog;
+        hog.setSVMDetector(cv::gpu::HOGDescriptor::getDefaultPeopleDetector());
+
+        hog.detectMultiScale(img, found_locations);
+
+        TEST_CYCLE()
+        {
+            hog.detectMultiScale(img, found_locations);
+        }
+    }
+}
+
+
 ///////////////////////////////////////////////////////////////
 // HaarClassifier
 
diff --git a/modules/gpu/test/test_objdetect.cpp b/modules/gpu/test/test_objdetect.cpp
index b47966d50..8f7ab1eb8 100644
--- a/modules/gpu/test/test_objdetect.cpp
+++ b/modules/gpu/test/test_objdetect.cpp
@@ -175,7 +175,8 @@ struct HOG : testing::TestWithParam<cv::gpu::DeviceInfo>, cv::gpu::HOGDescriptor
     }
 };
 
-TEST_P(HOG, Detect)
+// desabled while resize does not fixed
+TEST_P(HOG, DISABLED_Detect)
 {
     cv::Mat img_rgb = readImage("hog/road.png");
     ASSERT_FALSE(img_rgb.empty());
@@ -286,6 +287,54 @@ TEST_P(HOG, GetDescriptors)
 
 INSTANTIATE_TEST_CASE_P(GPU_ObjDetect, HOG, ALL_DEVICES);
 
+//============== caltech hog tests =====================//
+struct CalTech : public ::testing::TestWithParam<std::tr1::tuple<cv::gpu::DeviceInfo, std::string> >
+{
+    cv::gpu::DeviceInfo devInfo;
+    cv::Mat img;
+
+    virtual void SetUp()
+    {
+        devInfo = GET_PARAM(0);
+        cv::gpu::setDevice(devInfo.deviceID());
+
+        img = readImage(GET_PARAM(1), cv::IMREAD_GRAYSCALE);
+        ASSERT_FALSE(img.empty());
+    }
+};
+
+TEST_P(CalTech, HOG)
+{
+    cv::gpu::GpuMat d_img(img);
+    cv::Mat markedImage(img.clone());
+
+    cv::gpu::HOGDescriptor d_hog;
+    d_hog.setSVMDetector(cv::gpu::HOGDescriptor::getDefaultPeopleDetector());
+    d_hog.nlevels = d_hog.nlevels + 32;
+
+    std::vector<cv::Rect> found_locations;
+    d_hog.detectMultiScale(d_img, found_locations);
+
+#if defined (LOG_CASCADE_STATISTIC)
+    for (int i = 0; i < (int)found_locations.size(); i++)
+    {
+        cv::Rect r = found_locations[i];
+
+        std::cout << r.x << " " << r.y  << " " << r.width << " " << r.height << std::endl;
+        cv::rectangle(markedImage, r , CV_RGB(255, 0, 0));
+    }
+
+    cv::imshow("Res", markedImage); cv::waitKey();
+#endif
+}
+
+INSTANTIATE_TEST_CASE_P(detect, CalTech, testing::Combine(ALL_DEVICES,
+    ::testing::Values<std::string>("caltech/image_00000009_0.png", "caltech/image_00000032_0.png",
+        "caltech/image_00000165_0.png", "caltech/image_00000261_0.png", "caltech/image_00000469_0.png",
+        "caltech/image_00000527_0.png", "caltech/image_00000574_0.png")));
+
+
+
 
 //////////////////////////////////////////////////////////////////////////////////////////
 /// LBP classifier

From 396e4517ffc72283631c7b5b8d2e44366f223141 Mon Sep 17 00:00:00 2001
From: Vsevolod Glumov <seva17@gmail.com>
Date: Tue, 28 Aug 2012 15:01:14 +0400
Subject: [PATCH 10/27] Improved javadoc comments. Draft.

---
 .../src/java/android+AsyncServiceHelper.java  |  4 ++--
 .../src/java/android+BaseLoaderCallback.java  | 14 ++++++------
 .../android+InstallCallbackInterface.java     | 10 ++++-----
 .../java/android+LoaderCallbackInterface.java | 22 +++++++++----------
 .../src/java/android+OpenCVLoader.java        | 18 +++++++--------
 .../src/java/android+StaticHelper.java        |  2 +-
 .../generator/src/java/android+Utils.java     | 12 +++++-----
 .../generator/src/java/core+TermCriteria.java | 10 ++++-----
 .../java/engine+OpenCVEngineInterface.aidl    | 22 +++++++++----------
 .../generator/src/java/features2d+DMatch.java | 10 ++++-----
 .../src/java/features2d+KeyPoint.java         | 16 +++++++-------
 .../src/java/highgui+VideoCapture.java        | 16 +++++++-------
 12 files changed, 78 insertions(+), 78 deletions(-)

diff --git a/modules/java/generator/src/java/android+AsyncServiceHelper.java b/modules/java/generator/src/java/android+AsyncServiceHelper.java
index 723a56039..8069f4672 100644
--- a/modules/java/generator/src/java/android+AsyncServiceHelper.java
+++ b/modules/java/generator/src/java/android+AsyncServiceHelper.java
@@ -105,7 +105,7 @@ class AsyncServiceHelper
     }
     
     /**
-     * URI for OpenCV Manager on Google Play (Android Market)
+     *  URL of OpenCV Manager page on Google Play Market.
      */
     protected static final String OPEN_CV_SERVICE_URL = "market://details?id=org.opencv.engine";
 
@@ -263,7 +263,7 @@ class AsyncServiceHelper
             }
             else
             {
-                // If dependencies list is not defined or empty
+                // If dependencies list is not defined or empty.
                 String AbsLibraryPath = Path + File.separator + "libopencv_java.so";
                 result &= loadLibrary(AbsLibraryPath);
             }
diff --git a/modules/java/generator/src/java/android+BaseLoaderCallback.java b/modules/java/generator/src/java/android+BaseLoaderCallback.java
index 2936b8a3f..220ca5e01 100644
--- a/modules/java/generator/src/java/android+BaseLoaderCallback.java
+++ b/modules/java/generator/src/java/android+BaseLoaderCallback.java
@@ -7,7 +7,7 @@ import android.content.DialogInterface.OnClickListener;
 import android.util.Log;
 
 /**
- * Basic implementation of LoaderCallbackInterface
+ * Basic implementation of LoaderCallbackInterface.
  */
 public abstract class BaseLoaderCallback implements LoaderCallbackInterface {
 
@@ -22,9 +22,9 @@ public abstract class BaseLoaderCallback implements LoaderCallbackInterface {
             /** OpenCV initialization was successful. **/
             case LoaderCallbackInterface.SUCCESS:
             {
-                /** Application must override this method to handle successful library initialization **/
+                /** Application must override this method to handle successful library initialization. **/
             } break;
-            /** OpenCV Manager or library package installation is in progress. Restart of application is required **/
+            /** OpenCV Manager or library package installation is in progress. Restart the application. **/
             case LoaderCallbackInterface.RESTART_REQUIRED:
             {
                 Log.d(TAG, "OpenCV downloading. App restart is needed!");
@@ -40,7 +40,7 @@ public abstract class BaseLoaderCallback implements LoaderCallbackInterface {
 
                 RestartMessage.show();
             } break;
-            /** OpenCV loader cannot start Google Play **/
+            /** OpenCV loader cannot start Google Play Market. **/
             case LoaderCallbackInterface.MARKET_ERROR:
             {
                 Log.d(TAG, "Google Play service is not installed! You can get it here");
@@ -55,13 +55,13 @@ public abstract class BaseLoaderCallback implements LoaderCallbackInterface {
                 });
                 MarketErrorMessage.show();
             } break;
-            /** Package installation was canceled **/
+            /** Package installation has been canceled. **/
             case LoaderCallbackInterface.INSTALL_CANCELED:
             {
                 Log.d(TAG, "OpenCV library instalation was canceled by user");
                 mAppContext.finish();
             } break;
-            /** Application is incompatible with this version of OpenCV Manager. Possible Service update is needed **/
+            /** Application is incompatible with this version of OpenCV Manager. Possibly, a service update is required. **/
             case LoaderCallbackInterface.INCOMPATIBLE_MANAGER_VERSION:
             {
                 Log.d(TAG, "OpenCV Manager Service is uncompatible with this app!");
@@ -76,7 +76,7 @@ public abstract class BaseLoaderCallback implements LoaderCallbackInterface {
                 });
                 IncomatibilityMessage.show();
             }
-            /** Other status, i.e. INIT_FAILED **/
+            /** Other status, i.e. INIT_FAILED. **/
             default:
             {
                 Log.e(TAG, "OpenCV loading failed!");
diff --git a/modules/java/generator/src/java/android+InstallCallbackInterface.java b/modules/java/generator/src/java/android+InstallCallbackInterface.java
index bd477705f..12785d9ac 100644
--- a/modules/java/generator/src/java/android+InstallCallbackInterface.java
+++ b/modules/java/generator/src/java/android+InstallCallbackInterface.java
@@ -1,21 +1,21 @@
 package org.opencv.android;
 
 /**
- * Installation callback interface
+ * Installation callback interface.
  */
 public interface InstallCallbackInterface
 {
     /**
-     * Target package name
-     * @return Return target package name
+     * Target package name.
+     * @return Return target package name.
      */
     public String getPackageName();
     /**
-     * Installation of package is approved
+     * Installation is approved.
      */
     public void install();
     /**
-     * Installation canceled
+     * Installation is canceled.
      */
     public void cancel();
 };
diff --git a/modules/java/generator/src/java/android+LoaderCallbackInterface.java b/modules/java/generator/src/java/android+LoaderCallbackInterface.java
index b96cabe4a..56cdf1519 100644
--- a/modules/java/generator/src/java/android+LoaderCallbackInterface.java
+++ b/modules/java/generator/src/java/android+LoaderCallbackInterface.java
@@ -1,44 +1,44 @@
 package org.opencv.android;
 
 /**
- * Interface for callback object in case of asynchronous initialization of OpenCV
+ * Interface for callback object in case of asynchronous initialization of OpenCV.
  */
 public interface LoaderCallbackInterface
 {
     /**
-     * OpenCV initialization finished successfully
+     * OpenCV initialization finished successfully.
      */
     static final int SUCCESS = 0;
     /**
-     * OpenCV library installation via Google Play service was initialized. Application restart is required
+     * OpenCV library installation via Google Play service has been initialized. Restart the application.
      */
     static final int RESTART_REQUIRED = 1;
     /**
-     * Google Play (Android Market) cannot be invoked
+     * Google Play Market cannot be invoked.
      */
     static final int MARKET_ERROR = 2;
     /**
-     * OpenCV library installation was canceled by user
+     * OpenCV library installation has been canceled by user.
      */
     static final int INSTALL_CANCELED = 3;
     /**
-     * Version of OpenCV Manager Service is incompatible with this app. Service update is needed
+     * This version of OpenCV Manager Service is incompatible with the app. Possibly, a service update is required.
      */
     static final int INCOMPATIBLE_MANAGER_VERSION = 4;
     /**
-     * OpenCV library initialization failed
+     * OpenCV library initialization failed.
      */
     static final int INIT_FAILED = 0xff;
 
     /**
-     * Callback method that is called after OpenCV library initialization
-     * @param status Status of initialization. See Initialization status constants
+     * This callback method is called after OpenCV library initialization.
+     * @param status Status of initialization (see Initialization status constants).
      */
     public void onManagerConnected(int status);
 
     /**
-     * Callback method that is called in case when package installation is needed
-     * @param callback Answer object with approve and cancel methods and package description
+     * This callback method is called in case the package installation is needed.
+     * @param callback Answer object with approve and cancel methods and the package description.
      */
     public void onPackageInstall(InstallCallbackInterface callback);
 };
diff --git a/modules/java/generator/src/java/android+OpenCVLoader.java b/modules/java/generator/src/java/android+OpenCVLoader.java
index dd4ee53d5..376d04c73 100644
--- a/modules/java/generator/src/java/android+OpenCVLoader.java
+++ b/modules/java/generator/src/java/android+OpenCVLoader.java
@@ -3,18 +3,18 @@ package org.opencv.android;
 import android.content.Context;
 
 /**
- * Helper class provides common initialization methods for OpenCV library
+ * Helper class provides common initialization methods for OpenCV library.
  */
 public class OpenCVLoader
 {
     /**
-     * OpenCV Library version 2.4.2
+     * OpenCV Library version 2.4.2.
      */
     public static final String OPENCV_VERSION_2_4_2 = "2.4.2";
 
     /**
-     * Load and initialize OpenCV library from current application package. Roughly it is analog of system.loadLibrary("opencv_java")
-     * @return Return true is initialization of OpenCV was successful
+     * Loads and initializes OpenCV library from current application package. Roughly, it's an analog of system.loadLibrary("opencv_java").
+     * @return Returns true is initialization of OpenCV was successful.
      */
     public static boolean initDebug()
     {
@@ -22,11 +22,11 @@ public class OpenCVLoader
     }
 
     /**
-     *  Load and initialize OpenCV library using OpenCV Engine service.
-     * @param Version OpenCV Library version
-     * @param AppContext Application context for connecting to service
-     * @param Callback Object, that implements LoaderCallbackInterface for handling Connection status
-     * @return Return true if initialization of OpenCV starts successfully
+     * Loads and initializes OpenCV library using OpenCV Engine service.
+     * @param Version OpenCV Library version.
+     * @param AppContext Application context for connecting to service.
+     * @param Callback Object, that implements LoaderCallbackInterface for handling Connection status.
+     * @return Returns true if initialization of OpenCV is successful.
      */
     public static boolean initAsync(String Version, Context AppContext,
             LoaderCallbackInterface Callback)
diff --git a/modules/java/generator/src/java/android+StaticHelper.java b/modules/java/generator/src/java/android+StaticHelper.java
index 8bc04e1fb..3082d2259 100644
--- a/modules/java/generator/src/java/android+StaticHelper.java
+++ b/modules/java/generator/src/java/android+StaticHelper.java
@@ -76,7 +76,7 @@ class StaticHelper {
         }
         else
         {
-            // If dependencies list is not defined or empty
+            // If dependencies list is not defined or empty.
             result &= loadLibrary("opencv_java");
         }
 
diff --git a/modules/java/generator/src/java/android+Utils.java b/modules/java/generator/src/java/android+Utils.java
index a990cd10b..ceecf3a63 100644
--- a/modules/java/generator/src/java/android+Utils.java
+++ b/modules/java/generator/src/java/android+Utils.java
@@ -76,14 +76,14 @@ public class Utils {
     /**
      * Converts Android Bitmap to OpenCV Mat.
      * <p>
-     * The function converts an image in the Android Bitmap representation to the OpenCV Mat.
+     * This function converts an Android Bitmap image to the OpenCV Mat.
      * <br>The 'ARGB_8888' and 'RGB_565' input Bitmap formats are supported.
      * <br>The output Mat is always created of the same size as the input Bitmap and of the 'CV_8UC4' type,
      * it keeps the image in RGBA format.
-     * <br>The function throws an exception if the conversion fails.
+     * <br>This function throws an exception if the conversion fails.
      * @param bmp is a valid input Bitmap object of the type 'ARGB_8888' or 'RGB_565'.
-     * @param mat is a valid output Mat object, it will be reallocated if needed, so it's possible to pass an empty Mat.
-     * @param unPremultiplyAlpha is a flag if the bitmap needs to be converted from alpha premultiplied format (like Android keeps 'ARGB_8888' ones) to regular one. The flag is ignored for 'RGB_565' bitmaps.
+     * @param mat is a valid output Mat object, it will be reallocated if needed, so it may be empty.
+     * @param unPremultiplyAlpha is a flag if the bitmap needs to be converted from alpha premultiplied format (like Android keeps 'ARGB_8888' ones) to regular one. This flag is ignored for 'RGB_565' bitmaps.
      */
     public static void bitmapToMat(Bitmap bmp, Mat mat, boolean unPremultiplyAlpha) {
         if (bmp == null)
@@ -94,7 +94,7 @@ public class Utils {
     }
 
     /**
-     * Shortened form of the bitmapToMat(bmp, mat, unPremultiplyAlpha=false)
+     * Short form of the bitmapToMat(bmp, mat, unPremultiplyAlpha=false).
      * @param bmp is a valid input Bitmap object of the type 'ARGB_8888' or 'RGB_565'.
      * @param mat is a valid output Mat object, it will be reallocated if needed, so it's possible to pass an empty Mat.
      */
@@ -124,7 +124,7 @@ public class Utils {
     }
 
     /**
-     * Shortened form of the <b>matToBitmap(mat, bmp, premultiplyAlpha=false)</b>
+     * Short form of the <b>matToBitmap(mat, bmp, premultiplyAlpha=false)</b>
      * @param mat is a valid input Mat object of the types 'CV_8UC1', 'CV_8UC3' or 'CV_8UC4'.
      * @param bmp is a valid Bitmap object of the same size as the Mat m and of type 'ARGB_8888' or 'RGB_565'.
      */
diff --git a/modules/java/generator/src/java/core+TermCriteria.java b/modules/java/generator/src/java/core+TermCriteria.java
index 1717883d1..3c4a8debe 100644
--- a/modules/java/generator/src/java/core+TermCriteria.java
+++ b/modules/java/generator/src/java/core+TermCriteria.java
@@ -4,15 +4,15 @@ package org.opencv.core;
 public class TermCriteria {
 
     /**
-     * the maximum number of iterations or elements to compute
+     * the maximum of iterations or elements to compute
      */
     public static final int COUNT = 1;
     /**
-     * the maximum number of iterations or elements to compute
+     * the maximum of iterations or elements to compute
      */
     public static final int MAX_ITER = COUNT;
     /**
-     * the desired accuracy or change in parameters at which the iterative algorithm stops
+     * the desired accuracy threshold or change in parameters at which the iterative algorithm stops.
      */
     public static final int EPS = 2;
 
@@ -21,7 +21,7 @@ public class TermCriteria {
     public double epsilon;
 
     /**
-     * Termination criteria in iterative algorithms
+     * Termination criteria for iterative algorithms.
      * 
      * @param type
      *            the type of termination criteria: COUNT, EPS or COUNT + EPS
@@ -37,7 +37,7 @@ public class TermCriteria {
     }
 
     /**
-     * Termination criteria in iterative algorithms
+     * Termination criteria for iterative algorithms
      */
     public TermCriteria() {
         this(0, 0, 0.0);
diff --git a/modules/java/generator/src/java/engine+OpenCVEngineInterface.aidl b/modules/java/generator/src/java/engine+OpenCVEngineInterface.aidl
index d3f216ccd..7bf967fd8 100644
--- a/modules/java/generator/src/java/engine+OpenCVEngineInterface.aidl
+++ b/modules/java/generator/src/java/engine+OpenCVEngineInterface.aidl
@@ -1,33 +1,33 @@
 package org.opencv.engine;
 
 /**
-* Class provides Java interface to OpenCV Engine Service. Is synchronous with native OpenCVEngine class.
+* Class provides a Java interface for OpenCV Engine Service. It's synchronous with native OpenCVEngine class.
 */
 interface OpenCVEngineInterface
 {
 	/**
-	* @return Return service version
+	* @return Returns service version.
 	*/
 	int getEngineVersion();
 
 	/**
-	* Find installed OpenCV library
-	* @param OpenCV version
-	* @return Return path to OpenCV native libs or empty string if OpenCV was not found
+	* Finds an installed OpenCV library.
+	* @param OpenCV version.
+	* @return Returns path to OpenCV native libs or an empty string if OpenCV can not be found.
 	*/
 	String getLibPathByVersion(String version);
 
 	/**
-	* Try to install defined version of OpenCV from Google Play (Android Market).
-	* @param OpenCV version
-	* @return Return true if installation was successful or OpenCV package has been already installed
+	* Tries to install defined version of OpenCV from Google Play Market.
+	* @param OpenCV version.
+	* @return Returns true if installation was successful or OpenCV package has been already installed.
 	*/
 	boolean installVersion(String version);
  
 	/**
-	* Return list of libraries in loading order separated by ";" symbol
-	* @param OpenCV version
-	* @return Return OpenCV libraries names separated by symbol ";" in loading order
+	* Returns list of libraries in loading order, separated by semicolon.
+	* @param OpenCV version.
+	* @return Returns names of OpenCV libraries, separated by semicolon.
 	*/
 	String getLibraryList(String version);
 }
\ No newline at end of file
diff --git a/modules/java/generator/src/java/features2d+DMatch.java b/modules/java/generator/src/java/features2d+DMatch.java
index ac864063e..b93a53335 100644
--- a/modules/java/generator/src/java/features2d+DMatch.java
+++ b/modules/java/generator/src/java/features2d+DMatch.java
@@ -3,21 +3,21 @@ package org.opencv.features2d;
 //C++: class DMatch
 
 /**
- * Struct for matching: query descriptor index, train descriptor index, train
+ * Structure for matching: query descriptor index, train descriptor index, train
  * image index and distance between descriptors.
  */
 public class DMatch {
 
     /**
-     * query descriptor index
+     * Query descriptor index.
      */
     public int queryIdx;
     /**
-     * train descriptor index
+     * Train descriptor index.
      */
     public int trainIdx;
     /**
-     * train image index
+     * Train image index.
      */
     public int imgIdx;
 
@@ -46,7 +46,7 @@ public class DMatch {
     }
 
     /**
-     * less is better
+     * Less is better.
      */
     public boolean lessThan(DMatch it) {
         return distance < it.distance;
diff --git a/modules/java/generator/src/java/features2d+KeyPoint.java b/modules/java/generator/src/java/features2d+KeyPoint.java
index f141cd16f..352f7cda0 100644
--- a/modules/java/generator/src/java/features2d+KeyPoint.java
+++ b/modules/java/generator/src/java/features2d+KeyPoint.java
@@ -6,29 +6,29 @@ import org.opencv.core.Point;
 public class KeyPoint {
 
     /**
-     * coordinates of the keypoint
+     * Coordinates of the keypoint.
      */
     public Point pt;
     /**
-     * diameter of the meaningful keypoint neighborhood
+     * Diameter of the useful keypoint adjacent area.
      */
     public float size;
     /**
-     * computed orientation of the keypoint (-1 if not applicable)
+     * Computed orientation of the keypoint (-1 if not applicable).
      */
     public float angle;
     /**
-     * the response by which the most strong keypoints have been selected. Can
-     * be used for further sorting or subsampling
+     * The response, by which the strongest keypoints have been selected. Can
+     * be used for further sorting or subsampling.
      */
     public float response;
     /**
-     * octave (pyramid layer) from which the keypoint has been extracted
+     * Octave (pyramid layer), from which the keypoint has been extracted.
      */
     public int octave;
     /**
-     * object id that can be used to clustered keypoints by an object they
-     * belong to
+     * Object ID, that can be used to cluster keypoints by an object they
+     * belong to.
      */
     public int class_id;
 
diff --git a/modules/java/generator/src/java/highgui+VideoCapture.java b/modules/java/generator/src/java/highgui+VideoCapture.java
index bb71fc041..98b911d78 100644
--- a/modules/java/generator/src/java/highgui+VideoCapture.java
+++ b/modules/java/generator/src/java/highgui+VideoCapture.java
@@ -47,14 +47,14 @@ public class VideoCapture {
     //
 
 /**
- * Returns the specified "VideoCapture" property
+ * Returns the specified "VideoCapture" property.
  *
  * Note: When querying a property that is not supported by the backend used by
  * the "VideoCapture" class, value 0 is returned.
  *
- * @param propId Property identifier. It can be one of the following:
- *   * CV_CAP_PROP_FRAME_WIDTH Width of the frames in the video stream.
- *   * CV_CAP_PROP_FRAME_HEIGHT Height of the frames in the video stream.
+ * @param propId Property identifier; it can be one of the following:
+ *   * CV_CAP_PROP_FRAME_WIDTH width of the frames in the video stream.
+ *   * CV_CAP_PROP_FRAME_HEIGHT height of the frames in the video stream.
  *
  * @see <a href="http://opencv.itseez.com/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-get">org.opencv.highgui.VideoCapture.get</a>
  */
@@ -173,10 +173,10 @@ public class VideoCapture {
 /**
  * Sets a property in the "VideoCapture".
  *
- * @param propId Property identifier. It can be one of the following:
- *   * CV_CAP_PROP_FRAME_WIDTH Width of the frames in the video stream.
- *   * CV_CAP_PROP_FRAME_HEIGHT Height of the frames in the video stream.
- * @param value Value of the property.
+ * @param propId Property identifier; it can be one of the following:
+ *   * CV_CAP_PROP_FRAME_WIDTH width of the frames in the video stream.
+ *   * CV_CAP_PROP_FRAME_HEIGHT height of the frames in the video stream.
+ * @param value value of the property.
  *
  * @see <a href="http://opencv.itseez.com/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-set">org.opencv.highgui.VideoCapture.set</a>
  */

From 7744b1d6005fa3a503b17d2a12acf0a57125b149 Mon Sep 17 00:00:00 2001
From: Andrey Kamaev <andrey.kamaev@itseez.com>
Date: Tue, 28 Aug 2012 14:44:46 +0400
Subject: [PATCH 11/27] Android camera: fix logging macro part 2

---
 modules/highgui/src/cap_android.cpp | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)

diff --git a/modules/highgui/src/cap_android.cpp b/modules/highgui/src/cap_android.cpp
index d8513f240..b67e56dff 100644
--- a/modules/highgui/src/cap_android.cpp
+++ b/modules/highgui/src/cap_android.cpp
@@ -48,15 +48,14 @@
 #include <android/log.h>
 #include <camera_activity.hpp>
 
-//#if !defined(LOGD) && !defined(LOGI) && !defined(LOGE)
+#undef LOG_TAG
 #undef LOGD
 #undef LOGE
 #undef LOGI
-#define LOG_TAG "CV_CAP"
+#define LOG_TAG "OpenCV::camera"
 #define LOGD(...) ((void)__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__))
 #define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__))
 #define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__))
-//#endif
 
 class HighguiAndroidCameraActivity;
 

From 47b9640785cb0fe4dce043cb676e687e74704276 Mon Sep 17 00:00:00 2001
From: Andrey Kamaev <andrey.kamaev@itseez.com>
Date: Tue, 28 Aug 2012 15:06:47 +0400
Subject: [PATCH 12/27] Updated package version in Android samples

---
 samples/android/15-puzzle/AndroidManifest.xml  | 14 +++++++-------
 .../color-blob-detection/AndroidManifest.xml   |  6 +++---
 .../android/face-detection/AndroidManifest.xml | 14 +++++++-------
 .../image-manipulations/AndroidManifest.xml    | 14 +++++++-------
 .../AndroidManifest.xml                        | 18 +++++++++---------
 .../tutorial-1-addopencv/AndroidManifest.xml   | 14 +++++++-------
 .../AndroidManifest.xml                        | 14 +++++++-------
 .../tutorial-3-native/AndroidManifest.xml      | 14 +++++++-------
 .../tutorial-4-mixed/AndroidManifest.xml       | 14 +++++++-------
 9 files changed, 61 insertions(+), 61 deletions(-)

diff --git a/samples/android/15-puzzle/AndroidManifest.xml b/samples/android/15-puzzle/AndroidManifest.xml
index dec508ee7..02a6cc975 100644
--- a/samples/android/15-puzzle/AndroidManifest.xml
+++ b/samples/android/15-puzzle/AndroidManifest.xml
@@ -1,15 +1,15 @@
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="org.opencv.samples.puzzle15"
-      android:versionCode="1"
-      android:versionName="1.0">
+      android:versionCode="21"
+      android:versionName="2.1">
 
     <supports-screens android:resizeable="true"
-                      android:smallScreens="true" 
-                      android:normalScreens="true" 
-                      android:largeScreens="true" 
+                      android:smallScreens="true"
+                      android:normalScreens="true"
+                      android:largeScreens="true"
                       android:anyDensity="true" />
-    
+
     <application android:icon="@drawable/icon" android:label="@string/app_name">
         <activity android:name=".puzzle15Activity"
                   android:label="@string/app_name"
@@ -21,7 +21,7 @@
             </intent-filter>
         </activity>
     </application>
-    
+
     <uses-sdk android:minSdkVersion="8" />
 
     <uses-permission android:name="android.permission.CAMERA"/>
diff --git a/samples/android/color-blob-detection/AndroidManifest.xml b/samples/android/color-blob-detection/AndroidManifest.xml
index 83791f06a..a580be645 100644
--- a/samples/android/color-blob-detection/AndroidManifest.xml
+++ b/samples/android/color-blob-detection/AndroidManifest.xml
@@ -1,8 +1,8 @@
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="org.opencv.example.colorblobdetect"
-    android:versionCode="1"
-    android:versionName="1.0" >
+    android:versionCode="21"
+    android:versionName="2.1" >
 
     <uses-sdk android:minSdkVersion="8" />
 
@@ -23,5 +23,5 @@
     <uses-permission android:name="android.permission.CAMERA"/>
     <uses-feature android:name="android.hardware.camera" />
     <uses-feature android:name="android.hardware.camera.autofocus" />
-    
+
 </manifest>
\ No newline at end of file
diff --git a/samples/android/face-detection/AndroidManifest.xml b/samples/android/face-detection/AndroidManifest.xml
index 34ede0562..285bcb9fa 100644
--- a/samples/android/face-detection/AndroidManifest.xml
+++ b/samples/android/face-detection/AndroidManifest.xml
@@ -1,13 +1,13 @@
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="org.opencv.samples.fd"
-      android:versionCode="1"
-      android:versionName="1.0">
+      android:versionCode="21"
+      android:versionName="2.1">
 
     <supports-screens android:resizeable="true"
-                      android:smallScreens="true" 
-                      android:normalScreens="true" 
-                      android:largeScreens="true" 
+                      android:smallScreens="true"
+                      android:normalScreens="true"
+                      android:largeScreens="true"
                       android:anyDensity="true" />
 
     <application android:label="@string/app_name" android:icon="@drawable/icon">
@@ -21,11 +21,11 @@
             </intent-filter>
         </activity>
     </application>
-    
+
     <uses-sdk android:minSdkVersion="8" />
 
     <uses-permission android:name="android.permission.CAMERA"/>
     <uses-feature android:name="android.hardware.camera" />
     <uses-feature android:name="android.hardware.camera.autofocus" />
 
-</manifest> 
+</manifest>
diff --git a/samples/android/image-manipulations/AndroidManifest.xml b/samples/android/image-manipulations/AndroidManifest.xml
index ab3200318..72df75e44 100644
--- a/samples/android/image-manipulations/AndroidManifest.xml
+++ b/samples/android/image-manipulations/AndroidManifest.xml
@@ -1,13 +1,13 @@
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="org.opencv.samples.imagemanipulations"
-      android:versionCode="1"
-      android:versionName="1.0">
+      android:versionCode="21"
+      android:versionName="2.1">
 
     <supports-screens android:resizeable="true"
-                      android:smallScreens="true" 
-                      android:normalScreens="true" 
-                      android:largeScreens="true" 
+                      android:smallScreens="true"
+                      android:normalScreens="true"
+                      android:largeScreens="true"
                       android:anyDensity="true" />
 
     <application android:label="@string/app_name" android:icon="@drawable/icon">
@@ -21,11 +21,11 @@
             </intent-filter>
         </activity>
     </application>
-    
+
     <uses-sdk android:minSdkVersion="8" />
 
     <uses-permission android:name="android.permission.CAMERA"/>
     <uses-feature android:name="android.hardware.camera" />
     <uses-feature android:name="android.hardware.camera.autofocus" />
 
-</manifest> 
+</manifest>
diff --git a/samples/android/tutorial-0-androidcamera/AndroidManifest.xml b/samples/android/tutorial-0-androidcamera/AndroidManifest.xml
index 51aa236ed..714b0095a 100644
--- a/samples/android/tutorial-0-androidcamera/AndroidManifest.xml
+++ b/samples/android/tutorial-0-androidcamera/AndroidManifest.xml
@@ -1,21 +1,21 @@
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="org.opencv.samples.tutorial0"
-      android:versionCode="1"
-      android:versionName="1.0">
+      android:versionCode="21"
+      android:versionName="2.1">
 
     <supports-screens android:resizeable="true"
-                      android:smallScreens="true" 
-                      android:normalScreens="true" 
-                      android:largeScreens="true" 
+                      android:smallScreens="true"
+                      android:normalScreens="true"
+                      android:largeScreens="true"
                       android:anyDensity="true" />
 
     <uses-sdk android:minSdkVersion="8"/>
-    
+
     <uses-permission android:name="android.permission.CAMERA"/>
     <uses-feature android:name="android.hardware.camera" />
     <uses-feature android:name="android.hardware.camera.autofocus" />
-    
+
     <application android:label="@string/app_name" android:icon="@drawable/icon">
         <activity android:name="Sample0Base"
                   android:label="@string/app_name"
@@ -27,6 +27,6 @@
             </intent-filter>
         </activity>
     </application>
-    
 
-</manifest> 
+
+</manifest>
diff --git a/samples/android/tutorial-1-addopencv/AndroidManifest.xml b/samples/android/tutorial-1-addopencv/AndroidManifest.xml
index 438f09624..51cc50f7f 100644
--- a/samples/android/tutorial-1-addopencv/AndroidManifest.xml
+++ b/samples/android/tutorial-1-addopencv/AndroidManifest.xml
@@ -1,13 +1,13 @@
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="org.opencv.samples.tutorial1"
-      android:versionCode="1"
-      android:versionName="1.0">
+      android:versionCode="21"
+      android:versionName="2.1">
 
     <supports-screens android:resizeable="true"
-                      android:smallScreens="true" 
-                      android:normalScreens="true" 
-                      android:largeScreens="true" 
+                      android:smallScreens="true"
+                      android:normalScreens="true"
+                      android:largeScreens="true"
                       android:anyDensity="true" />
 
     <application android:label="@string/app_name" android:icon="@drawable/icon">
@@ -21,11 +21,11 @@
             </intent-filter>
         </activity>
     </application>
-    
+
     <uses-sdk android:minSdkVersion="8" />
 
     <uses-permission android:name="android.permission.CAMERA"/>
     <uses-feature android:name="android.hardware.camera" />
     <uses-feature android:name="android.hardware.camera.autofocus" />
 
-</manifest> 
+</manifest>
diff --git a/samples/android/tutorial-2-opencvcamera/AndroidManifest.xml b/samples/android/tutorial-2-opencvcamera/AndroidManifest.xml
index accc3b2cf..7daacd164 100644
--- a/samples/android/tutorial-2-opencvcamera/AndroidManifest.xml
+++ b/samples/android/tutorial-2-opencvcamera/AndroidManifest.xml
@@ -1,13 +1,13 @@
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="org.opencv.samples.tutorial2"
-      android:versionCode="1"
-      android:versionName="1.0">
+      android:versionCode="21"
+      android:versionName="2.1">
 
     <supports-screens android:resizeable="true"
-                      android:smallScreens="true" 
-                      android:normalScreens="true" 
-                      android:largeScreens="true" 
+                      android:smallScreens="true"
+                      android:normalScreens="true"
+                      android:largeScreens="true"
                       android:anyDensity="true" />
 
     <application android:label="@string/app_name" android:icon="@drawable/icon">
@@ -21,11 +21,11 @@
             </intent-filter>
         </activity>
     </application>
-    
+
     <uses-sdk android:minSdkVersion="8" />
 
     <uses-permission android:name="android.permission.CAMERA"/>
     <uses-feature android:name="android.hardware.camera" />
     <uses-feature android:name="android.hardware.camera.autofocus" />
 
-</manifest> 
+</manifest>
diff --git a/samples/android/tutorial-3-native/AndroidManifest.xml b/samples/android/tutorial-3-native/AndroidManifest.xml
index 145048e7f..8ee38142b 100644
--- a/samples/android/tutorial-3-native/AndroidManifest.xml
+++ b/samples/android/tutorial-3-native/AndroidManifest.xml
@@ -1,13 +1,13 @@
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="org.opencv.samples.tutorial3"
-      android:versionCode="1"
-      android:versionName="1.0">
+      android:versionCode="21"
+      android:versionName="2.1">
 
     <supports-screens android:resizeable="true"
-                      android:smallScreens="true" 
-                      android:normalScreens="true" 
-                      android:largeScreens="true" 
+                      android:smallScreens="true"
+                      android:normalScreens="true"
+                      android:largeScreens="true"
                       android:anyDensity="true" />
 
     <application android:label="@string/app_name" android:icon="@drawable/icon">
@@ -21,11 +21,11 @@
             </intent-filter>
         </activity>
     </application>
-    
+
     <uses-sdk android:minSdkVersion="8" />
 
     <uses-permission android:name="android.permission.CAMERA"/>
     <uses-feature android:name="android.hardware.camera" />
     <uses-feature android:name="android.hardware.camera.autofocus" />
 
-</manifest> 
+</manifest>
diff --git a/samples/android/tutorial-4-mixed/AndroidManifest.xml b/samples/android/tutorial-4-mixed/AndroidManifest.xml
index 3201f7c04..524c76399 100644
--- a/samples/android/tutorial-4-mixed/AndroidManifest.xml
+++ b/samples/android/tutorial-4-mixed/AndroidManifest.xml
@@ -1,13 +1,13 @@
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="org.opencv.samples.tutorial4"
-      android:versionCode="1"
-      android:versionName="1.0">
+      android:versionCode="21"
+      android:versionName="2.1">
 
     <supports-screens android:resizeable="true"
-                      android:smallScreens="true" 
-                      android:normalScreens="true" 
-                      android:largeScreens="true" 
+                      android:smallScreens="true"
+                      android:normalScreens="true"
+                      android:largeScreens="true"
                       android:anyDensity="true" />
 
     <application android:label="@string/app_name" android:icon="@drawable/icon">
@@ -21,11 +21,11 @@
             </intent-filter>
         </activity>
     </application>
-    
+
     <uses-sdk android:minSdkVersion="8" />
 
     <uses-permission android:name="android.permission.CAMERA"/>
     <uses-feature android:name="android.hardware.camera" />
     <uses-feature android:name="android.hardware.camera.autofocus" />
 
-</manifest> 
+</manifest>

From f56432559e9b7607fb70ed0a71b65c4337a82b1e Mon Sep 17 00:00:00 2001
From: Vincent Rabaud <vrabaud@willowgarage.com>
Date: Fri, 24 Aug 2012 11:26:34 +0200
Subject: [PATCH 13/27] add conversion from/to Matx

---
 modules/core/include/opencv2/core/eigen.hpp | 103 ++++++++++++++++++++
 1 file changed, 103 insertions(+)

diff --git a/modules/core/include/opencv2/core/eigen.hpp b/modules/core/include/opencv2/core/eigen.hpp
index 3051486ea..49bd36ba3 100644
--- a/modules/core/include/opencv2/core/eigen.hpp
+++ b/modules/core/include/opencv2/core/eigen.hpp
@@ -74,6 +74,21 @@ void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCo
     }
 }
 
+// Matx case
+template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols>
+void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src,
+               Matx<_Tp, _rows, _cols>& dst )
+{
+    if( !(src.Flags & Eigen::RowMajorBit) )
+    {
+        dst = Matx<_Tp, _cols, _rows>(static_cast<const _Tp*>(src.data())).t();
+    }
+    else
+    {
+        dst = Matx<_Tp, _rows, _cols>(static_cast<const _Tp*>(src.data()));
+    }
+}
+
 template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols>
 void cv2eigen( const Mat& src,
                Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst )
@@ -103,6 +118,27 @@ void cv2eigen( const Mat& src,
     }
 }
 
+// Matx case
+template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols>
+void cv2eigen( const Matx<_Tp, _rows, _cols>& src,
+               Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst )
+{
+    if( !(dst.Flags & Eigen::RowMajorBit) )
+    {
+        Mat _dst(_cols, _rows, DataType<_Tp>::type,
+                 dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
+        transpose(src, _dst);
+        CV_DbgAssert(_dst.data == (uchar*)dst.data());
+    }
+    else
+    {
+        Mat _dst(_rows, _cols, DataType<_Tp>::type,
+                 dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
+        Mat(src).copyTo(_dst);
+        CV_DbgAssert(_dst.data == (uchar*)dst.data());
+    }
+}
+
 template<typename _Tp>
 void cv2eigen( const Mat& src,
                Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst )
@@ -132,6 +168,27 @@ void cv2eigen( const Mat& src,
     }
 }
 
+// Matx case
+template<typename _Tp, int _rows, int _cols>
+void cv2eigen( const Matx<_Tp, _rows, _cols>& src,
+               Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst )
+{
+    dst.resize(_rows, _cols);
+    if( !(dst.Flags & Eigen::RowMajorBit) )
+    {
+        Mat _dst(_cols, _rows, DataType<_Tp>::type,
+             dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
+        transpose(src, _dst);
+        CV_DbgAssert(_dst.data == (uchar*)dst.data());
+    }
+    else
+    {
+        Mat _dst(_rows, _cols, DataType<_Tp>::type,
+                 dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
+        Mat(src).copyTo(_dst);
+        CV_DbgAssert(_dst.data == (uchar*)dst.data());
+    }
+}
 
 template<typename _Tp>
 void cv2eigen( const Mat& src,
@@ -159,6 +216,29 @@ void cv2eigen( const Mat& src,
     }
 }
 
+// Matx case
+template<typename _Tp, int _rows>
+void cv2eigen( const Matx<_Tp, _rows, 1>& src,
+               Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst )
+{
+    dst.resize(_rows);
+
+    if( !(dst.Flags & Eigen::RowMajorBit) )
+    {
+        Mat _dst(1, _rows, DataType<_Tp>::type,
+                 dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
+        transpose(src, _dst);
+        CV_DbgAssert(_dst.data == (uchar*)dst.data());
+    }
+    else
+    {
+        Mat _dst(_rows, 1, DataType<_Tp>::type,
+                 dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
+        src.copyTo(_dst);
+        CV_DbgAssert(_dst.data == (uchar*)dst.data());
+    }
+}
+
 
 template<typename _Tp>
 void cv2eigen( const Mat& src,
@@ -185,6 +265,29 @@ void cv2eigen( const Mat& src,
     }
 }
 
+//Matx
+template<typename _Tp, int _cols>
+void cv2eigen( const Matx<_Tp, 1, _cols>& src,
+               Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst )
+{
+    dst.resize(_cols);
+    if( !(dst.Flags & Eigen::RowMajorBit) )
+    {
+        Mat _dst(_cols, 1, DataType<_Tp>::type,
+                 dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
+        transpose(src, _dst);
+        CV_DbgAssert(_dst.data == (uchar*)dst.data());
+    }
+    else
+    {
+        Mat _dst(1, _cols, DataType<_Tp>::type,
+                 dst.data(), (size_t)(dst.stride()*sizeof(_Tp)));
+        Mat(src).copyTo(_dst);
+        CV_DbgAssert(_dst.data == (uchar*)dst.data());
+    }
+}
+
+
 }
 
 #endif

From dc6fa94118860ddbb31f1141834b90af14afc3f9 Mon Sep 17 00:00:00 2001
From: Vsevolod Glumov <seva17@gmail.com>
Date: Tue, 28 Aug 2012 15:49:50 +0400
Subject: [PATCH 14/27] Improved javadoc comments.

---
 .../src/java/android+AsyncServiceHelper.java   |  2 +-
 .../src/java/android+BaseLoaderCallback.java   |  2 +-
 .../java/android+LoaderCallbackInterface.java  | 12 ++++++------
 .../src/java/android+OpenCVLoader.java         | 10 +++++-----
 .../java/generator/src/java/android+Utils.java | 18 +++++++++---------
 .../generator/src/java/core+TermCriteria.java  | 14 +++++++-------
 .../src/java/engine+OpenCVEngineInterface.aidl |  8 ++++----
 .../src/java/highgui+VideoCapture.java         |  4 ++--
 8 files changed, 35 insertions(+), 35 deletions(-)

diff --git a/modules/java/generator/src/java/android+AsyncServiceHelper.java b/modules/java/generator/src/java/android+AsyncServiceHelper.java
index 8069f4672..b5487b9c6 100644
--- a/modules/java/generator/src/java/android+AsyncServiceHelper.java
+++ b/modules/java/generator/src/java/android+AsyncServiceHelper.java
@@ -263,7 +263,7 @@ class AsyncServiceHelper
             }
             else
             {
-                // If dependencies list is not defined or empty.
+                // If the dependencies list is not defined or empty.
                 String AbsLibraryPath = Path + File.separator + "libopencv_java.so";
                 result &= loadLibrary(AbsLibraryPath);
             }
diff --git a/modules/java/generator/src/java/android+BaseLoaderCallback.java b/modules/java/generator/src/java/android+BaseLoaderCallback.java
index 220ca5e01..4fb5a23ae 100644
--- a/modules/java/generator/src/java/android+BaseLoaderCallback.java
+++ b/modules/java/generator/src/java/android+BaseLoaderCallback.java
@@ -40,7 +40,7 @@ public abstract class BaseLoaderCallback implements LoaderCallbackInterface {
 
                 RestartMessage.show();
             } break;
-            /** OpenCV loader cannot start Google Play Market. **/
+            /** OpenCV loader can not start Google Play Market. **/
             case LoaderCallbackInterface.MARKET_ERROR:
             {
                 Log.d(TAG, "Google Play service is not installed! You can get it here");
diff --git a/modules/java/generator/src/java/android+LoaderCallbackInterface.java b/modules/java/generator/src/java/android+LoaderCallbackInterface.java
index 56cdf1519..0d932c7cd 100644
--- a/modules/java/generator/src/java/android+LoaderCallbackInterface.java
+++ b/modules/java/generator/src/java/android+LoaderCallbackInterface.java
@@ -18,7 +18,7 @@ public interface LoaderCallbackInterface
      */
     static final int MARKET_ERROR = 2;
     /**
-     * OpenCV library installation has been canceled by user.
+     * OpenCV library installation has been canceled by the user.
      */
     static final int INSTALL_CANCELED = 3;
     /**
@@ -26,19 +26,19 @@ public interface LoaderCallbackInterface
      */
     static final int INCOMPATIBLE_MANAGER_VERSION = 4;
     /**
-     * OpenCV library initialization failed.
+     * OpenCV library initialization has failed.
      */
     static final int INIT_FAILED = 0xff;
 
     /**
-     * This callback method is called after OpenCV library initialization.
-     * @param status Status of initialization (see Initialization status constants).
+     * Callback method, called after OpenCV library initialization.
+     * @param status status of initialization (see initialization status constants).
      */
     public void onManagerConnected(int status);
 
     /**
-     * This callback method is called in case the package installation is needed.
-     * @param callback Answer object with approve and cancel methods and the package description.
+     * Callback method, called in case the package installation is needed.
+     * @param callback answer object with approve and cancel methods and the package description.
      */
     public void onPackageInstall(InstallCallbackInterface callback);
 };
diff --git a/modules/java/generator/src/java/android+OpenCVLoader.java b/modules/java/generator/src/java/android+OpenCVLoader.java
index 376d04c73..b3025a9aa 100644
--- a/modules/java/generator/src/java/android+OpenCVLoader.java
+++ b/modules/java/generator/src/java/android+OpenCVLoader.java
@@ -14,7 +14,7 @@ public class OpenCVLoader
 
     /**
      * Loads and initializes OpenCV library from current application package. Roughly, it's an analog of system.loadLibrary("opencv_java").
-     * @return Returns true is initialization of OpenCV was successful.
+     * @return returns true is initialization of OpenCV was successful.
      */
     public static boolean initDebug()
     {
@@ -23,10 +23,10 @@ public class OpenCVLoader
 
     /**
      * Loads and initializes OpenCV library using OpenCV Engine service.
-     * @param Version OpenCV Library version.
-     * @param AppContext Application context for connecting to service.
-     * @param Callback Object, that implements LoaderCallbackInterface for handling Connection status.
-     * @return Returns true if initialization of OpenCV is successful.
+     * @param Version OpenCV library version.
+     * @param AppContext application context for connecting to the service.
+     * @param Callback object, that implements LoaderCallbackInterface for handling the connection status.
+     * @return returns true if initialization of OpenCV is successful.
      */
     public static boolean initAsync(String Version, Context AppContext,
             LoaderCallbackInterface Callback)
diff --git a/modules/java/generator/src/java/android+Utils.java b/modules/java/generator/src/java/android+Utils.java
index ceecf3a63..e40630b83 100644
--- a/modules/java/generator/src/java/android+Utils.java
+++ b/modules/java/generator/src/java/android+Utils.java
@@ -77,13 +77,13 @@ public class Utils {
      * Converts Android Bitmap to OpenCV Mat.
      * <p>
      * This function converts an Android Bitmap image to the OpenCV Mat.
-     * <br>The 'ARGB_8888' and 'RGB_565' input Bitmap formats are supported.
+     * <br>'ARGB_8888' and 'RGB_565' input Bitmap formats are supported.
      * <br>The output Mat is always created of the same size as the input Bitmap and of the 'CV_8UC4' type,
      * it keeps the image in RGBA format.
      * <br>This function throws an exception if the conversion fails.
      * @param bmp is a valid input Bitmap object of the type 'ARGB_8888' or 'RGB_565'.
      * @param mat is a valid output Mat object, it will be reallocated if needed, so it may be empty.
-     * @param unPremultiplyAlpha is a flag if the bitmap needs to be converted from alpha premultiplied format (like Android keeps 'ARGB_8888' ones) to regular one. This flag is ignored for 'RGB_565' bitmaps.
+     * @param unPremultiplyAlpha is a flag, that determines, whether the bitmap needs to be converted from alpha premultiplied format (like Android keeps 'ARGB_8888' ones) to regular one; this flag is ignored for 'RGB_565' bitmaps.
      */
     public static void bitmapToMat(Bitmap bmp, Mat mat, boolean unPremultiplyAlpha) {
         if (bmp == null)
@@ -96,7 +96,7 @@ public class Utils {
     /**
      * Short form of the bitmapToMat(bmp, mat, unPremultiplyAlpha=false).
      * @param bmp is a valid input Bitmap object of the type 'ARGB_8888' or 'RGB_565'.
-     * @param mat is a valid output Mat object, it will be reallocated if needed, so it's possible to pass an empty Mat.
+     * @param mat is a valid output Mat object, it will be reallocated if needed, so Mat may be empty.
      */
     public static void bitmapToMat(Bitmap bmp, Mat mat) {
     	bitmapToMat(bmp, mat, false);
@@ -106,14 +106,14 @@ public class Utils {
     /**
      * Converts OpenCV Mat to Android Bitmap.
      * <p>
-     * <br>The function converts an image in the OpenCV Mat representation to the Android Bitmap.
+     * <br>This function converts an image in the OpenCV Mat representation to the Android Bitmap.
      * <br>The input Mat object has to be of the types 'CV_8UC1' (gray-scale), 'CV_8UC3' (RGB) or 'CV_8UC4' (RGBA).
      * <br>The output Bitmap object has to be of the same size as the input Mat and of the types 'ARGB_8888' or 'RGB_565'.
-     * <br>The function throws an exception if the conversion fails.
+     * <br>This function throws an exception if the conversion fails.
      *
-     * @param mat is a valid input Mat object of the types 'CV_8UC1', 'CV_8UC3' or 'CV_8UC4'.
-     * @param bmp is a valid Bitmap object of the same size as the Mat m and of type 'ARGB_8888' or 'RGB_565'.
-     * @param premultiplyAlpha is a flag if the Mat needs to be converted to alpha premultiplied format (like Android keeps 'ARGB_8888' bitmaps). The flag is ignored for 'RGB_565' bitmaps.
+     * @param mat is a valid input Mat object of types 'CV_8UC1', 'CV_8UC3' or 'CV_8UC4'.
+     * @param bmp is a valid Bitmap object of the same size as the Mat and of type 'ARGB_8888' or 'RGB_565'.
+     * @param premultiplyAlpha is a flag, that determines, whether the Mat needs to be converted to alpha premultiplied format (like Android keeps 'ARGB_8888' bitmaps); the flag is ignored for 'RGB_565' bitmaps.
      */
     public static void matToBitmap(Mat mat, Bitmap bmp, boolean premultiplyAlpha) {
         if (mat == null)
@@ -126,7 +126,7 @@ public class Utils {
     /**
      * Short form of the <b>matToBitmap(mat, bmp, premultiplyAlpha=false)</b>
      * @param mat is a valid input Mat object of the types 'CV_8UC1', 'CV_8UC3' or 'CV_8UC4'.
-     * @param bmp is a valid Bitmap object of the same size as the Mat m and of type 'ARGB_8888' or 'RGB_565'.
+     * @param bmp is a valid Bitmap object of the same size as the Mat and of type 'ARGB_8888' or 'RGB_565'.
      */
     public static void matToBitmap(Mat mat, Bitmap bmp) {
     	matToBitmap(mat, bmp, false);
diff --git a/modules/java/generator/src/java/core+TermCriteria.java b/modules/java/generator/src/java/core+TermCriteria.java
index 3c4a8debe..aaee88d78 100644
--- a/modules/java/generator/src/java/core+TermCriteria.java
+++ b/modules/java/generator/src/java/core+TermCriteria.java
@@ -4,15 +4,15 @@ package org.opencv.core;
 public class TermCriteria {
 
     /**
-     * the maximum of iterations or elements to compute
+     * The maximum number of iterations or elements to compute
      */
     public static final int COUNT = 1;
     /**
-     * the maximum of iterations or elements to compute
+     * The maximum number of iterations or elements to compute
      */
     public static final int MAX_ITER = COUNT;
     /**
-     * the desired accuracy threshold or change in parameters at which the iterative algorithm stops.
+     * The desired accuracy threshold or change in parameters at which the iterative algorithm is terminated.
      */
     public static final int EPS = 2;
 
@@ -24,11 +24,11 @@ public class TermCriteria {
      * Termination criteria for iterative algorithms.
      * 
      * @param type
-     *            the type of termination criteria: COUNT, EPS or COUNT + EPS
+     *            the type of termination criteria: COUNT, EPS or COUNT + EPS.
      * @param maxCount
-     *            the maximum number of iterations/elements
+     *            the maximum number of iterations/elements.
      * @param epsilon
-     *            the desired accuracy
+     *            the desired accuracy.
      */
     public TermCriteria(int type, int maxCount, double epsilon) {
         this.type = type;
@@ -37,7 +37,7 @@ public class TermCriteria {
     }
 
     /**
-     * Termination criteria for iterative algorithms
+     * Termination criteria for iterative algorithms.
      */
     public TermCriteria() {
         this(0, 0, 0.0);
diff --git a/modules/java/generator/src/java/engine+OpenCVEngineInterface.aidl b/modules/java/generator/src/java/engine+OpenCVEngineInterface.aidl
index 7bf967fd8..7949b3160 100644
--- a/modules/java/generator/src/java/engine+OpenCVEngineInterface.aidl
+++ b/modules/java/generator/src/java/engine+OpenCVEngineInterface.aidl
@@ -6,28 +6,28 @@ package org.opencv.engine;
 interface OpenCVEngineInterface
 {
 	/**
-	* @return Returns service version.
+	* @return returns service version.
 	*/
 	int getEngineVersion();
 
 	/**
 	* Finds an installed OpenCV library.
 	* @param OpenCV version.
-	* @return Returns path to OpenCV native libs or an empty string if OpenCV can not be found.
+	* @return returns path to OpenCV native libs or an empty string if OpenCV can not be found.
 	*/
 	String getLibPathByVersion(String version);
 
 	/**
 	* Tries to install defined version of OpenCV from Google Play Market.
 	* @param OpenCV version.
-	* @return Returns true if installation was successful or OpenCV package has been already installed.
+	* @return returns true if installation was successful or OpenCV package has been already installed.
 	*/
 	boolean installVersion(String version);
  
 	/**
 	* Returns list of libraries in loading order, separated by semicolon.
 	* @param OpenCV version.
-	* @return Returns names of OpenCV libraries, separated by semicolon.
+	* @return returns names of OpenCV libraries, separated by semicolon.
 	*/
 	String getLibraryList(String version);
 }
\ No newline at end of file
diff --git a/modules/java/generator/src/java/highgui+VideoCapture.java b/modules/java/generator/src/java/highgui+VideoCapture.java
index 98b911d78..b8569bb9c 100644
--- a/modules/java/generator/src/java/highgui+VideoCapture.java
+++ b/modules/java/generator/src/java/highgui+VideoCapture.java
@@ -52,7 +52,7 @@ public class VideoCapture {
  * Note: When querying a property that is not supported by the backend used by
  * the "VideoCapture" class, value 0 is returned.
  *
- * @param propId Property identifier; it can be one of the following:
+ * @param propId property identifier; it can be one of the following:
  *   * CV_CAP_PROP_FRAME_WIDTH width of the frames in the video stream.
  *   * CV_CAP_PROP_FRAME_HEIGHT height of the frames in the video stream.
  *
@@ -173,7 +173,7 @@ public class VideoCapture {
 /**
  * Sets a property in the "VideoCapture".
  *
- * @param propId Property identifier; it can be one of the following:
+ * @param propId property identifier; it can be one of the following:
  *   * CV_CAP_PROP_FRAME_WIDTH width of the frames in the video stream.
  *   * CV_CAP_PROP_FRAME_HEIGHT height of the frames in the video stream.
  * @param value value of the property.

From 18fc11bc0464a8c84ea93dcb77c4957e715f1779 Mon Sep 17 00:00:00 2001
From: Corentin Wallez <corentin@wallez.net>
Date: Tue, 21 Aug 2012 23:45:12 +0200
Subject: [PATCH 15/27] Fix fixed-point arithmetics in FREAK::meanIntensity

---
 modules/features2d/src/freak.cpp | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/modules/features2d/src/freak.cpp b/modules/features2d/src/freak.cpp
index 26ded8547..4e1e6411f 100644
--- a/modules/features2d/src/freak.cpp
+++ b/modules/features2d/src/freak.cpp
@@ -455,7 +455,6 @@ uchar FREAK::meanIntensity( const cv::Mat& image, const cv::Mat& integral,
     const float radius = FreakPoint.sigma;
 
     // calculate output:
-    int ret_val;
     if( radius < 0.5 ) {
         // interpolation multipliers:
         const int r_x = static_cast<int>((xf-x)*1024);
@@ -463,6 +462,7 @@ uchar FREAK::meanIntensity( const cv::Mat& image, const cv::Mat& integral,
         const int r_x_1 = (1024-r_x);
         const int r_y_1 = (1024-r_y);
         uchar* ptr = image.data+x+y*imagecols;
+        unsigned int ret_val;
         // linear interpolation:
         ret_val = (r_x_1*r_y_1*int(*ptr));
         ptr++;
@@ -471,7 +471,9 @@ uchar FREAK::meanIntensity( const cv::Mat& image, const cv::Mat& integral,
         ret_val += (r_x*r_y*int(*ptr));
         ptr--;
         ret_val += (r_x_1*r_y*int(*ptr));
-        return static_cast<uchar>((ret_val+512)/1024);
+        //return the rounded mean
+        ret_val += 2 * 1024 * 1024;
+        return static_cast<uchar>(ret_val / (4 * 1024 * 1024));
     }
 
     // expected case:
@@ -481,6 +483,7 @@ uchar FREAK::meanIntensity( const cv::Mat& image, const cv::Mat& integral,
     const int y_top = int(yf-radius+0.5);
     const int x_right = int(xf+radius+1.5);//integral image is 1px wider
     const int y_bottom = int(yf+radius+1.5);//integral image is 1px higher
+    int ret_val;
 
     ret_val = integral.at<int>(y_bottom,x_right);//bottom right corner
     ret_val -= integral.at<int>(y_bottom,x_left);

From 8dcf52c90b1340b9aadd3c8b7eae50302efb7b4c Mon Sep 17 00:00:00 2001
From: Leonid Beynenson <Leonid.Beynenson@itseez.com>
Date: Tue, 28 Aug 2012 17:44:33 +0400
Subject: [PATCH 16/27] Added possibility to make subfolders in modules'
 folders "src/".

---
 cmake/OpenCVModule.cmake | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/cmake/OpenCVModule.cmake b/cmake/OpenCVModule.cmake
index 018a46730..72c7fc830 100644
--- a/cmake/OpenCVModule.cmake
+++ b/cmake/OpenCVModule.cmake
@@ -422,8 +422,8 @@ endmacro()
 # Usage:
 # ocv_glob_module_sources(<extra sources&headers in the same format as used in ocv_set_module_sources>)
 macro(ocv_glob_module_sources)
-  file(GLOB lib_srcs "src/*.cpp")
-  file(GLOB lib_int_hdrs "src/*.hpp" "src/*.h")
+  file(GLOB_RECURSE lib_srcs "src/*.cpp")
+  file(GLOB_RECURSE lib_int_hdrs "src/*.hpp" "src/*.h")
   file(GLOB lib_hdrs "include/opencv2/${name}/*.hpp" "include/opencv2/${name}/*.h")
   file(GLOB lib_hdrs_detail "include/opencv2/${name}/detail/*.hpp" "include/opencv2/${name}/detail/*.h")
 

From aa2524f41e509dc990388ca4c4a343117ffec20b Mon Sep 17 00:00:00 2001
From: Leonid Beynenson <Leonid.Beynenson@itseez.com>
Date: Tue, 28 Aug 2012 17:46:45 +0400
Subject: [PATCH 17/27] Changed the file .gitignore (added vim swap files and
 tag files)

---
 .gitignore | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/.gitignore b/.gitignore
index dd15dac16..0a19f3cee 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,3 +3,6 @@
 refman.rst
 OpenCV4Tegra/
 *.user
+.sw[a-z]
+.*.swp
+tags

From 633a8bfaccfad935f7bf2f969c97dfe3091109ac Mon Sep 17 00:00:00 2001
From: Vadim Pisarevsky <vadim.pisarevsky@itseez.com>
Date: Tue, 28 Aug 2012 18:15:14 +0400
Subject: [PATCH 18/27] fixed many warnings (modified pull request 13)

---
 3rdparty/libtiff/tif_stream.cxx               |  1 +
 apps/traincascade/HOGfeatures.h               |  8 +--
 apps/traincascade/lbpfeatures.h               | 20 ++++----
 modules/contrib/src/chamfermatching.cpp       | 51 ++++++++++---------
 .../include/opencv2/features2d/features2d.hpp |  5 +-
 modules/features2d/src/fast.cpp               |  5 ++
 modules/gpu/perf/perf_imgproc.cpp             |  8 +--
 modules/gpu/perf/perf_labeling.cpp            |  2 +-
 modules/highgui/src/cap_ffmpeg_impl.hpp       |  2 +-
 modules/ml/src/tree.cpp                       |  2 +-
 modules/objdetect/src/cascadedetect.hpp       | 44 ++++++++--------
 modules/stitching/src/seam_finders.cpp        |  4 +-
 modules/video/src/bgfg_gmg.cpp                |  2 +-
 13 files changed, 82 insertions(+), 72 deletions(-)

diff --git a/3rdparty/libtiff/tif_stream.cxx b/3rdparty/libtiff/tif_stream.cxx
index 163447ebd..7d0f3c036 100644
--- a/3rdparty/libtiff/tif_stream.cxx
+++ b/3rdparty/libtiff/tif_stream.cxx
@@ -28,6 +28,7 @@
  * TIFF Library UNIX-specific Routines.
  */
 #include "tiffiop.h"
+#include "tiffio.hxx"
 #include <iostream>
 
 #ifndef __VMS
diff --git a/apps/traincascade/HOGfeatures.h b/apps/traincascade/HOGfeatures.h
index 56b269e22..3de3ab2ff 100644
--- a/apps/traincascade/HOGfeatures.h
+++ b/apps/traincascade/HOGfeatures.h
@@ -65,11 +65,11 @@ inline float CvHOGEvaluator::Feature::calc( const vector<Mat>& _hists, const Mat
     int binIdx = featComponent % N_BINS;
     int cellIdx = featComponent / N_BINS;
 
-    const float *hist = _hists[binIdx].ptr<float>((int)y);
-    res = hist[fastRect[cellIdx].p0] - hist[fastRect[cellIdx].p1] - hist[fastRect[cellIdx].p2] + hist[fastRect[cellIdx].p3];
+    const float *phist = _hists[binIdx].ptr<float>((int)y);
+    res = phist[fastRect[cellIdx].p0] - phist[fastRect[cellIdx].p1] - phist[fastRect[cellIdx].p2] + phist[fastRect[cellIdx].p3];
 
-    const float *normSum = _normSum.ptr<float>((int)y);
-    normFactor = (float)(normSum[fastRect[0].p0] - normSum[fastRect[1].p1] - normSum[fastRect[2].p2] + normSum[fastRect[3].p3]);
+    const float *pnormSum = _normSum.ptr<float>((int)y);
+    normFactor = (float)(pnormSum[fastRect[0].p0] - pnormSum[fastRect[1].p1] - pnormSum[fastRect[2].p2] + pnormSum[fastRect[3].p3]);
     res = (res > 0.001f) ? ( res / (normFactor + 0.001f) ) : 0.f; //for cutting negative values, which apper due to floating precision
 
     return res;
diff --git a/apps/traincascade/lbpfeatures.h b/apps/traincascade/lbpfeatures.h
index 7c41f9097..5937f0850 100644
--- a/apps/traincascade/lbpfeatures.h
+++ b/apps/traincascade/lbpfeatures.h
@@ -41,17 +41,17 @@ protected:
 
 inline uchar CvLBPEvaluator::Feature::calc(const Mat &_sum, size_t y) const
 {
-    const int* sum = _sum.ptr<int>((int)y);
-    int cval = sum[p[5]] - sum[p[6]] - sum[p[9]] + sum[p[10]];
+    const int* psum = _sum.ptr<int>((int)y);
+    int cval = psum[p[5]] - psum[p[6]] - psum[p[9]] + psum[p[10]];
 
-    return (uchar)((sum[p[0]] - sum[p[1]] - sum[p[4]] + sum[p[5]] >= cval ? 128 : 0) |   // 0
-        (sum[p[1]] - sum[p[2]] - sum[p[5]] + sum[p[6]] >= cval ? 64 : 0) |    // 1
-        (sum[p[2]] - sum[p[3]] - sum[p[6]] + sum[p[7]] >= cval ? 32 : 0) |    // 2
-        (sum[p[6]] - sum[p[7]] - sum[p[10]] + sum[p[11]] >= cval ? 16 : 0) |  // 5
-        (sum[p[10]] - sum[p[11]] - sum[p[14]] + sum[p[15]] >= cval ? 8 : 0) | // 8
-        (sum[p[9]] - sum[p[10]] - sum[p[13]] + sum[p[14]] >= cval ? 4 : 0) |  // 7
-        (sum[p[8]] - sum[p[9]] - sum[p[12]] + sum[p[13]] >= cval ? 2 : 0) |   // 6
-        (sum[p[4]] - sum[p[5]] - sum[p[8]] + sum[p[9]] >= cval ? 1 : 0));     // 3
+    return (uchar)((psum[p[0]] - psum[p[1]] - psum[p[4]] + psum[p[5]] >= cval ? 128 : 0) |   // 0
+        (psum[p[1]] - psum[p[2]] - psum[p[5]] + psum[p[6]] >= cval ? 64 : 0) |    // 1
+        (psum[p[2]] - psum[p[3]] - psum[p[6]] + psum[p[7]] >= cval ? 32 : 0) |    // 2
+        (psum[p[6]] - psum[p[7]] - psum[p[10]] + psum[p[11]] >= cval ? 16 : 0) |  // 5
+        (psum[p[10]] - psum[p[11]] - psum[p[14]] + psum[p[15]] >= cval ? 8 : 0) | // 8
+        (psum[p[9]] - psum[p[10]] - psum[p[13]] + psum[p[14]] >= cval ? 4 : 0) |  // 7
+        (psum[p[8]] - psum[p[9]] - psum[p[12]] + psum[p[13]] >= cval ? 2 : 0) |   // 6
+        (psum[p[4]] - psum[p[5]] - psum[p[8]] + psum[p[9]] >= cval ? 1 : 0));     // 3
 }
 
 #endif
diff --git a/modules/contrib/src/chamfermatching.cpp b/modules/contrib/src/chamfermatching.cpp
index 09d589e5d..386b5ef16 100644
--- a/modules/contrib/src/chamfermatching.cpp
+++ b/modules/contrib/src/chamfermatching.cpp
@@ -100,8 +100,8 @@ private:
         float max_scale_;
 
     public:
-        SlidingWindowImageRange(int width, int height, int x_step = 3, int y_step = 3, int scales = 5, float min_scale = 0.6, float max_scale = 1.6) :
-        width_(width), height_(height), x_step_(x_step),y_step_(y_step), scales_(scales), min_scale_(min_scale), max_scale_(max_scale)
+        SlidingWindowImageRange(int width, int height, int x_step = 3, int y_step = 3, int _scales = 5, float min_scale = 0.6, float max_scale = 1.6) :
+        width_(width), height_(height), x_step_(x_step),y_step_(y_step), scales_(_scales), min_scale_(min_scale), max_scale_(max_scale)
         {
         }
 
@@ -121,8 +121,8 @@ private:
         LocationImageRange& operator=(const LocationImageRange&);
 
     public:
-        LocationImageRange(const std::vector<Point>& locations, int scales = 5, float min_scale = 0.6, float max_scale = 1.6) :
-        locations_(locations), scales_(scales), min_scale_(min_scale), max_scale_(max_scale)
+        LocationImageRange(const std::vector<Point>& locations, int _scales = 5, float min_scale = 0.6, float max_scale = 1.6) :
+        locations_(locations), scales_(_scales), min_scale_(min_scale), max_scale_(max_scale)
         {
         }
 
@@ -141,10 +141,10 @@ private:
         LocationScaleImageRange(const LocationScaleImageRange&);
         LocationScaleImageRange& operator=(const LocationScaleImageRange&);
     public:
-        LocationScaleImageRange(const std::vector<Point>& locations, const std::vector<float>& scales) :
-        locations_(locations), scales_(scales)
+        LocationScaleImageRange(const std::vector<Point>& locations, const std::vector<float>& _scales) :
+        locations_(locations), scales_(_scales)
         {
-            assert(locations.size()==scales.size());
+            assert(locations.size()==_scales.size());
         }
 
         ImageIterator* iterator() const
@@ -237,7 +237,7 @@ private:
 
         std::vector<Template*> templates;
     public:
-        Matching(bool use_orientation = true, float truncate = 10) : truncate_(truncate), use_orientation_(use_orientation)
+        Matching(bool use_orientation = true, float _truncate = 10) : truncate_(_truncate), use_orientation_(use_orientation)
         {
         }
 
@@ -370,7 +370,7 @@ private:
         LocationImageIterator& operator=(const LocationImageIterator&);
 
     public:
-        LocationImageIterator(const std::vector<Point>& locations, int scales, float min_scale, float max_scale);
+        LocationImageIterator(const std::vector<Point>& locations, int _scales, float min_scale, float max_scale);
 
         bool hasNext() const {
             return has_next_;
@@ -392,10 +392,10 @@ private:
         LocationScaleImageIterator& operator=(const LocationScaleImageIterator&);
 
     public:
-        LocationScaleImageIterator(const std::vector<Point>& locations, const std::vector<float>& scales) :
-        locations_(locations), scales_(scales)
+        LocationScaleImageIterator(const std::vector<Point>& locations, const std::vector<float>& _scales) :
+        locations_(locations), scales_(_scales)
         {
-            assert(locations.size()==scales.size());
+            assert(locations.size()==_scales.size());
             reset();
         }
 
@@ -494,7 +494,7 @@ ChamferMatcher::SlidingWindowImageIterator::SlidingWindowImageIterator( int widt
                                                                         int height,
                                                                         int x_step = 3,
                                                                         int y_step = 3,
-                                                                        int scales = 5,
+                                                                        int _scales = 5,
                                                                         float min_scale = 0.6,
                                                                         float max_scale = 1.6) :
 
@@ -502,7 +502,7 @@ ChamferMatcher::SlidingWindowImageIterator::SlidingWindowImageIterator( int widt
                                                                             height_(height),
                                                                             x_step_(x_step),
                                                                             y_step_(y_step),
-                                                                            scales_(scales),
+                                                                            scales_(_scales),
                                                                             min_scale_(min_scale),
                                                                             max_scale_(max_scale)
 {
@@ -550,11 +550,11 @@ ChamferMatcher::ImageIterator* ChamferMatcher::SlidingWindowImageRange::iterator
 
 
 ChamferMatcher::LocationImageIterator::LocationImageIterator(const std::vector<Point>& locations,
-                                                                int scales = 5,
+                                                                int _scales = 5,
                                                                 float min_scale = 0.6,
                                                                 float max_scale = 1.6) :
                                                                     locations_(locations),
-                                                                    scales_(scales),
+                                                                    scales_(_scales),
                                                                     min_scale_(min_scale),
                                                                     max_scale_(max_scale)
 {
@@ -1138,10 +1138,10 @@ ChamferMatcher::Match* ChamferMatcher::Matching::localChamferDistance(Point offs
 }
 
 
-ChamferMatcher::Matches* ChamferMatcher::Matching::matchTemplates(Mat& dist_img, Mat& orientation_img, const ImageRange& range, float orientation_weight)
+ChamferMatcher::Matches* ChamferMatcher::Matching::matchTemplates(Mat& dist_img, Mat& orientation_img, const ImageRange& range, float _orientation_weight)
 {
 
-    ChamferMatcher::Matches* matches(new Matches());
+    ChamferMatcher::Matches* pmatches(new Matches());
     // try each template
     for(size_t i = 0; i < templates.size(); i++) {
         ImageIterator* it = range.iterator();
@@ -1156,17 +1156,17 @@ ChamferMatcher::Matches* ChamferMatcher::Matching::matchTemplates(Mat& dist_img,
             if (loc.x-tpl->center.x<0 || loc.x+tpl->size.width/2>=dist_img.cols) continue;
             if (loc.y-tpl->center.y<0 || loc.y+tpl->size.height/2>=dist_img.rows) continue;
 
-            ChamferMatcher::Match* is = localChamferDistance(loc, dist_img, orientation_img, tpl, orientation_weight);
+            ChamferMatcher::Match* is = localChamferDistance(loc, dist_img, orientation_img, tpl, _orientation_weight);
             if(is)
             {
-                matches->push_back(*is);
+                pmatches->push_back(*is);
                 delete is;
             }
         }
 
         delete it;
     }
-    return matches;
+    return pmatches;
 }
 
 
@@ -1176,7 +1176,8 @@ ChamferMatcher::Matches* ChamferMatcher::Matching::matchTemplates(Mat& dist_img,
  * @param edge_img Edge image
  * @return a match object
  */
-ChamferMatcher::Matches* ChamferMatcher::Matching::matchEdgeImage(Mat& edge_img, const ImageRange& range, float orientation_weight, int /*max_matches*/, float /*min_match_distance*/)
+ChamferMatcher::Matches* ChamferMatcher::Matching::matchEdgeImage(Mat& edge_img, const ImageRange& range,
+                    float _orientation_weight, int /*max_matches*/, float /*min_match_distance*/)
 {
     CV_Assert(edge_img.channels()==1);
 
@@ -1203,10 +1204,10 @@ ChamferMatcher::Matches* ChamferMatcher::Matching::matchEdgeImage(Mat& edge_img,
 
 
     // Template matching
-    ChamferMatcher::Matches* matches = matchTemplates(    dist_img,
+    ChamferMatcher::Matches* pmatches = matchTemplates(    dist_img,
                                                         orientation_img,
                                                         range,
-                                                        orientation_weight);
+                                                        _orientation_weight);
 
 
     if (use_orientation_) {
@@ -1215,7 +1216,7 @@ ChamferMatcher::Matches* ChamferMatcher::Matching::matchEdgeImage(Mat& edge_img,
     dist_img.release();
     annotated_img.release();
 
-    return matches;
+    return pmatches;
 }
 
 
diff --git a/modules/features2d/include/opencv2/features2d/features2d.hpp b/modules/features2d/include/opencv2/features2d/features2d.hpp
index a191ca223..ff52822ed 100644
--- a/modules/features2d/include/opencv2/features2d/features2d.hpp
+++ b/modules/features2d/include/opencv2/features2d/features2d.hpp
@@ -473,7 +473,10 @@ protected:
 
 //! detects corners using FAST algorithm by E. Rosten
 CV_EXPORTS void FAST( InputArray image, CV_OUT vector<KeyPoint>& keypoints,
-                      int threshold, bool nonmaxSupression=true, int type = 2 );
+                      int threshold, bool nonmaxSupression=true );
+
+CV_EXPORTS void FAST( InputArray image, CV_OUT vector<KeyPoint>& keypoints,
+                      int threshold, bool nonmaxSupression, int type );
 
 class CV_EXPORTS_W FastFeatureDetector : public FeatureDetector
 {
diff --git a/modules/features2d/src/fast.cpp b/modules/features2d/src/fast.cpp
index fe496762e..b9834bbf0 100644
--- a/modules/features2d/src/fast.cpp
+++ b/modules/features2d/src/fast.cpp
@@ -578,6 +578,11 @@ void FAST(InputArray _img, std::vector<KeyPoint>& keypoints, int threshold, bool
       break;
   }
 }
+
+void FAST(InputArray _img, std::vector<KeyPoint>& keypoints, int threshold, bool nonmax_suppression)
+{
+    FAST(_img, keypoints, threshold, nonmax_suppression, FastFeatureDetector::TYPE_9_16);
+}
 /*
  *   FastFeatureDetector
  */
diff --git a/modules/gpu/perf/perf_imgproc.cpp b/modules/gpu/perf/perf_imgproc.cpp
index ba864afc9..80d4af54d 100644
--- a/modules/gpu/perf/perf_imgproc.cpp
+++ b/modules/gpu/perf/perf_imgproc.cpp
@@ -23,13 +23,13 @@ void generateMap(cv::Mat& map_x, cv::Mat& map_y, int remapMode)
             case HALF_SIZE:
                 if (i > map_x.cols*0.25 && i < map_x.cols*0.75 && j > map_x.rows*0.25 && j < map_x.rows*0.75)
                 {
-                    map_x.at<float>(j,i) = 2 * (i - map_x.cols * 0.25f) + 0.5f;
-                    map_y.at<float>(j,i) = 2 * (j - map_x.rows * 0.25f) + 0.5f;
+                    map_x.at<float>(j,i) = 2.f * (i - map_x.cols * 0.25f) + 0.5f;
+                    map_y.at<float>(j,i) = 2.f * (j - map_x.rows * 0.25f) + 0.5f;
                 }
                 else
                 {
-                    map_x.at<float>(j,i) = 0;
-                    map_y.at<float>(j,i) = 0;
+                    map_x.at<float>(j,i) = 0.f;
+                    map_y.at<float>(j,i) = 0.f;
                 }
                 break;
             case UPSIDE_DOWN:
diff --git a/modules/gpu/perf/perf_labeling.cpp b/modules/gpu/perf/perf_labeling.cpp
index bbab5ecfa..1a812652d 100644
--- a/modules/gpu/perf/perf_labeling.cpp
+++ b/modules/gpu/perf/perf_labeling.cpp
@@ -23,7 +23,7 @@ struct GreedyLabeling
 
     struct InInterval
     {
-        InInterval(const int& _lo, const int& _hi) : lo(-_lo), hi(_hi) {};
+        InInterval(const int& _lo, const int& _hi) : lo(-_lo), hi(_hi) {}
         const int lo, hi;
 
         bool operator() (const unsigned char a, const unsigned char b) const
diff --git a/modules/highgui/src/cap_ffmpeg_impl.hpp b/modules/highgui/src/cap_ffmpeg_impl.hpp
index fc9ace54a..d3a5ed3ad 100644
--- a/modules/highgui/src/cap_ffmpeg_impl.hpp
+++ b/modules/highgui/src/cap_ffmpeg_impl.hpp
@@ -2050,7 +2050,7 @@ bool InputMediaStream_FFMPEG::read(unsigned char** data, int* size, int* endOfFi
 
         if (ret < 0)
         {
-            if (ret == (int64_t)AVERROR_EOF)
+            if ((int64_t)ret == (int64_t)AVERROR_EOF)
                 *endOfFile = true;
             return false;
         }
diff --git a/modules/ml/src/tree.cpp b/modules/ml/src/tree.cpp
index 936f552d3..0da24d66a 100644
--- a/modules/ml/src/tree.cpp
+++ b/modules/ml/src/tree.cpp
@@ -2069,7 +2069,7 @@ void CvDTree::cluster_categories( const int* vectors, int n, int m,
     {
         int sum = 0;
         const int* v = vectors + i*m;
-        labels[i] = i < k ? i : (*r)(k);
+        labels[i] = i < k ? i : r->uniform(0, k);
 
         // compute weight of each vector
         for( j = 0; j < m; j++ )
diff --git a/modules/objdetect/src/cascadedetect.hpp b/modules/objdetect/src/cascadedetect.hpp
index ec208c1ba..904c207b3 100644
--- a/modules/objdetect/src/cascadedetect.hpp
+++ b/modules/objdetect/src/cascadedetect.hpp
@@ -128,20 +128,20 @@ inline HaarEvaluator::Feature :: Feature()
         p[2][0] = p[2][1] = p[2][2] = p[2][3] = 0;
 }
 
-inline float HaarEvaluator::Feature :: calc( int offset ) const
+inline float HaarEvaluator::Feature :: calc( int _offset ) const
 {
-    float ret = rect[0].weight * CALC_SUM(p[0], offset) + rect[1].weight * CALC_SUM(p[1], offset);
+    float ret = rect[0].weight * CALC_SUM(p[0], _offset) + rect[1].weight * CALC_SUM(p[1], _offset);
 
     if( rect[2].weight != 0.0f )
-        ret += rect[2].weight * CALC_SUM(p[2], offset);
+        ret += rect[2].weight * CALC_SUM(p[2], _offset);
 
     return ret;
 }
 
-inline void HaarEvaluator::Feature :: updatePtrs( const Mat& sum )
+inline void HaarEvaluator::Feature :: updatePtrs( const Mat& _sum )
 {
-    const int* ptr = (const int*)sum.data;
-    size_t step = sum.step/sizeof(ptr[0]);
+    const int* ptr = (const int*)_sum.data;
+    size_t step = _sum.step/sizeof(ptr[0]);
     if (tilted)
     {
         CV_TILTED_PTRS( p[0][0], p[0][1], p[0][2], p[0][3], ptr, rect[0].r, step );
@@ -210,24 +210,24 @@ inline LBPEvaluator::Feature :: Feature()
         p[i] = 0;
 }
 
-inline int LBPEvaluator::Feature :: calc( int offset ) const
+inline int LBPEvaluator::Feature :: calc( int _offset ) const
 {
-    int cval = CALC_SUM_( p[5], p[6], p[9], p[10], offset );
+    int cval = CALC_SUM_( p[5], p[6], p[9], p[10], _offset );
 
-    return (CALC_SUM_( p[0], p[1], p[4], p[5], offset ) >= cval ? 128 : 0) |   // 0
-           (CALC_SUM_( p[1], p[2], p[5], p[6], offset ) >= cval ? 64 : 0) |    // 1
-           (CALC_SUM_( p[2], p[3], p[6], p[7], offset ) >= cval ? 32 : 0) |    // 2
-           (CALC_SUM_( p[6], p[7], p[10], p[11], offset ) >= cval ? 16 : 0) |  // 5
-           (CALC_SUM_( p[10], p[11], p[14], p[15], offset ) >= cval ? 8 : 0)|  // 8
-           (CALC_SUM_( p[9], p[10], p[13], p[14], offset ) >= cval ? 4 : 0)|   // 7
-           (CALC_SUM_( p[8], p[9], p[12], p[13], offset ) >= cval ? 2 : 0)|    // 6
-           (CALC_SUM_( p[4], p[5], p[8], p[9], offset ) >= cval ? 1 : 0);
+    return (CALC_SUM_( p[0], p[1], p[4], p[5], _offset ) >= cval ? 128 : 0) |   // 0
+           (CALC_SUM_( p[1], p[2], p[5], p[6], _offset ) >= cval ? 64 : 0) |    // 1
+           (CALC_SUM_( p[2], p[3], p[6], p[7], _offset ) >= cval ? 32 : 0) |    // 2
+           (CALC_SUM_( p[6], p[7], p[10], p[11], _offset ) >= cval ? 16 : 0) |  // 5
+           (CALC_SUM_( p[10], p[11], p[14], p[15], _offset ) >= cval ? 8 : 0)|  // 8
+           (CALC_SUM_( p[9], p[10], p[13], p[14], _offset ) >= cval ? 4 : 0)|   // 7
+           (CALC_SUM_( p[8], p[9], p[12], p[13], _offset ) >= cval ? 2 : 0)|    // 6
+           (CALC_SUM_( p[4], p[5], p[8], p[9], _offset ) >= cval ? 1 : 0);
 }
 
-inline void LBPEvaluator::Feature :: updatePtrs( const Mat& sum )
+inline void LBPEvaluator::Feature :: updatePtrs( const Mat& _sum )
 {
-    const int* ptr = (const int*)sum.data;
-    size_t step = sum.step/sizeof(ptr[0]);
+    const int* ptr = (const int*)_sum.data;
+    size_t step = _sum.step/sizeof(ptr[0]);
     Rect tr = rect;
     CV_SUM_PTRS( p[0], p[1], p[4], p[5], ptr, tr, step );
     tr.x += 2*rect.width;
@@ -292,10 +292,10 @@ inline HOGEvaluator::Feature :: Feature()
     featComponent = 0;
 }
 
-inline float HOGEvaluator::Feature :: calc( int offset ) const
+inline float HOGEvaluator::Feature :: calc( int _offset ) const
 {
-    float res = CALC_SUM(pF, offset);
-    float normFactor = CALC_SUM(pN, offset);
+    float res = CALC_SUM(pF, _offset);
+    float normFactor = CALC_SUM(pN, _offset);
     res = (res > 0.001f) ? (res / ( normFactor + 0.001f) ) : 0.f;
     return res;
 }
diff --git a/modules/stitching/src/seam_finders.cpp b/modules/stitching/src/seam_finders.cpp
index 3e10398ee..e568a6a03 100644
--- a/modules/stitching/src/seam_finders.cpp
+++ b/modules/stitching/src/seam_finders.cpp
@@ -817,7 +817,7 @@ bool DpSeamFinder::estimateSeam(
                 {
                     pair<float, int> opt = *min_element(steps, steps + nsteps);
                     cost(y, x) = opt.first;
-                    control(y, x) = opt.second;
+                    control(y, x) = (uchar)opt.second;
                     reachable(y, x) = 255;
                 }
             }
@@ -847,7 +847,7 @@ bool DpSeamFinder::estimateSeam(
                 {
                     pair<float, int> opt = *min_element(steps, steps + nsteps);
                     cost(y, x) = opt.first;
-                    control(y, x) = opt.second;
+                    control(y, x) = (uchar)opt.second;
                     reachable(y, x) = 255;
                 }
             }
diff --git a/modules/video/src/bgfg_gmg.cpp b/modules/video/src/bgfg_gmg.cpp
index 02b708e25..e3574b78f 100644
--- a/modules/video/src/bgfg_gmg.cpp
+++ b/modules/video/src/bgfg_gmg.cpp
@@ -269,7 +269,7 @@ namespace
                     if (updateBackgroundModel_)
                     {
                         for (int i = 0; i < nfeatures; ++i)
-                            weights[i] *= 1.0f - learningRate_;
+                            weights[i] *= (float)(1.0f - learningRate_);
 
                         bool inserted = insertFeature(newFeatureColor, (float)learningRate_, colors, weights, nfeatures, maxFeatures_);
 

From 4d6730dc68ea69843eb30c449882b5284d76dd49 Mon Sep 17 00:00:00 2001
From: Vsevolod Glumov <seva17@gmail.com>
Date: Tue, 28 Aug 2012 18:51:34 +0400
Subject: [PATCH 19/27] Improved javadoc comments. Minor formatting fix.

---
 modules/java/generator/src/java/android+OpenCVLoader.java | 4 ++--
 .../generator/src/java/engine+OpenCVEngineInterface.aidl  | 8 ++++----
 2 files changed, 6 insertions(+), 6 deletions(-)

diff --git a/modules/java/generator/src/java/android+OpenCVLoader.java b/modules/java/generator/src/java/android+OpenCVLoader.java
index b3025a9aa..e754a995f 100644
--- a/modules/java/generator/src/java/android+OpenCVLoader.java
+++ b/modules/java/generator/src/java/android+OpenCVLoader.java
@@ -14,7 +14,7 @@ public class OpenCVLoader
 
     /**
      * Loads and initializes OpenCV library from current application package. Roughly, it's an analog of system.loadLibrary("opencv_java").
-     * @return returns true is initialization of OpenCV was successful.
+     * @return Returns true is initialization of OpenCV was successful.
      */
     public static boolean initDebug()
     {
@@ -26,7 +26,7 @@ public class OpenCVLoader
      * @param Version OpenCV library version.
      * @param AppContext application context for connecting to the service.
      * @param Callback object, that implements LoaderCallbackInterface for handling the connection status.
-     * @return returns true if initialization of OpenCV is successful.
+     * @return Returns true if initialization of OpenCV is successful.
      */
     public static boolean initAsync(String Version, Context AppContext,
             LoaderCallbackInterface Callback)
diff --git a/modules/java/generator/src/java/engine+OpenCVEngineInterface.aidl b/modules/java/generator/src/java/engine+OpenCVEngineInterface.aidl
index 7949b3160..7bf967fd8 100644
--- a/modules/java/generator/src/java/engine+OpenCVEngineInterface.aidl
+++ b/modules/java/generator/src/java/engine+OpenCVEngineInterface.aidl
@@ -6,28 +6,28 @@ package org.opencv.engine;
 interface OpenCVEngineInterface
 {
 	/**
-	* @return returns service version.
+	* @return Returns service version.
 	*/
 	int getEngineVersion();
 
 	/**
 	* Finds an installed OpenCV library.
 	* @param OpenCV version.
-	* @return returns path to OpenCV native libs or an empty string if OpenCV can not be found.
+	* @return Returns path to OpenCV native libs or an empty string if OpenCV can not be found.
 	*/
 	String getLibPathByVersion(String version);
 
 	/**
 	* Tries to install defined version of OpenCV from Google Play Market.
 	* @param OpenCV version.
-	* @return returns true if installation was successful or OpenCV package has been already installed.
+	* @return Returns true if installation was successful or OpenCV package has been already installed.
 	*/
 	boolean installVersion(String version);
  
 	/**
 	* Returns list of libraries in loading order, separated by semicolon.
 	* @param OpenCV version.
-	* @return returns names of OpenCV libraries, separated by semicolon.
+	* @return Returns names of OpenCV libraries, separated by semicolon.
 	*/
 	String getLibraryList(String version);
 }
\ No newline at end of file

From 6c3e769f328d6930f989b54eba9dcdc48257c0fe Mon Sep 17 00:00:00 2001
From: Sergiu Dotenco <sergiu.dotenco@gmail.com>
Date: Tue, 28 Aug 2012 17:21:06 +0200
Subject: [PATCH 20/27] eliminated type conversion warnings

---
 modules/imgproc/src/smooth.cpp | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/modules/imgproc/src/smooth.cpp b/modules/imgproc/src/smooth.cpp
index 0fe1b6be4..8ec6f6d79 100644
--- a/modules/imgproc/src/smooth.cpp
+++ b/modules/imgproc/src/smooth.cpp
@@ -1325,7 +1325,7 @@ public:
 					#if CV_SSE3
 					if( haveSSE3 )
 					{
-						__m128 _val0 = _mm_set1_ps(val0);
+						__m128 _val0 = _mm_set1_ps(static_cast<float>(val0));
 						const __m128 _signMask = _mm_load_ps((const float*)bufSignMask);
 
 						for( ; k <= maxk - 4; k += 4 )
@@ -1373,9 +1373,9 @@ public:
 					#if CV_SSE3
 					if( haveSSE3 )
 					{
-                        const __m128 _b0 = _mm_set1_ps(b0);
-						const __m128 _g0 = _mm_set1_ps(g0);
-						const __m128 _r0 = _mm_set1_ps(r0);
+						const __m128 _b0 = _mm_set1_ps(static_cast<float>(b0));
+						const __m128 _g0 = _mm_set1_ps(static_cast<float>(g0));
+						const __m128 _r0 = _mm_set1_ps(static_cast<float>(r0));
 						const __m128 _signMask = _mm_load_ps((const float*)bufSignMask);
                         
                         for( ; k <= maxk - 4; k += 4 )

From cd59cf3ab5c37d1db53394f5143cd87f9047547f Mon Sep 17 00:00:00 2001
From: Andrey Kamaev <andrey.kamaev@itseez.com>
Date: Tue, 28 Aug 2012 17:23:33 +0400
Subject: [PATCH 21/27] Fixed java camera release in Android tutorial-0 sample

---
 .../opencv/samples/tutorial0/Sample0View.java |  2 +-
 .../samples/tutorial0/SampleViewBase.java     | 26 +++++++++++++++----
 2 files changed, 22 insertions(+), 6 deletions(-)

diff --git a/samples/android/tutorial-0-androidcamera/src/org/opencv/samples/tutorial0/Sample0View.java b/samples/android/tutorial-0-androidcamera/src/org/opencv/samples/tutorial0/Sample0View.java
index 769c34c36..a0278187c 100644
--- a/samples/android/tutorial-0-androidcamera/src/org/opencv/samples/tutorial0/Sample0View.java
+++ b/samples/android/tutorial-0-androidcamera/src/org/opencv/samples/tutorial0/Sample0View.java
@@ -6,7 +6,7 @@ import android.util.Log;
 
 class Sample0View extends SampleViewBase {
 
-    private static final String TAG = "Sample0View";
+    private static final String TAG = "Sample::View";
     int mSize;
     int[] mRGBA;
     private Bitmap mBitmap;
diff --git a/samples/android/tutorial-0-androidcamera/src/org/opencv/samples/tutorial0/SampleViewBase.java b/samples/android/tutorial-0-androidcamera/src/org/opencv/samples/tutorial0/SampleViewBase.java
index 376c86adb..c1cc15872 100644
--- a/samples/android/tutorial-0-androidcamera/src/org/opencv/samples/tutorial0/SampleViewBase.java
+++ b/samples/android/tutorial-0-androidcamera/src/org/opencv/samples/tutorial0/SampleViewBase.java
@@ -23,7 +23,7 @@ public abstract class SampleViewBase extends SurfaceView implements SurfaceHolde
     private int                 mFrameWidth;
     private int                 mFrameHeight;
     private byte[]              mFrame;
-    private boolean             mThreadRun;
+    private volatile boolean    mThreadRun;
     private byte[]              mBuffer;
     private SurfaceTexture      mSf;
 
@@ -55,9 +55,16 @@ public abstract class SampleViewBase extends SurfaceView implements SurfaceHolde
 
     public boolean openCamera() {
         Log.i(TAG, "openCamera");
-        mCamera = Camera.open();
+        mCamera = null;
+        try {
+            mCamera = Camera.open();
+        }
+        catch (Exception e){
+            Log.e(TAG, "Camera is not available (in use or does not exist)");
+            e.printStackTrace();
+        }
         if(mCamera == null) {
-            Log.e(TAG, "Can't open camera!");
+            Log.e(TAG, "Failed to open camera");
             return false;
         }
 
@@ -79,7 +86,6 @@ public abstract class SampleViewBase extends SurfaceView implements SurfaceHolde
         synchronized (this) {
             if (mCamera != null) {
                 mCamera.stopPreview();
-                mCamera.setPreviewCallback(null);
                 mCamera.release();
                 mCamera = null;
             }
@@ -91,6 +97,7 @@ public abstract class SampleViewBase extends SurfaceView implements SurfaceHolde
         Log.i(TAG, "setupCamera");
         synchronized (this) {
             if (mCamera != null) {
+                Log.i(TAG, "setupCamera - " + width + "x" + height);
                 Camera.Parameters params = mCamera.getParameters();
                 List<Camera.Size> sizes = params.getSupportedPreviewSizes();
                 mFrameWidth = width;
@@ -144,6 +151,14 @@ public abstract class SampleViewBase extends SurfaceView implements SurfaceHolde
 
     public void surfaceChanged(SurfaceHolder _holder, int format, int width, int height) {
         Log.i(TAG, "surfaceChanged");
+        // stop preview before making changes
+        try {
+            mCamera.stopPreview();
+        } catch (Exception e){
+          // ignore: tried to stop a non-existent preview
+        }
+
+        // start preview with new settings
         setupCamera(width, height);
     }
 
@@ -154,7 +169,6 @@ public abstract class SampleViewBase extends SurfaceView implements SurfaceHolde
 
     public void surfaceDestroyed(SurfaceHolder holder) {
         Log.i(TAG, "surfaceDestroyed");
-        releaseCamera();
     }
 
     /* The bitmap returned by this method shall be owned by the child and released in onPreviewStopped() */
@@ -184,6 +198,8 @@ public abstract class SampleViewBase extends SurfaceView implements SurfaceHolde
             synchronized (this) {
                 try {
                     this.wait();
+                    if (!mThreadRun)
+                        break;
                     bmp = processFrame(mFrame);
                 } catch (InterruptedException e) {
                     e.printStackTrace();

From 0adbead654e49ec352ab4bb21cf112d47a44ab71 Mon Sep 17 00:00:00 2001
From: Andrey Kamaev <andrey.kamaev@itseez.com>
Date: Tue, 28 Aug 2012 20:39:10 +0400
Subject: [PATCH 22/27] Android toolchain: fix CCache program search

---
 android/android.toolchain.cmake | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)

diff --git a/android/android.toolchain.cmake b/android/android.toolchain.cmake
index 47918ade5..b4d498fc3 100644
--- a/android/android.toolchain.cmake
+++ b/android/android.toolchain.cmake
@@ -690,12 +690,13 @@ if( BUILD_WITH_ANDROID_NDK )
 endif()
 
 # ccache support
-__INIT_VARIABLE( NDK_CCACHE ENV_NDK_CCACHE )
-if( NDK_CCACHE )
- find_program(NDK_CCACHE "${NDK_CCACHE}" DOC "The path to ccache binary")
+__INIT_VARIABLE( _ndk_ccache NDK_CCACHE ENV_NDK_CCACHE )
+if( _ndk_ccache )
+ find_program( NDK_CCACHE "${_ndk_ccache}" DOC "The path to ccache binary")
 else()
- unset( NDK_CCACHE )
+ unset( NDK_CCACHE CACHE )
 endif()
+unset( _ndk_ccache )
 
 # specify the cross compiler
 if( NDK_CCACHE )

From 14694343cba605aa0bed6e3af0925cc63ec9d033 Mon Sep 17 00:00:00 2001
From: Vladislav Vinogradov <vlad.vinogradov@itseez.com>
Date: Wed, 29 Aug 2012 10:51:40 +0400
Subject: [PATCH 23/27] fixed gpu PyrLKSparse perf test

---
 modules/gpu/perf/perf_video.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/modules/gpu/perf/perf_video.cpp b/modules/gpu/perf/perf_video.cpp
index 8346d25f4..aa802fbf5 100644
--- a/modules/gpu/perf/perf_video.cpp
+++ b/modules/gpu/perf/perf_video.cpp
@@ -219,7 +219,7 @@ PERF_TEST_P(ImagePair_Gray_NPts_WinSz_Levels_Iters, Video_PyrLKOpticalFlowSparse
 
     if (runOnGpu)
     {
-        cv::gpu::GpuMat d_pts(pts);
+        cv::gpu::GpuMat d_pts(pts.reshape(2, 1));
 
         cv::gpu::PyrLKOpticalFlow d_pyrLK;
         d_pyrLK.winSize = cv::Size(winSize, winSize);

From ee2bebf5f7a9fda0e3aac9d5edd35d7f58ac3939 Mon Sep 17 00:00:00 2001
From: OpenCV Buildbot <buildbot@opencv.org>
Date: Wed, 29 Aug 2012 18:59:21 +0400
Subject: [PATCH 24/27] update FFMPEG wrapper binaries

---
 3rdparty/ffmpeg/opencv_ffmpeg.dll    | Bin 9161356 -> 9161356 bytes
 3rdparty/ffmpeg/opencv_ffmpeg_64.dll | Bin 9219038 -> 9219038 bytes
 2 files changed, 0 insertions(+), 0 deletions(-)

diff --git a/3rdparty/ffmpeg/opencv_ffmpeg.dll b/3rdparty/ffmpeg/opencv_ffmpeg.dll
index 056295fef85329261c0f48b7fba88629f8f24865..2063af43c263b5b1d14f2090a45fc86fe8aca0a1 100644
GIT binary patch
delta 465
zcmWN=*)|k#0KnnHOpR8wsFWmSOOqB_XcA4R>`_UJA}y9eWl2%}3~`YQ&*94P1i9)7
zeoy27o%5}%tw&eFzl)J%Jh8gmoc@1sUQEMuj9?UZ;7*KT2JXV$xCi&*KHQI)n1$JR
z01x6JJd8Pb1drk|%*Eq)0`u@B=Hn?Wz|&ZWXYec*VKJ6qDVE_mEXVU0#|v127x5Ba
z#w%EfRd^Mz;dQ)$)mVc!F@d+R7H?x6*5e&a;$3XOMr^`+cpo2NGqzwWwqZMVU?)Dr
zF6_of_!ysH4?e|Se1^~Q1-`^Se1)&E9|!Oa4&qyUhwt$N4&gA4;3$5?PdJ9-IDwz>
z3x35(oWg0G!EYPRmi>#=#}ld8)@=Aa{1MKD^Wo3%SNJ<5TnJO)Vz?Ck*^F&16Ws=q
CN%6)2

delta 465
zcmWN=={6K#0D$4cjHY5RDwKpaC0d1wvQ%0Kt+u93WhvSeN*Q_)e(=L}_|<U*=^oyz
z@jd4}E9)E4m2h=2lATPfEw`s<{7;E#n2r&QVg~NO81BSfxEnJu3*(rLIhczH%)>pn
z7x!U47GNRn#{*b|2eB9rVF{LE86L(XcodJ}aV*CZcoHk{6jovtp2jnH7SG{%ynxks
z5o@p(>+lj@#w%El4R{r=VIwwSGq&J$yn#2d6>s5fyn}bK4cqY^c3>xV;eC975AhK`
z#wXZ~J=lwV*pE*!iO=vkzQC9G3J35tzQMORh(kDxBlr&A<0y{d2mFYi@H2kFar}zk
zZ~`ZB3curzzfM>Di^P+Oh1k|~_%r+!&V;FOHk=E8hlKOtLbw?I370lwTgybZ0d*?y
A_y7O^

diff --git a/3rdparty/ffmpeg/opencv_ffmpeg_64.dll b/3rdparty/ffmpeg/opencv_ffmpeg_64.dll
index c7aed0dc59fd2e593fa1d2ea4717b3e27ace957a..5a75816df44fbfc5b9460ddecea3c7f9167c1dc1 100644
GIT binary patch
delta 467
zcmWN=SyRn%0D$4i|LCZ+kd!54tEiJKrRd0d3TaW6LZ$44HcL1quTJWMPvPE7<D+!(
z&YXMS!ta@Rvg?0h+3;s3>PRGit#n1{f2#{(4sO5*W4IA>F^-!s5A(4AH)A0dVKJ8A
z7Tk)ZxDCs2JC<Vw?!cY63wL8B?!mpd536uL9>9Zm2oGa5)?h6j!J}A*^_aj0Jcf;U
z98cg$JcUizjHj^$Tk#B@#WqahIc&%CcmXfsCA^GRFohl1iC6I&UdJxHf!)}Hz1W90
zu^$KU7T(4?cozq82=C#2e1O9^f}{8l$8a1U;bVM)Pw^Q(#~1h#U*QD4#y9vDCvgg=
zaRz7c9lpm8_z~yu6Mn`om|k<fHi}Y-<Wf8~A1;Jn!^QAhNccTm3Nzty_#<5T8;`B7
G|NalQYwVf;

delta 467
zcmWmB=~m2f0D$4ce;AU?w4kgZ86|r{l0rj`r9xRI`&!7BrBZln7|yAy=(}^`Qs%>Z
z&RmP156=}m#lr7cF__CmiEMH{pNamYe@%-^a4AL@!)3S}<G2D>VhOIoQe2H?xCRrL
z#B!{_O02@QxDMB2HP+w;+=!cSGj74HSc}_mJMO?b+==zL3sblo8?X`gU=!}eeYhVF
z;6Xfuhp`!tU<)3_V|W}}@dUQvNo>bc*nypR8qeTa?7}pj!}HjUJ($4@co8q*W$eX1
z?8hs36|dm{4&rsZfj99MW^o8_;~l(<_wYVGz=!w<ALA2ziqCKuNANkmz?V3Rukba#
z!MFGh$M8LVz>oL|$8iED@$;fnspx;lY&<p<Ob1_rufex~U?!Lia>4iDN09#;kNqqx
F`~#IL>&O5A


From 3d9018f0191304c3f24816530a3552d57a557428 Mon Sep 17 00:00:00 2001
From: Andrey Kamaev <andrey.kamaev@itseez.com>
Date: Wed, 29 Aug 2012 19:16:11 +0400
Subject: [PATCH 25/27] Fix run.py version control detection when used outide
 of OpenCV build

---
 modules/ts/misc/run.py | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/modules/ts/misc/run.py b/modules/ts/misc/run.py
index f2c213ed1..09db7dc79 100644
--- a/modules/ts/misc/run.py
+++ b/modules/ts/misc/run.py
@@ -339,6 +339,8 @@ class RunInfo(object):
         self.tests = self.getAvailableTestApps()
 
     def getVCVersion(self, root_path):
+        if not root_path:
+            return None
         if os.path.isdir(os.path.join(root_path, ".svn")):
             return self.getSvnVersion(root_path)
         elif os.path.isdir(os.path.join(root_path, ".git")):

From a09679044e5334aebe3dbd1929a950ccee40ac56 Mon Sep 17 00:00:00 2001
From: Anatoly Baksheev <no@email>
Date: Mon, 27 Aug 2012 14:27:13 +0400
Subject: [PATCH 26/27] renamed device::bilaterl_filter kernel to
 device::disp_bilaterl_filter for correct naming

fixed some warnings
---
 modules/gpu/src/bilateral_filter.cpp          |  18 +-
 modules/gpu/src/cuda/disp_bilateral_filter.cu | 219 ++++++++++++++++++
 2 files changed, 228 insertions(+), 9 deletions(-)
 create mode 100644 modules/gpu/src/cuda/disp_bilateral_filter.cu

diff --git a/modules/gpu/src/bilateral_filter.cpp b/modules/gpu/src/bilateral_filter.cpp
index 04c312688..facd1ee08 100644
--- a/modules/gpu/src/bilateral_filter.cpp
+++ b/modules/gpu/src/bilateral_filter.cpp
@@ -57,16 +57,16 @@ void cv::gpu::DisparityBilateralFilter::operator()(const GpuMat&, const GpuMat&,
 
 namespace cv { namespace gpu { namespace device 
 {
-    namespace bilateral_filter
+    namespace disp_bilateral_filter
     {
-        void load_constants(float* table_color, PtrStepSzf table_space, int ndisp, int radius, short edge_disc, short max_disc);
+        void disp_load_constants(float* table_color, PtrStepSzf table_space, int ndisp, int radius, short edge_disc, short max_disc);
 
-        void bilateral_filter_gpu(PtrStepSzb disp, PtrStepSzb img, int channels, int iters, cudaStream_t stream);
-        void bilateral_filter_gpu(PtrStepSz<short> disp, PtrStepSzb img, int channels, int iters, cudaStream_t stream);
+        template<typename T>
+        void disp_bilateral_filter(PtrStepSz<T> disp, PtrStepSzb img, int channels, int iters, cudaStream_t stream);
     }
 }}}
 
-using namespace ::cv::gpu::device::bilateral_filter;
+using namespace ::cv::gpu::device::disp_bilateral_filter;
 
 namespace
 {
@@ -103,14 +103,14 @@ namespace
     }
 
     template <typename T>
-    void bilateral_filter_operator(int ndisp, int radius, int iters, float edge_threshold,float max_disc_threshold, 
+    void disp_bilateral_filter_operator(int ndisp, int radius, int iters, float edge_threshold,float max_disc_threshold, 
                                    GpuMat& table_color, GpuMat& table_space, 
                                    const GpuMat& disp, const GpuMat& img, GpuMat& dst, Stream& stream)
     {
         short edge_disc = max<short>(short(1), short(ndisp * edge_threshold + 0.5));
         short max_disc = short(ndisp * max_disc_threshold + 0.5);
 
-        load_constants(table_color.ptr<float>(), table_space, ndisp, radius, edge_disc, max_disc);
+        disp_load_constants(table_color.ptr<float>(), table_space, ndisp, radius, edge_disc, max_disc);
 
         if (&dst != &disp)
         {
@@ -120,7 +120,7 @@ namespace
                 disp.copyTo(dst);
         }
 
-        bilateral_filter_gpu((PtrStepSz<T>)dst, img, img.channels(), iters, StreamAccessor::getStream(stream));
+        disp_bilateral_filter<T>(dst, img, img.channels(), iters, StreamAccessor::getStream(stream));
     }
 
     typedef void (*bilateral_filter_operator_t)(int ndisp, int radius, int iters, float edge_threshold, float max_disc_threshold, 
@@ -128,7 +128,7 @@ namespace
                                                 const GpuMat& disp, const GpuMat& img, GpuMat& dst, Stream& stream);
     
     const bilateral_filter_operator_t operators[] = 
-        {bilateral_filter_operator<unsigned char>, 0, 0, bilateral_filter_operator<short>, 0, 0, 0, 0};
+        {disp_bilateral_filter_operator<unsigned char>, 0, 0, disp_bilateral_filter_operator<short>, 0, 0, 0, 0};
 }
 
 cv::gpu::DisparityBilateralFilter::DisparityBilateralFilter(int ndisp_, int radius_, int iters_)
diff --git a/modules/gpu/src/cuda/disp_bilateral_filter.cu b/modules/gpu/src/cuda/disp_bilateral_filter.cu
new file mode 100644
index 000000000..e91cf9cc3
--- /dev/null
+++ b/modules/gpu/src/cuda/disp_bilateral_filter.cu
@@ -0,0 +1,219 @@
+/*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 "internal_shared.hpp"
+#include "opencv2/gpu/device/limits.hpp"
+
+namespace cv { namespace gpu { namespace device
+{
+    namespace disp_bilateral_filter
+    {
+        __constant__ float* ctable_color;
+        __constant__ float* ctable_space;
+        __constant__ size_t ctable_space_step;
+
+        __constant__ int cndisp;
+        __constant__ int cradius;
+
+        __constant__ short cedge_disc;
+        __constant__ short cmax_disc;
+
+        void disp_load_constants(float* table_color, PtrStepSzf table_space, int ndisp, int radius, short edge_disc, short max_disc)
+        {
+            cudaSafeCall( cudaMemcpyToSymbol(ctable_color, &table_color, sizeof(table_color)) );
+            cudaSafeCall( cudaMemcpyToSymbol(ctable_space, &table_space.data, sizeof(table_space.data)) );
+            size_t table_space_step = table_space.step / sizeof(float);
+            cudaSafeCall( cudaMemcpyToSymbol(ctable_space_step, &table_space_step, sizeof(size_t)) );
+
+            cudaSafeCall( cudaMemcpyToSymbol(cndisp, &ndisp, sizeof(int)) );
+            cudaSafeCall( cudaMemcpyToSymbol(cradius, &radius, sizeof(int)) );
+
+            cudaSafeCall( cudaMemcpyToSymbol(cedge_disc, &edge_disc, sizeof(short)) );
+            cudaSafeCall( cudaMemcpyToSymbol(cmax_disc, &max_disc, sizeof(short)) );
+        }
+
+        template <int channels>
+        struct DistRgbMax
+        {
+            static __device__ __forceinline__ uchar calc(const uchar* a, const uchar* b)
+            {
+                uchar x = ::abs(a[0] - b[0]);
+                uchar y = ::abs(a[1] - b[1]);
+                uchar z = ::abs(a[2] - b[2]);
+                return (::max(::max(x, y), z));
+            }
+        };
+
+        template <>
+        struct DistRgbMax<1>
+        {
+            static __device__ __forceinline__ uchar calc(const uchar* a, const uchar* b)
+            {
+                return ::abs(a[0] - b[0]);
+            }
+        };
+
+        template <int channels, typename T>
+        __global__ void disp_bilateral_filter(int t, T* disp, size_t disp_step, const uchar* img, size_t img_step, int h, int w)
+        {
+            const int y = blockIdx.y * blockDim.y + threadIdx.y;
+            const int x = ((blockIdx.x * blockDim.x + threadIdx.x) << 1) + ((y + t) & 1);
+
+            T dp[5];
+
+            if (y > 0 && y < h - 1 && x > 0 && x < w - 1)
+            {
+                dp[0] = *(disp + (y  ) * disp_step + x + 0);
+                dp[1] = *(disp + (y-1) * disp_step + x + 0);
+                dp[2] = *(disp + (y  ) * disp_step + x - 1);
+                dp[3] = *(disp + (y+1) * disp_step + x + 0);
+                dp[4] = *(disp + (y  ) * disp_step + x + 1);
+
+                if(::abs(dp[1] - dp[0]) >= cedge_disc || ::abs(dp[2] - dp[0]) >= cedge_disc || ::abs(dp[3] - dp[0]) >= cedge_disc || ::abs(dp[4] - dp[0]) >= cedge_disc)
+                {
+                    const int ymin = ::max(0, y - cradius);
+                    const int xmin = ::max(0, x - cradius);
+                    const int ymax = ::min(h - 1, y + cradius);
+                    const int xmax = ::min(w - 1, x + cradius);
+
+                    float cost[] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
+
+                    const uchar* ic = img + y * img_step + channels * x;
+
+                    for(int yi = ymin; yi <= ymax; yi++)
+                    {
+                        const T* disp_y = disp + yi * disp_step;
+
+                        for(int xi = xmin; xi <= xmax; xi++)
+                        {
+                            const uchar* in = img + yi * img_step + channels * xi;
+
+                            uchar dist_rgb = DistRgbMax<channels>::calc(in, ic);
+
+                            const float weight = ctable_color[dist_rgb] * (ctable_space + ::abs(y-yi)* ctable_space_step)[::abs(x-xi)];
+
+                            const T disp_reg = disp_y[xi];
+
+                            cost[0] += ::min(cmax_disc, ::abs(disp_reg - dp[0])) * weight;
+                            cost[1] += ::min(cmax_disc, ::abs(disp_reg - dp[1])) * weight;
+                            cost[2] += ::min(cmax_disc, ::abs(disp_reg - dp[2])) * weight;
+                            cost[3] += ::min(cmax_disc, ::abs(disp_reg - dp[3])) * weight;
+                            cost[4] += ::min(cmax_disc, ::abs(disp_reg - dp[4])) * weight;
+                        }
+                    }
+
+                    float minimum = numeric_limits<float>::max();
+                    int id = 0;
+
+                    if (cost[0] < minimum)
+                    {
+                        minimum = cost[0];
+                        id = 0;
+                    }
+                    if (cost[1] < minimum)
+                    {
+                        minimum = cost[1];
+                        id = 1;
+                    }
+                    if (cost[2] < minimum)
+                    {
+                        minimum = cost[2];
+                        id = 2;
+                    }
+                    if (cost[3] < minimum)
+                    {
+                        minimum = cost[3];
+                        id = 3;
+                    }
+                    if (cost[4] < minimum)
+                    {
+                        minimum = cost[4];
+                        id = 4;
+                    }
+
+                    *(disp + y * disp_step + x) = dp[id];
+                }
+            }
+        }
+
+        template <typename T>
+        void disp_bilateral_filter(PtrStepSz<T> disp, PtrStepSzb img, int channels, int iters, cudaStream_t stream)
+        {
+            dim3 threads(32, 8, 1);
+            dim3 grid(1, 1, 1);
+            grid.x = divUp(disp.cols, threads.x << 1);
+            grid.y = divUp(disp.rows, threads.y);
+
+            switch (channels)
+            {
+            case 1:
+                for (int i = 0; i < iters; ++i)
+                {
+                    disp_bilateral_filter<1><<<grid, threads, 0, stream>>>(0, disp.data, disp.step/sizeof(T), img.data, img.step, disp.rows, disp.cols);
+                    cudaSafeCall( cudaGetLastError() );
+
+                    disp_bilateral_filter<1><<<grid, threads, 0, stream>>>(1, disp.data, disp.step/sizeof(T), img.data, img.step, disp.rows, disp.cols);
+                    cudaSafeCall( cudaGetLastError() );
+                }
+                break;
+            case 3:
+                for (int i = 0; i < iters; ++i)
+                {
+                    disp_bilateral_filter<3><<<grid, threads, 0, stream>>>(0, disp.data, disp.step/sizeof(T), img.data, img.step, disp.rows, disp.cols);
+                    cudaSafeCall( cudaGetLastError() );
+
+                    disp_bilateral_filter<3><<<grid, threads, 0, stream>>>(1, disp.data, disp.step/sizeof(T), img.data, img.step, disp.rows, disp.cols);
+                    cudaSafeCall( cudaGetLastError() );
+                }
+                break;
+            default:
+                cv::gpu::error("Unsupported channels count", __FILE__, __LINE__, "disp_bilateral_filter");
+            }
+
+            if (stream == 0)
+                cudaSafeCall( cudaDeviceSynchronize() );
+        }
+
+        template void disp_bilateral_filter<uchar>(PtrStepSz<uchar> disp, PtrStepSzb img, int channels, int iters, cudaStream_t stream);
+        template void disp_bilateral_filter<short>(PtrStepSz<short> disp, PtrStepSzb img, int channels, int iters, cudaStream_t stream);
+    } // namespace bilateral_filter
+}}} // namespace cv { namespace gpu { namespace device

From 0ba01afd83d16d8ba2cfbf98dd46debe569b69cd Mon Sep 17 00:00:00 2001
From: Anatoly Baksheev <no@email>
Date: Wed, 29 Aug 2012 16:49:07 +0400
Subject: [PATCH 27/27] added GPU bilateral filter + tests

added GPU non local means brute force filter + tests
---
 CMakeLists.txt                                |   1 -
 cmake/OpenCVCompilerOptions.cmake             |   7 +-
 modules/gpu/doc/image_processing.rst          |  48 +++
 modules/gpu/include/opencv2/gpu/gpu.hpp       |   8 +
 modules/gpu/perf/perf_core.cpp                |  18 +-
 modules/gpu/perf/perf_denoising.cpp           |  98 ++++++
 modules/gpu/perf/perf_imgproc.cpp             |  28 +-
 modules/gpu/perf/perf_matop.cpp               |   6 +-
 modules/gpu/perf/perf_video.cpp               |  10 +-
 modules/gpu/perf/utility.hpp                  |   1 +
 modules/gpu/src/cuda/bilateral_filter.cu      | 292 ++++++++----------
 modules/gpu/src/cuda/nlm.cu                   | 143 +++++++++
 modules/gpu/src/denoising.cpp                 | 135 ++++++++
 modules/gpu/src/hough.cpp                     |   4 +-
 .../gpu/src/opencv2/gpu/device/functional.hpp |   2 +
 modules/gpu/test/test_denoising.cpp           | 140 +++++++++
 modules/gpu/test/utility.cpp                  |   8 +
 modules/gpu/test/utility.hpp                  |   5 +
 modules/imgproc/src/smooth.cpp                |   2 +
 19 files changed, 755 insertions(+), 201 deletions(-)
 create mode 100644 modules/gpu/perf/perf_denoising.cpp
 create mode 100644 modules/gpu/src/cuda/nlm.cu
 create mode 100644 modules/gpu/src/denoising.cpp
 create mode 100644 modules/gpu/test/test_denoising.cpp

diff --git a/CMakeLists.txt b/CMakeLists.txt
index c87d6fbf9..f9baf672e 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -197,7 +197,6 @@ OCV_OPTION(ENABLE_SSE41               "Enable SSE4.1 instructions"
 OCV_OPTION(ENABLE_SSE42               "Enable SSE4.2 instructions"                               OFF  IF (CMAKE_COMPILER_IS_GNUCXX AND (X86 OR X86_64)) )
 OCV_OPTION(ENABLE_NOISY_WARNINGS      "Show all warnings even if they are too noisy"             OFF )
 OCV_OPTION(OPENCV_WARNINGS_ARE_ERRORS "Treat warnings as errors"                                 OFF )
-OCV_OPTION(ENABLE_MULTI_PROCESSOR_COMPILATION "Enabling multi-processory compilation"            OFF IF MSVC)
 
 
 # uncategorized options
diff --git a/cmake/OpenCVCompilerOptions.cmake b/cmake/OpenCVCompilerOptions.cmake
index b3d71c8c8..191352745 100644
--- a/cmake/OpenCVCompilerOptions.cmake
+++ b/cmake/OpenCVCompilerOptions.cmake
@@ -282,9 +282,4 @@ if(MSVC)
   if(NOT ENABLE_NOISY_WARNINGS)
     set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /wd4251") #class 'std::XXX' needs to have dll-interface to be used by clients of YYY
   endif()
-endif()
-
-
-if (MSVC AND ENABLE_MULTI_PROCESSOR_COMPILATION)
-   SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP")
-endif()
+endif()
\ No newline at end of file
diff --git a/modules/gpu/doc/image_processing.rst b/modules/gpu/doc/image_processing.rst
index 858b707ba..c8fd7491e 100644
--- a/modules/gpu/doc/image_processing.rst
+++ b/modules/gpu/doc/image_processing.rst
@@ -818,9 +818,57 @@ Performs linear blending of two images.
     :param result: Destination image.
 
     :param stream: Stream for the asynchronous version.
+    
+    
+gpu::bilateralFilter
+-------------------
+Performs bilateral filtering of passed image
 
+.. ocv:function:: void gpu::bilateralFilter(const GpuMat& src, GpuMat& dst, int kernel_size, float sigma_color, float sigma_spatial, int borderMode, Stream& stream = Stream::Null());
+    
+    :param src: Source image. Supports only (channles != 2 && depth() != CV_8S && depth() != CV_32S && depth() != CV_64F).
 
+    :param dst: Destination imagwe.
 
+    :param kernel_size: Kernel window size.
+
+    :param sigma_color: Filter sigma in the color space. 
+    
+    :param sigma_spatial:  Filter sigma in the coordinate space. 
+
+    :param borderMode:  Border type. See :ocv:func:`borderInterpolate` for details. ``BORDER_REFLECT101`` , ``BORDER_REPLICATE`` , ``BORDER_CONSTANT`` , ``BORDER_REFLECT`` and ``BORDER_WRAP`` are supported for now.
+
+    :param stream: Stream for the asynchronous version.
+
+.. seealso::
+
+    :ocv:func:`bilateralFilter`,
+    
+    
+gpu::nonLocalMeans
+-------------------
+Performs pure non local means denoising without any simplification, and thus it is not fast.
+
+.. ocv:function:: void nonLocalMeans(const GpuMat& src, GpuMat& dst, float h, int search_widow_size = 11, int block_size = 7, int borderMode = BORDER_DEFAULT, Stream& s = Stream::Null());
+    
+    :param src: Source image. Supports only CV_8UC1, CV_8UC3.
+
+    :param dst: Destination imagwe.
+
+    :param h: Filter sigma regulating filter strength for color. 
+    
+    :param search_widow_size: Size of search window.
+
+    :param block_size: Size of block used for computing weights. 
+        
+    :param borderMode:  Border type. See :ocv:func:`borderInterpolate` for details. ``BORDER_REFLECT101`` , ``BORDER_REPLICATE`` , ``BORDER_CONSTANT`` , ``BORDER_REFLECT`` and ``BORDER_WRAP`` are supported for now.
+
+    :param stream: Stream for the asynchronous version.
+
+.. seealso::
+
+    :ocv:func:`fastNlMeansDenoising`
+    
 gpu::alphaComp
 -------------------
 Composites two images using alpha opacity values contained in each image.
diff --git a/modules/gpu/include/opencv2/gpu/gpu.hpp b/modules/gpu/include/opencv2/gpu/gpu.hpp
index c2fcc31a2..2faa1751d 100644
--- a/modules/gpu/include/opencv2/gpu/gpu.hpp
+++ b/modules/gpu/include/opencv2/gpu/gpu.hpp
@@ -769,6 +769,14 @@ CV_EXPORTS void pyrUp(const GpuMat& src, GpuMat& dst, Stream& stream = Stream::N
 CV_EXPORTS void blendLinear(const GpuMat& img1, const GpuMat& img2, const GpuMat& weights1, const GpuMat& weights2,
                             GpuMat& result, Stream& stream = Stream::Null());
 
+//! Performa bilateral filtering of passsed image
+CV_EXPORTS void bilateralFilter(const GpuMat& src, GpuMat& dst, int kernel_size, float sigma_color, float sigma_spatial, 
+                                int borderMode = BORDER_DEFAULT, Stream& stream = Stream::Null());
+
+//! Brute force non-local means algorith (slow but universal)
+CV_EXPORTS void nonLocalMeans(const GpuMat& src, GpuMat& dst, float h, 
+                              int search_widow_size = 11, int block_size = 7, int borderMode = BORDER_DEFAULT, Stream& s = Stream::Null());
+
 
 struct CV_EXPORTS CannyBuf;
 
diff --git a/modules/gpu/perf/perf_core.cpp b/modules/gpu/perf/perf_core.cpp
index b638fbf4a..915a9a20b 100644
--- a/modules/gpu/perf/perf_core.cpp
+++ b/modules/gpu/perf/perf_core.cpp
@@ -882,7 +882,7 @@ PERF_TEST_P(Sz_Depth, Core_BitwiseAndMat, Combine(GPU_TYPICAL_MAT_SIZES, Values(
 //////////////////////////////////////////////////////////////////////
 // BitwiseAndScalar
 
-PERF_TEST_P(Sz_Depth_Cn, Core_BitwiseAndScalar, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_16U, CV_32S), Values(1, 3, 4)))
+PERF_TEST_P(Sz_Depth_Cn, Core_BitwiseAndScalar, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_16U, CV_32S), GPU_CHANNELS_1_3_4))
 {
     const cv::Size size = GET_PARAM(0);
     const int depth = GET_PARAM(1);
@@ -963,7 +963,7 @@ PERF_TEST_P(Sz_Depth, Core_BitwiseOrMat, Combine(GPU_TYPICAL_MAT_SIZES, Values(C
 //////////////////////////////////////////////////////////////////////
 // BitwiseOrScalar
 
-PERF_TEST_P(Sz_Depth_Cn, Core_BitwiseOrScalar, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_16U, CV_32S), Values(1, 3, 4)))
+PERF_TEST_P(Sz_Depth_Cn, Core_BitwiseOrScalar, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_16U, CV_32S), GPU_CHANNELS_1_3_4))
 {
     const cv::Size size = GET_PARAM(0);
     const int depth = GET_PARAM(1);
@@ -1044,7 +1044,7 @@ PERF_TEST_P(Sz_Depth, Core_BitwiseXorMat, Combine(GPU_TYPICAL_MAT_SIZES, Values(
 //////////////////////////////////////////////////////////////////////
 // BitwiseXorScalar
 
-PERF_TEST_P(Sz_Depth_Cn, Core_BitwiseXorScalar, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_16U, CV_32S), Values(1, 3, 4)))
+PERF_TEST_P(Sz_Depth_Cn, Core_BitwiseXorScalar, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_16U, CV_32S), GPU_CHANNELS_1_3_4))
 {
     const cv::Size size = GET_PARAM(0);
     const int depth = GET_PARAM(1);
@@ -1085,7 +1085,7 @@ PERF_TEST_P(Sz_Depth_Cn, Core_BitwiseXorScalar, Combine(GPU_TYPICAL_MAT_SIZES, V
 //////////////////////////////////////////////////////////////////////
 // RShift
 
-PERF_TEST_P(Sz_Depth_Cn, Core_RShift, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_16U, CV_32S), Values(1, 3, 4)))
+PERF_TEST_P(Sz_Depth_Cn, Core_RShift, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_16U, CV_32S), GPU_CHANNELS_1_3_4))
 {
     const cv::Size size = GET_PARAM(0);
     const int depth = GET_PARAM(1);
@@ -1119,7 +1119,7 @@ PERF_TEST_P(Sz_Depth_Cn, Core_RShift, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8
 //////////////////////////////////////////////////////////////////////
 // LShift
 
-PERF_TEST_P(Sz_Depth_Cn, Core_LShift, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_16U, CV_32S), Values(1, 3, 4)))
+PERF_TEST_P(Sz_Depth_Cn, Core_LShift, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_16U, CV_32S), GPU_CHANNELS_1_3_4))
 {
     const cv::Size size = GET_PARAM(0);
     const int depth = GET_PARAM(1);
@@ -1461,7 +1461,7 @@ DEF_PARAM_TEST(Sz_Depth_Cn_Code, cv::Size, MatDepth, int, FlipCode);
 PERF_TEST_P(Sz_Depth_Cn_Code, Core_Flip, Combine(
     GPU_TYPICAL_MAT_SIZES,
     Values(CV_8U, CV_16U, CV_32F),
-    Values(1, 3, 4),
+    GPU_CHANNELS_1_3_4,
     ALL_FLIP_CODES))
 {
     cv::Size size = GET_PARAM(0);
@@ -1973,7 +1973,7 @@ PERF_TEST_P(Sz_Norm, Core_NormDiff, Combine(
 PERF_TEST_P(Sz_Depth_Cn, Core_Sum, Combine(
     GPU_TYPICAL_MAT_SIZES,
     Values(CV_8U, CV_16U, CV_32F),
-    Values(1, 3, 4)))
+    GPU_CHANNELS_1_3_4))
 {
     cv::Size size = GET_PARAM(0);
     int depth = GET_PARAM(1);
@@ -2015,7 +2015,7 @@ PERF_TEST_P(Sz_Depth_Cn, Core_Sum, Combine(
 PERF_TEST_P(Sz_Depth_Cn, Core_SumAbs, Combine(
     GPU_TYPICAL_MAT_SIZES,
     Values(CV_8U, CV_16U, CV_32F),
-    Values(1, 3, 4)))
+    GPU_CHANNELS_1_3_4))
 {
     cv::Size size = GET_PARAM(0);
     int depth = GET_PARAM(1);
@@ -2052,7 +2052,7 @@ PERF_TEST_P(Sz_Depth_Cn, Core_SumAbs, Combine(
 PERF_TEST_P(Sz_Depth_Cn, Core_SumSqr, Combine(
     GPU_TYPICAL_MAT_SIZES,
     Values<MatDepth>(CV_8U, CV_16U, CV_32F),
-    Values(1, 3, 4)))
+    GPU_CHANNELS_1_3_4))
 {
     cv::Size size = GET_PARAM(0);
     int depth = GET_PARAM(1);
diff --git a/modules/gpu/perf/perf_denoising.cpp b/modules/gpu/perf/perf_denoising.cpp
new file mode 100644
index 000000000..ee76b5594
--- /dev/null
+++ b/modules/gpu/perf/perf_denoising.cpp
@@ -0,0 +1,98 @@
+#include "perf_precomp.hpp"
+
+using namespace std;
+using namespace testing;
+
+
+//////////////////////////////////////////////////////////////////////
+// BilateralFilter
+
+DEF_PARAM_TEST(Sz_Depth_Cn_KernelSz, cv::Size, MatDepth , int, int);
+
+PERF_TEST_P(Sz_Depth_Cn_KernelSz, Denoising_BilateralFilter, 
+            Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_16U, CV_32F), GPU_CHANNELS_1_3_4, Values(3, 5, 9)))
+{
+    declare.time(30.0);
+
+    cv::Size size = GET_PARAM(0);
+    int depth = GET_PARAM(1);
+    int channels = GET_PARAM(2);
+    int kernel_size = GET_PARAM(3);
+
+    float sigma_color = 7;
+    float sigma_spatial = 5;
+    int borderMode = cv::BORDER_REFLECT101;
+
+    int type = CV_MAKE_TYPE(depth, channels);
+
+    cv::Mat src(size, type);
+    fillRandom(src);
+
+     if (runOnGpu)
+    {
+        cv::gpu::GpuMat d_src(src);
+        cv::gpu::GpuMat d_dst;
+
+        cv::gpu::bilateralFilter(d_src, d_dst, kernel_size, sigma_color, sigma_spatial, borderMode);
+
+        TEST_CYCLE()
+        {
+            cv::gpu::bilateralFilter(d_src, d_dst, kernel_size, sigma_color, sigma_spatial, borderMode);
+        }
+    }
+    else
+    {
+        cv::Mat dst;
+
+        cv::bilateralFilter(src, dst, kernel_size, sigma_color, sigma_spatial, borderMode);
+
+        TEST_CYCLE()
+        {
+            cv::bilateralFilter(src, dst, kernel_size, sigma_color, sigma_spatial, borderMode);
+        }
+    }
+}
+
+
+//////////////////////////////////////////////////////////////////////
+// nonLocalMeans
+
+DEF_PARAM_TEST(Sz_Depth_Cn_WinSz_BlockSz, cv::Size, MatDepth , int, int, int);
+
+PERF_TEST_P(Sz_Depth_Cn_WinSz_BlockSz, Denoising_NonLocalMeans, 
+            Combine(GPU_TYPICAL_MAT_SIZES, Values<MatDepth>(CV_8U), Values(1), Values(21), Values(5, 7)))
+{
+    declare.time(30.0);
+
+    cv::Size size = GET_PARAM(0);
+    int depth = GET_PARAM(1);
+    int channels = GET_PARAM(2);
+    
+    int search_widow_size = GET_PARAM(3);
+    int block_size = GET_PARAM(4);
+
+    float h = 10;
+    int borderMode = cv::BORDER_REFLECT101;
+    
+    int type = CV_MAKE_TYPE(depth, channels);
+
+    cv::Mat src(size, type);
+    fillRandom(src);
+
+    if (runOnGpu)
+    {
+        cv::gpu::GpuMat d_src(src);
+        cv::gpu::GpuMat d_dst;
+
+        cv::gpu::nonLocalMeans(d_src, d_dst, h, search_widow_size, block_size, borderMode);
+
+        TEST_CYCLE()
+        {
+            cv::gpu::nonLocalMeans(d_src, d_dst, h, search_widow_size, block_size, borderMode);
+        }
+    }
+    else
+    {
+        FAIL();
+    }
+}
\ No newline at end of file
diff --git a/modules/gpu/perf/perf_imgproc.cpp b/modules/gpu/perf/perf_imgproc.cpp
index 80d4af54d..761510da3 100644
--- a/modules/gpu/perf/perf_imgproc.cpp
+++ b/modules/gpu/perf/perf_imgproc.cpp
@@ -54,7 +54,7 @@ DEF_PARAM_TEST(Sz_Depth_Cn_Inter_Border_Mode, cv::Size, MatDepth, int, Interpola
 PERF_TEST_P(Sz_Depth_Cn_Inter_Border_Mode, ImgProc_Remap, Combine(
     GPU_TYPICAL_MAT_SIZES,
     Values(CV_8U, CV_16U, CV_32F),
-    Values(1, 3, 4),
+    GPU_CHANNELS_1_3_4,
     Values(Interpolation(cv::INTER_NEAREST), Interpolation(cv::INTER_LINEAR), Interpolation(cv::INTER_CUBIC)),
     ALL_BORDER_MODES,
     ALL_REMAP_MODES))
@@ -113,7 +113,7 @@ DEF_PARAM_TEST(Sz_Depth_Cn_Inter_Scale, cv::Size, MatDepth, int, Interpolation,
 PERF_TEST_P(Sz_Depth_Cn_Inter_Scale, ImgProc_Resize, Combine(
     GPU_TYPICAL_MAT_SIZES,
     Values(CV_8U, CV_16U, CV_32F),
-    Values(1, 3, 4),
+    GPU_CHANNELS_1_3_4,
     ALL_INTERPOLATIONS,
     Values(0.5, 0.3, 2.0)))
 {
@@ -163,7 +163,7 @@ DEF_PARAM_TEST(Sz_Depth_Cn_Scale, cv::Size, MatDepth, int, double);
 PERF_TEST_P(Sz_Depth_Cn_Scale, ImgProc_ResizeArea, Combine(
     GPU_TYPICAL_MAT_SIZES,
     Values(CV_8U, CV_16U, CV_32F),
-    Values(1, 3, 4),
+    GPU_CHANNELS_1_3_4,
     Values(0.2, 0.1, 0.05)))
 {
     declare.time(1.0);
@@ -212,7 +212,7 @@ DEF_PARAM_TEST(Sz_Depth_Cn_Inter_Border, cv::Size, MatDepth, int, Interpolation,
 PERF_TEST_P(Sz_Depth_Cn_Inter_Border, ImgProc_WarpAffine, Combine(
     GPU_TYPICAL_MAT_SIZES,
     Values(CV_8U, CV_16U, CV_32F),
-    Values(1, 3, 4),
+    GPU_CHANNELS_1_3_4,
     Values(Interpolation(cv::INTER_NEAREST), Interpolation(cv::INTER_LINEAR), Interpolation(cv::INTER_CUBIC)),
     ALL_BORDER_MODES))
 {
@@ -265,7 +265,7 @@ PERF_TEST_P(Sz_Depth_Cn_Inter_Border, ImgProc_WarpAffine, Combine(
 PERF_TEST_P(Sz_Depth_Cn_Inter_Border, ImgProc_WarpPerspective, Combine(
     GPU_TYPICAL_MAT_SIZES,
     Values(CV_8U, CV_16U, CV_32F),
-    Values(1, 3, 4),
+    GPU_CHANNELS_1_3_4,
     Values(Interpolation(cv::INTER_NEAREST), Interpolation(cv::INTER_LINEAR), Interpolation(cv::INTER_CUBIC)),
     ALL_BORDER_MODES))
 {
@@ -321,7 +321,7 @@ DEF_PARAM_TEST(Sz_Depth_Cn_Border, cv::Size, MatDepth, int, BorderMode);
 PERF_TEST_P(Sz_Depth_Cn_Border, ImgProc_CopyMakeBorder, Combine(
     GPU_TYPICAL_MAT_SIZES,
     Values(CV_8U, CV_16U, CV_32F),
-    Values(1, 3, 4),
+    GPU_CHANNELS_1_3_4,
     ALL_BORDER_MODES))
 {
     cv::Size size = GET_PARAM(0);
@@ -789,7 +789,7 @@ PERF_TEST_P(Image, ImgProc_MeanShiftSegmentation, Values<string>("gpu/meanshift/
 //////////////////////////////////////////////////////////////////////
 // BlendLinear
 
-PERF_TEST_P(Sz_Depth_Cn, ImgProc_BlendLinear, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_32F), Values(1, 3, 4)))
+PERF_TEST_P(Sz_Depth_Cn, ImgProc_BlendLinear, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_32F), GPU_CHANNELS_1_3_4))
 {
     cv::Size size = GET_PARAM(0);
     int depth = GET_PARAM(1);
@@ -887,7 +887,7 @@ DEF_PARAM_TEST(Sz_TemplateSz_Cn_Method, cv::Size, cv::Size, int, TemplateMethod)
 PERF_TEST_P(Sz_TemplateSz_Cn_Method, ImgProc_MatchTemplate8U, Combine(
     GPU_TYPICAL_MAT_SIZES,
     Values(cv::Size(5, 5), cv::Size(16, 16), cv::Size(30, 30)),
-    Values(1, 3, 4),
+    GPU_CHANNELS_1_3_4,
     ALL_TEMPLATE_METHODS))
 {
     cv::Size size = GET_PARAM(0);
@@ -933,7 +933,7 @@ PERF_TEST_P(Sz_TemplateSz_Cn_Method, ImgProc_MatchTemplate8U, Combine(
 PERF_TEST_P(Sz_TemplateSz_Cn_Method, ImgProc_MatchTemplate32F, Combine(
     GPU_TYPICAL_MAT_SIZES,
     Values(cv::Size(5, 5), cv::Size(16, 16), cv::Size(30, 30)),
-    Values(1, 3, 4),
+    GPU_CHANNELS_1_3_4,
     Values(TemplateMethod(cv::TM_SQDIFF), TemplateMethod(cv::TM_CCORR))))
 {
     cv::Size size = GET_PARAM(0);
@@ -1287,7 +1287,7 @@ DEF_PARAM_TEST(Sz_Depth_Cn_Inter, cv::Size, MatDepth, int, Interpolation);
 PERF_TEST_P(Sz_Depth_Cn_Inter, ImgProc_Rotate, Combine(
     GPU_TYPICAL_MAT_SIZES,
     Values(CV_8U, CV_16U, CV_32F),
-    Values(1, 3, 4),
+    GPU_CHANNELS_1_3_4,
     Values(Interpolation(cv::INTER_NEAREST), Interpolation(cv::INTER_LINEAR), Interpolation(cv::INTER_CUBIC))))
 {
     cv::Size size = GET_PARAM(0);
@@ -1324,7 +1324,7 @@ PERF_TEST_P(Sz_Depth_Cn_Inter, ImgProc_Rotate, Combine(
 PERF_TEST_P(Sz_Depth_Cn, ImgProc_PyrDown, Combine(
     GPU_TYPICAL_MAT_SIZES,
     Values(CV_8U, CV_16U, CV_32F),
-    Values(1, 3, 4)))
+    GPU_CHANNELS_1_3_4))
 {
     cv::Size size = GET_PARAM(0);
     int depth = GET_PARAM(1);
@@ -1366,7 +1366,7 @@ PERF_TEST_P(Sz_Depth_Cn, ImgProc_PyrDown, Combine(
 PERF_TEST_P(Sz_Depth_Cn, ImgProc_PyrUp, Combine(
     GPU_TYPICAL_MAT_SIZES,
     Values(CV_8U, CV_16U, CV_32F),
-    Values(1, 3, 4)))
+    GPU_CHANNELS_1_3_4))
 {
     cv::Size size = GET_PARAM(0);
     int depth = GET_PARAM(1);
@@ -1540,7 +1540,7 @@ PERF_TEST_P(Sz_Type_Op, ImgProc_AlphaComp, Combine(GPU_TYPICAL_MAT_SIZES, Values
 //////////////////////////////////////////////////////////////////////
 // ImagePyramidBuild
 
-PERF_TEST_P(Sz_Depth_Cn, ImgProc_ImagePyramidBuild, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_16U, CV_32F), Values(1, 3, 4)))
+PERF_TEST_P(Sz_Depth_Cn, ImgProc_ImagePyramidBuild, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_16U, CV_32F), GPU_CHANNELS_1_3_4))
 {
     cv::Size size = GET_PARAM(0);
     int depth = GET_PARAM(1);
@@ -1573,7 +1573,7 @@ PERF_TEST_P(Sz_Depth_Cn, ImgProc_ImagePyramidBuild, Combine(GPU_TYPICAL_MAT_SIZE
 //////////////////////////////////////////////////////////////////////
 // ImagePyramidGetLayer
 
-PERF_TEST_P(Sz_Depth_Cn, ImgProc_ImagePyramidGetLayer, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_16U, CV_32F), Values(1, 3, 4)))
+PERF_TEST_P(Sz_Depth_Cn, ImgProc_ImagePyramidGetLayer, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_16U, CV_32F), GPU_CHANNELS_1_3_4))
 {
     cv::Size size = GET_PARAM(0);
     int depth = GET_PARAM(1);
diff --git a/modules/gpu/perf/perf_matop.cpp b/modules/gpu/perf/perf_matop.cpp
index cdae962f2..83e27875a 100644
--- a/modules/gpu/perf/perf_matop.cpp
+++ b/modules/gpu/perf/perf_matop.cpp
@@ -8,7 +8,7 @@ namespace {
 //////////////////////////////////////////////////////////////////////
 // SetTo
 
-PERF_TEST_P(Sz_Depth_Cn, MatOp_SetTo, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_16U, CV_32F, CV_64F), Values(1, 3, 4)))
+PERF_TEST_P(Sz_Depth_Cn, MatOp_SetTo, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_16U, CV_32F, CV_64F), GPU_CHANNELS_1_3_4))
 {
     cv::Size size = GET_PARAM(0);
     int depth = GET_PARAM(1);
@@ -45,7 +45,7 @@ PERF_TEST_P(Sz_Depth_Cn, MatOp_SetTo, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8
 //////////////////////////////////////////////////////////////////////
 // SetToMasked
 
-PERF_TEST_P(Sz_Depth_Cn, MatOp_SetToMasked, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_16U, CV_32F, CV_64F), Values(1, 3, 4)))
+PERF_TEST_P(Sz_Depth_Cn, MatOp_SetToMasked, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_16U, CV_32F, CV_64F), GPU_CHANNELS_1_3_4))
 {
     cv::Size size = GET_PARAM(0);
     int depth = GET_PARAM(1);
@@ -87,7 +87,7 @@ PERF_TEST_P(Sz_Depth_Cn, MatOp_SetToMasked, Combine(GPU_TYPICAL_MAT_SIZES, Value
 //////////////////////////////////////////////////////////////////////
 // CopyToMasked
 
-PERF_TEST_P(Sz_Depth_Cn, MatOp_CopyToMasked, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_16U, CV_32F, CV_64F), Values(1, 3, 4)))
+PERF_TEST_P(Sz_Depth_Cn, MatOp_CopyToMasked, Combine(GPU_TYPICAL_MAT_SIZES, Values(CV_8U, CV_16U, CV_32F, CV_64F), GPU_CHANNELS_1_3_4))
 {
     cv::Size size = GET_PARAM(0);
     int depth = GET_PARAM(1);
diff --git a/modules/gpu/perf/perf_video.cpp b/modules/gpu/perf/perf_video.cpp
index aa802fbf5..7a6403469 100644
--- a/modules/gpu/perf/perf_video.cpp
+++ b/modules/gpu/perf/perf_video.cpp
@@ -423,7 +423,7 @@ PERF_TEST_P(Video, Video_FGDStatModel, Values("gpu/video/768x576.avi", "gpu/vide
 
 DEF_PARAM_TEST(Video_Cn_LearningRate, string, int, double);
 
-PERF_TEST_P(Video_Cn_LearningRate, Video_MOG, Combine(Values("gpu/video/768x576.avi", "gpu/video/1920x1080.avi"), Values(1, 3, 4), Values(0.0, 0.01)))
+PERF_TEST_P(Video_Cn_LearningRate, Video_MOG, Combine(Values("gpu/video/768x576.avi", "gpu/video/1920x1080.avi"), GPU_CHANNELS_1_3_4, Values(0.0, 0.01)))
 {
     string inputFile = perf::TestBase::getDataPath(GET_PARAM(0));
     int cn = GET_PARAM(1);
@@ -511,7 +511,7 @@ PERF_TEST_P(Video_Cn_LearningRate, Video_MOG, Combine(Values("gpu/video/768x576.
 
 DEF_PARAM_TEST(Video_Cn, string, int);
 
-PERF_TEST_P(Video_Cn, Video_MOG2, Combine(Values("gpu/video/768x576.avi", "gpu/video/1920x1080.avi"), Values(1, 3, 4)))
+PERF_TEST_P(Video_Cn, Video_MOG2, Combine(Values("gpu/video/768x576.avi", "gpu/video/1920x1080.avi"), GPU_CHANNELS_1_3_4))
 {
     string inputFile = perf::TestBase::getDataPath(GET_PARAM(0));
     int cn = GET_PARAM(1);
@@ -596,7 +596,7 @@ PERF_TEST_P(Video_Cn, Video_MOG2, Combine(Values("gpu/video/768x576.avi", "gpu/v
 //////////////////////////////////////////////////////
 // MOG2GetBackgroundImage
 
-PERF_TEST_P(Video_Cn, Video_MOG2GetBackgroundImage, Combine(Values("gpu/video/768x576.avi", "gpu/video/1920x1080.avi"), Values(1, 3, 4)))
+PERF_TEST_P(Video_Cn, Video_MOG2GetBackgroundImage, Combine(Values("gpu/video/768x576.avi", "gpu/video/1920x1080.avi"), GPU_CHANNELS_1_3_4))
 {
     string inputFile = perf::TestBase::getDataPath(GET_PARAM(0));
     int cn = GET_PARAM(1);
@@ -676,7 +676,7 @@ PERF_TEST_P(Video_Cn, Video_MOG2GetBackgroundImage, Combine(Values("gpu/video/76
 //////////////////////////////////////////////////////
 // VIBE
 
-PERF_TEST_P(Video_Cn, Video_VIBE, Combine(Values("gpu/video/768x576.avi", "gpu/video/1920x1080.avi"), Values(1, 3, 4)))
+PERF_TEST_P(Video_Cn, Video_VIBE, Combine(Values("gpu/video/768x576.avi", "gpu/video/1920x1080.avi"), GPU_CHANNELS_1_3_4))
 {
     string inputFile = perf::TestBase::getDataPath(GET_PARAM(0));
     int cn = GET_PARAM(1);
@@ -739,7 +739,7 @@ PERF_TEST_P(Video_Cn, Video_VIBE, Combine(Values("gpu/video/768x576.avi", "gpu/v
 
 DEF_PARAM_TEST(Video_Cn_MaxFeatures, string, int, int);
 
-PERF_TEST_P(Video_Cn_MaxFeatures, Video_GMG, Combine(Values("gpu/video/768x576.avi", "gpu/video/1920x1080.avi"), Values(1, 3, 4), Values(20, 40, 60)))
+PERF_TEST_P(Video_Cn_MaxFeatures, Video_GMG, Combine(Values("gpu/video/768x576.avi", "gpu/video/1920x1080.avi"), GPU_CHANNELS_1_3_4, Values(20, 40, 60)))
 {
     std::string inputFile = perf::TestBase::getDataPath(GET_PARAM(0));
     int cn = GET_PARAM(1);
diff --git a/modules/gpu/perf/utility.hpp b/modules/gpu/perf/utility.hpp
index 441d32adb..d2e3a070f 100644
--- a/modules/gpu/perf/utility.hpp
+++ b/modules/gpu/perf/utility.hpp
@@ -41,5 +41,6 @@ DEF_PARAM_TEST(Sz_Depth, cv::Size, MatDepth);
 DEF_PARAM_TEST(Sz_Depth_Cn, cv::Size, MatDepth, int);
 
 #define GPU_TYPICAL_MAT_SIZES testing::Values(perf::sz720p, perf::szSXGA, perf::sz1080p)
+#define GPU_CHANNELS_1_3_4 testing::Values(1, 3, 4)
 
 #endif // __OPENCV_PERF_GPU_UTILITY_HPP__
diff --git a/modules/gpu/src/cuda/bilateral_filter.cu b/modules/gpu/src/cuda/bilateral_filter.cu
index abae91d2c..9e9135e10 100644
--- a/modules/gpu/src/cuda/bilateral_filter.cu
+++ b/modules/gpu/src/cuda/bilateral_filter.cu
@@ -12,6 +12,7 @@
 //
 // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
 // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
+// Copyright (C) 1993-2011, NVIDIA Corporation, all rights reserved.
 // Third party copyrights are property of their respective owners.
 //
 // Redistribution and use in source and binary forms, with or without modification,
@@ -28,7 +29,7 @@
 //     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
+// any express or bpied warranties, including, but not limited to, the bpied
 // 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
@@ -41,186 +42,155 @@
 //M*/
 
 #include "internal_shared.hpp"
-#include "opencv2/gpu/device/limits.hpp"
+
+#include "opencv2/gpu/device/vec_traits.hpp"
+#include "opencv2/gpu/device/vec_math.hpp"
+#include "opencv2/gpu/device/border_interpolate.hpp"
+
+using namespace cv::gpu;
+
+typedef unsigned char uchar;
+typedef unsigned short ushort;
+
+//////////////////////////////////////////////////////////////////////////////////
+/// Bilateral filtering
 
 namespace cv { namespace gpu { namespace device
 {
-    namespace bilateral_filter
+    namespace imgproc
     {
-        __constant__ float* ctable_color;
-        __constant__ float* ctable_space;
-        __constant__ size_t ctable_space_step;
+        __device__ __forceinline__ float norm_l1(const float& a)  { return ::fabs(a); }
+        __device__ __forceinline__ float norm_l1(const float2& a) { return ::fabs(a.x) + ::fabs(a.y); }
+        __device__ __forceinline__ float norm_l1(const float3& a) { return ::fabs(a.x) + ::fabs(a.y) + ::fabs(a.z); }
+        __device__ __forceinline__ float norm_l1(const float4& a) { return ::fabs(a.x) + ::fabs(a.y) + ::fabs(a.z) + ::fabs(a.w); }
 
-        __constant__ int cndisp;
-        __constant__ int cradius;
+        __device__ __forceinline__ float sqr(const float& a)  { return a * a; }
 
-        __constant__ short cedge_disc;
-        __constant__ short cmax_disc;
-
-        void load_constants(float* table_color, PtrStepSzf table_space, int ndisp, int radius, short edge_disc, short max_disc)
+        template<typename T, typename B> 
+        __global__ void bilateral_kernel(const PtrStepSz<T> src, PtrStep<T> dst, const B b, const int ksz, const float sigma_spatial2_inv_half, const float sigma_color2_inv_half)
         {
-            cudaSafeCall( cudaMemcpyToSymbol(ctable_color, &table_color, sizeof(table_color)) );
-            cudaSafeCall( cudaMemcpyToSymbol(ctable_space, &table_space.data, sizeof(table_space.data)) );
-            size_t table_space_step = table_space.step / sizeof(float);
-            cudaSafeCall( cudaMemcpyToSymbol(ctable_space_step, &table_space_step, sizeof(size_t)) );
+            typedef typename TypeVec<float, VecTraits<T>::cn>::vec_type value_type;
+            
+            int x = threadIdx.x + blockIdx.x * blockDim.x;
+            int y = threadIdx.y + blockIdx.y * blockDim.y;
 
-            cudaSafeCall( cudaMemcpyToSymbol(cndisp, &ndisp, sizeof(int)) );
-            cudaSafeCall( cudaMemcpyToSymbol(cradius, &radius, sizeof(int)) );
+            if (x >= src.cols || y >= src.rows)
+                return;
 
-            cudaSafeCall( cudaMemcpyToSymbol(cedge_disc, &edge_disc, sizeof(short)) );
-            cudaSafeCall( cudaMemcpyToSymbol(cmax_disc, &max_disc, sizeof(short)) );
+            value_type center = saturate_cast<value_type>(src(y, x));
+
+            value_type sum1 = VecTraits<value_type>::all(0);
+            float sum2 = 0;
+
+            int r = ksz / 2;
+            float r2 = (float)(r * r);
+
+            int tx = x - r + ksz;
+            int ty = y - r + ksz;
+
+            if (x - ksz/2 >=0 && y - ksz/2 >=0 && tx < src.cols && ty < src.rows)
+            {
+                for (int cy = y - r; cy < ty; ++cy)
+                    for (int cx = x - r; cx < tx; ++cx)
+                    {
+                        float space2 = (x - cx) * (x - cx) + (y - cy) * (y - cy);
+                        if (space2 > r2)
+                            continue;
+
+                        value_type value = saturate_cast<value_type>(src(cy, cx));
+
+                        float weight = ::exp(space2 * sigma_spatial2_inv_half + sqr(norm_l1(value - center)) * sigma_color2_inv_half);
+                        sum1 = sum1 + weight * value;
+                        sum2 = sum2 + weight;
+                    }
+            }
+            else
+            {
+                for (int cy = y - r; cy < ty; ++cy)
+                    for (int cx = x - r; cx < tx; ++cx)
+                    {
+                        float space2 = (x - cx) * (x - cx) + (y - cy) * (y - cy);
+                        if (space2 > r2)
+                            continue;
+
+                        value_type value = saturate_cast<value_type>(b.at(cy, cx, src.data, src.step));
+
+                        float weight = ::exp(space2 * sigma_spatial2_inv_half + sqr(norm_l1(value - center)) * sigma_color2_inv_half);
+
+                        sum1 = sum1 + weight * value;
+                        sum2 = sum2 + weight;
+                    }
+            }
+            dst(y, x) = saturate_cast<T>(sum1 / sum2);
         }
 
-        template <int channels>
-        struct DistRgbMax
+        template<typename T, template <typename> class B>
+        void bilateral_caller(const PtrStepSzb& src, PtrStepSzb dst, int kernel_size, float sigma_spatial, float sigma_color, cudaStream_t stream)
         {
-            static __device__ __forceinline__ uchar calc(const uchar* a, const uchar* b)
-            {
-                uchar x = ::abs(a[0] - b[0]);
-                uchar y = ::abs(a[1] - b[1]);
-                uchar z = ::abs(a[2] - b[2]);
-                return (::max(::max(x, y), z));
-            }
-        };
+            dim3 block (32, 8);
+            dim3 grid (divUp (src.cols, block.x), divUp (src.rows, block.y));
 
-        template <>
-        struct DistRgbMax<1>
-        {
-            static __device__ __forceinline__ uchar calc(const uchar* a, const uchar* b)
-            {
-                return ::abs(a[0] - b[0]);
-            }
-        };
+            B<T> b(src.rows, src.cols);
 
-        template <int channels, typename T>
-        __global__ void bilateral_filter(int t, T* disp, size_t disp_step, const uchar* img, size_t img_step, int h, int w)
-        {
-            const int y = blockIdx.y * blockDim.y + threadIdx.y;
-            const int x = ((blockIdx.x * blockDim.x + threadIdx.x) << 1) + ((y + t) & 1);
+            float sigma_spatial2_inv_half = -0.5f/(sigma_spatial * sigma_spatial);
+             float sigma_color2_inv_half = -0.5f/(sigma_color * sigma_color);
 
-            T dp[5];
-
-            if (y > 0 && y < h - 1 && x > 0 && x < w - 1)
-            {
-                dp[0] = *(disp + (y  ) * disp_step + x + 0);
-                dp[1] = *(disp + (y-1) * disp_step + x + 0);
-                dp[2] = *(disp + (y  ) * disp_step + x - 1);
-                dp[3] = *(disp + (y+1) * disp_step + x + 0);
-                dp[4] = *(disp + (y  ) * disp_step + x + 1);
-
-                if(::abs(dp[1] - dp[0]) >= cedge_disc || ::abs(dp[2] - dp[0]) >= cedge_disc || ::abs(dp[3] - dp[0]) >= cedge_disc || ::abs(dp[4] - dp[0]) >= cedge_disc)
-                {
-                    const int ymin = ::max(0, y - cradius);
-                    const int xmin = ::max(0, x - cradius);
-                    const int ymax = ::min(h - 1, y + cradius);
-                    const int xmax = ::min(w - 1, x + cradius);
-
-                    float cost[] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
-
-                    const uchar* ic = img + y * img_step + channels * x;
-
-                    for(int yi = ymin; yi <= ymax; yi++)
-                    {
-                        const T* disp_y = disp + yi * disp_step;
-
-                        for(int xi = xmin; xi <= xmax; xi++)
-                        {
-                            const uchar* in = img + yi * img_step + channels * xi;
-
-                            uchar dist_rgb = DistRgbMax<channels>::calc(in, ic);
-
-                            const float weight = ctable_color[dist_rgb] * (ctable_space + ::abs(y-yi)* ctable_space_step)[::abs(x-xi)];
-
-                            const T disp_reg = disp_y[xi];
-
-                            cost[0] += ::min(cmax_disc, ::abs(disp_reg - dp[0])) * weight;
-                            cost[1] += ::min(cmax_disc, ::abs(disp_reg - dp[1])) * weight;
-                            cost[2] += ::min(cmax_disc, ::abs(disp_reg - dp[2])) * weight;
-                            cost[3] += ::min(cmax_disc, ::abs(disp_reg - dp[3])) * weight;
-                            cost[4] += ::min(cmax_disc, ::abs(disp_reg - dp[4])) * weight;
-                        }
-                    }
-
-                    float minimum = numeric_limits<float>::max();
-                    int id = 0;
-
-                    if (cost[0] < minimum)
-                    {
-                        minimum = cost[0];
-                        id = 0;
-                    }
-                    if (cost[1] < minimum)
-                    {
-                        minimum = cost[1];
-                        id = 1;
-                    }
-                    if (cost[2] < minimum)
-                    {
-                        minimum = cost[2];
-                        id = 2;
-                    }
-                    if (cost[3] < minimum)
-                    {
-                        minimum = cost[3];
-                        id = 3;
-                    }
-                    if (cost[4] < minimum)
-                    {
-                        minimum = cost[4];
-                        id = 4;
-                    }
-
-                    *(disp + y * disp_step + x) = dp[id];
-                }
-            }
-        }
-
-        template <typename T>
-        void bilateral_filter_caller(PtrStepSz<T> disp, PtrStepSzb img, int channels, int iters, cudaStream_t stream)
-        {
-            dim3 threads(32, 8, 1);
-            dim3 grid(1, 1, 1);
-            grid.x = divUp(disp.cols, threads.x << 1);
-            grid.y = divUp(disp.rows, threads.y);
-
-            switch (channels)
-            {
-            case 1:
-                for (int i = 0; i < iters; ++i)
-                {
-                    bilateral_filter<1><<<grid, threads, 0, stream>>>(0, disp.data, disp.step/sizeof(T), img.data, img.step, disp.rows, disp.cols);
-                    cudaSafeCall( cudaGetLastError() );
-
-                    bilateral_filter<1><<<grid, threads, 0, stream>>>(1, disp.data, disp.step/sizeof(T), img.data, img.step, disp.rows, disp.cols);
-                    cudaSafeCall( cudaGetLastError() );
-                }
-                break;
-            case 3:
-                for (int i = 0; i < iters; ++i)
-                {
-                    bilateral_filter<3><<<grid, threads, 0, stream>>>(0, disp.data, disp.step/sizeof(T), img.data, img.step, disp.rows, disp.cols);
-                    cudaSafeCall( cudaGetLastError() );
-
-                    bilateral_filter<3><<<grid, threads, 0, stream>>>(1, disp.data, disp.step/sizeof(T), img.data, img.step, disp.rows, disp.cols);
-                    cudaSafeCall( cudaGetLastError() );
-                }
-                break;
-            default:
-                cv::gpu::error("Unsupported channels count", __FILE__, __LINE__, "bilateral_filter_caller");
-            }
+            cudaSafeCall( cudaFuncSetCacheConfig (bilateral_kernel<T, B<T> >, cudaFuncCachePreferL1) );
+            bilateral_kernel<<<grid, block>>>((PtrStepSz<T>)src, (PtrStepSz<T>)dst, b, kernel_size, sigma_spatial2_inv_half, sigma_color2_inv_half);
+            cudaSafeCall ( cudaGetLastError () );
 
             if (stream == 0)
                 cudaSafeCall( cudaDeviceSynchronize() );
         }
 
-        void bilateral_filter_gpu(PtrStepSzb disp, PtrStepSzb img, int channels, int iters, cudaStream_t stream)
+        template<typename T>
+        void bilateral_filter_gpu(const PtrStepSzb& src, PtrStepSzb dst, int kernel_size, float gauss_spatial_coeff, float gauss_color_coeff, int borderMode, cudaStream_t stream)
         {
-            bilateral_filter_caller(disp, img, channels, iters, stream);
-        }
+            typedef void (*caller_t)(const PtrStepSzb& src, PtrStepSzb dst, int kernel_size, float sigma_spatial, float sigma_color, cudaStream_t stream);
 
-        void bilateral_filter_gpu(PtrStepSz<short> disp, PtrStepSzb img, int channels, int iters, cudaStream_t stream)
-        {
-            bilateral_filter_caller(disp, img, channels, iters, stream);
+            static caller_t funcs[] = 
+            {
+                bilateral_caller<T, BrdReflect101>,
+                bilateral_caller<T, BrdReplicate>,
+                bilateral_caller<T, BrdConstant>,
+                bilateral_caller<T, BrdReflect>,
+                bilateral_caller<T, BrdWrap>,
+            };
+            funcs[borderMode](src, dst, kernel_size, gauss_spatial_coeff, gauss_color_coeff, stream);
         }
-    } // namespace bilateral_filter
-}}} // namespace cv { namespace gpu { namespace device
+    }
+}}}
+
+
+#define OCV_INSTANTIATE_BILATERAL_FILTER(T) \
+    template void cv::gpu::device::imgproc::bilateral_filter_gpu<T>(const PtrStepSzb&, PtrStepSzb, int, float, float, int, cudaStream_t);
+
+OCV_INSTANTIATE_BILATERAL_FILTER(uchar)
+//OCV_INSTANTIATE_BILATERAL_FILTER(uchar2)
+OCV_INSTANTIATE_BILATERAL_FILTER(uchar3)
+OCV_INSTANTIATE_BILATERAL_FILTER(uchar4)
+
+//OCV_INSTANTIATE_BILATERAL_FILTER(schar)
+//OCV_INSTANTIATE_BILATERAL_FILTER(schar2)
+//OCV_INSTANTIATE_BILATERAL_FILTER(schar3)
+//OCV_INSTANTIATE_BILATERAL_FILTER(schar4)
+
+OCV_INSTANTIATE_BILATERAL_FILTER(short)
+//OCV_INSTANTIATE_BILATERAL_FILTER(short2)
+OCV_INSTANTIATE_BILATERAL_FILTER(short3)
+OCV_INSTANTIATE_BILATERAL_FILTER(short4)
+
+OCV_INSTANTIATE_BILATERAL_FILTER(ushort)
+//OCV_INSTANTIATE_BILATERAL_FILTER(ushort2)
+OCV_INSTANTIATE_BILATERAL_FILTER(ushort3)
+OCV_INSTANTIATE_BILATERAL_FILTER(ushort4)
+
+//OCV_INSTANTIATE_BILATERAL_FILTER(int)
+//OCV_INSTANTIATE_BILATERAL_FILTER(int2)
+//OCV_INSTANTIATE_BILATERAL_FILTER(int3)
+//OCV_INSTANTIATE_BILATERAL_FILTER(int4)
+
+OCV_INSTANTIATE_BILATERAL_FILTER(float)
+//OCV_INSTANTIATE_BILATERAL_FILTER(float2)
+OCV_INSTANTIATE_BILATERAL_FILTER(float3)
+OCV_INSTANTIATE_BILATERAL_FILTER(float4)
diff --git a/modules/gpu/src/cuda/nlm.cu b/modules/gpu/src/cuda/nlm.cu
new file mode 100644
index 000000000..1acbe7fe7
--- /dev/null
+++ b/modules/gpu/src/cuda/nlm.cu
@@ -0,0 +1,143 @@
+/*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) 1993-2011, NVIDIA Corporation, 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 bpied warranties, including, but not limited to, the bpied
+// 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 "internal_shared.hpp"
+
+#include "opencv2/gpu/device/vec_traits.hpp"
+#include "opencv2/gpu/device/vec_math.hpp"
+#include "opencv2/gpu/device/border_interpolate.hpp"
+
+using namespace cv::gpu;
+
+typedef unsigned char uchar;
+typedef unsigned short ushort;
+
+//////////////////////////////////////////////////////////////////////////////////
+/// Non local means denosings
+
+namespace cv { namespace gpu { namespace device
+{
+    namespace imgproc
+    {
+        __device__ __forceinline__ float norm2(const float& v) { return v*v; }
+        __device__ __forceinline__ float norm2(const float2& v) { return v.x*v.x + v.y*v.y; }
+        __device__ __forceinline__ float norm2(const float3& v) { return v.x*v.x + v.y*v.y + v.z*v.z; }
+        __device__ __forceinline__ float norm2(const float4& v) { return v.x*v.x + v.y*v.y + v.z*v.z  + v.w*v.w; }
+
+        template<typename T, typename B>
+        __global__ void nlm_kernel(const PtrStepSz<T> src, PtrStep<T> dst, const B b, int search_radius, int block_radius, float h2_inv_half)
+        {
+            typedef typename TypeVec<float, VecTraits<T>::cn>::vec_type value_type;
+
+            const int x = blockDim.x * blockIdx.x + threadIdx.x;
+            const int y = blockDim.y * blockIdx.y + threadIdx.y;
+
+            if (x >= src.cols || y >= src.rows)
+                return;
+
+            float block_radius2_inv = -1.f/(block_radius * block_radius);
+
+            value_type sum1 = VecTraits<value_type>::all(0);
+            float sum2 = 0.f;
+
+            for(float cy = -search_radius; cy <= search_radius; ++cy)
+                for(float cx = -search_radius; cx <= search_radius; ++cx)
+                {
+                    float color2 = 0;
+                    for(float by = -block_radius; by <= block_radius; ++by)
+                        for(float bx = -block_radius; bx <= block_radius; ++bx)
+                        {
+                            value_type v1 = saturate_cast<value_type>(src(y + by, x + bx));
+                            value_type v2 = saturate_cast<value_type>(src(y + cy + by, x + cx + bx));
+                            color2 += norm2(v1 - v2);
+                        }
+
+                    float dist2 = cx * cx + cy * cy;
+                    float w = __expf(color2 * h2_inv_half + dist2 * block_radius2_inv);
+                    
+                    sum1 = sum1 + saturate_cast<value_type>(src(y + cy, x + cy)) * w;
+                    sum2 += w;
+                }
+
+            dst(y, x) = saturate_cast<T>(sum1 / sum2);
+
+        }
+
+        template<typename T, template <typename> class B>
+        void nlm_caller(const PtrStepSzb src, PtrStepSzb dst, int search_radius, int block_radius, float h, cudaStream_t stream)
+        {
+            dim3 block (32, 8);
+            dim3 grid (divUp (src.cols, block.x), divUp (src.rows, block.y));
+
+            B<T> b(src.rows, src.cols);
+
+            float h2_inv_half = -0.5f/(h * h * VecTraits<T>::cn);
+
+            cudaSafeCall( cudaFuncSetCacheConfig (nlm_kernel<T, B<T> >, cudaFuncCachePreferL1) );
+            nlm_kernel<<<grid, block>>>((PtrStepSz<T>)src, (PtrStepSz<T>)dst, b, search_radius, block_radius, h2_inv_half);
+            cudaSafeCall ( cudaGetLastError () );
+
+            if (stream == 0)
+                cudaSafeCall( cudaDeviceSynchronize() );
+        }
+
+        template<typename T>
+        void nlm_bruteforce_gpu(const PtrStepSzb& src, PtrStepSzb dst, int search_radius, int block_radius, float h, int borderMode, cudaStream_t stream)
+        {
+            typedef void (*func_t)(const PtrStepSzb src, PtrStepSzb dst, int search_radius, int block_radius, float h, cudaStream_t stream);
+
+            static func_t funcs[] = 
+            {
+                nlm_caller<T, BrdReflect101>,
+                nlm_caller<T, BrdReplicate>,
+                nlm_caller<T, BrdConstant>,
+                nlm_caller<T, BrdReflect>,
+                nlm_caller<T, BrdWrap>,
+            };
+            funcs[borderMode](src, dst, search_radius, block_radius, h, stream);
+        }
+
+        template void nlm_bruteforce_gpu<uchar>(const PtrStepSzb&, PtrStepSzb, int, int, float, int, cudaStream_t);
+        template void nlm_bruteforce_gpu<uchar3>(const PtrStepSzb&, PtrStepSzb, int, int, float, int, cudaStream_t);
+    }
+}}}
diff --git a/modules/gpu/src/denoising.cpp b/modules/gpu/src/denoising.cpp
new file mode 100644
index 000000000..f7dd2fbfa
--- /dev/null
+++ b/modules/gpu/src/denoising.cpp
@@ -0,0 +1,135 @@
+/*M///////////////////////////////////////////////////////////////////////////////////////
+//
+//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
+//
+//  By downloading, copying, installing or using the software you agree to this license.
+//  If you do not agree to this license, do not download, install,
+//  copy or use the software.
+//
+//
+//                           License Agreement
+//                For Open Source Computer Vision Library
+//
+// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
+// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
+// Third party copyrights are property of their respective owners.
+//
+// Redistribution and use in source and binary forms, with or without modification,
+// are permitted provided that the following conditions are met:
+//
+//   * Redistribution's of source code must retain the above copyright notice,
+//     this list of conditions and the following disclaimer.
+//
+//   * Redistribution's in binary form must reproduce the above copyright notice,
+//     this list of conditions and the following disclaimer in the documentation
+//     and/or other GpuMaterials 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 bpied warranties, including, but not limited to, the bpied
+// 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)
+
+cv::gpu::bilateralFilter(const GpuMat&, GpuMat&, int, float, float, int, Stream&) { throw_nogpu(); }
+
+#else
+
+
+namespace cv { namespace gpu { namespace device
+{
+    namespace imgproc
+    {
+        template<typename T>
+        void bilateral_filter_gpu(const PtrStepSzb& src, PtrStepSzb dst, int kernel_size, float sigma_spatial, float sigma_color, int borderMode, cudaStream_t stream);
+
+        template<typename T>
+        void nlm_bruteforce_gpu(const PtrStepSzb& src, PtrStepSzb dst, int search_radius, int block_radius, float h, int borderMode, cudaStream_t stream);
+    }
+}}}
+
+void cv::gpu::bilateralFilter(const GpuMat& src, GpuMat& dst, int kernel_size, float sigma_color, float sigma_spatial, int borderMode, Stream& s)
+{
+    using cv::gpu::device::imgproc::bilateral_filter_gpu;
+
+    typedef void (*func_t)(const PtrStepSzb& src, PtrStepSzb dst, int kernel_size, float sigma_spatial, float sigma_color, int borderMode, cudaStream_t s);
+
+    static const func_t funcs[6][4] =
+    {
+        {bilateral_filter_gpu<uchar>      , 0 /*bilateral_filter_gpu<uchar2>*/ , bilateral_filter_gpu<uchar3>      , bilateral_filter_gpu<uchar4>      },
+        {0 /*bilateral_filter_gpu<schar>*/, 0 /*bilateral_filter_gpu<schar2>*/ , 0 /*bilateral_filter_gpu<schar3>*/, 0 /*bilateral_filter_gpu<schar4>*/},
+        {bilateral_filter_gpu<ushort>     , 0 /*bilateral_filter_gpu<ushort2>*/, bilateral_filter_gpu<ushort3>     , bilateral_filter_gpu<ushort4>     },
+        {bilateral_filter_gpu<short>      , 0 /*bilateral_filter_gpu<short2>*/ , bilateral_filter_gpu<short3>      , bilateral_filter_gpu<short4>      },
+        {0 /*bilateral_filter_gpu<int>*/  , 0 /*bilateral_filter_gpu<int2>*/   , 0 /*bilateral_filter_gpu<int3>*/  , 0 /*bilateral_filter_gpu<int4>*/  },
+        {bilateral_filter_gpu<float>      , 0 /*bilateral_filter_gpu<float2>*/ , bilateral_filter_gpu<float3>      , bilateral_filter_gpu<float4>      }
+    };
+
+    sigma_color = (sigma_color <= 0 ) ? 1 : sigma_color;
+    sigma_spatial = (sigma_spatial <= 0 ) ? 1 : sigma_spatial;
+    
+    
+    int radius = (kernel_size <= 0) ? cvRound(sigma_spatial*1.5) : kernel_size/2;
+    kernel_size = std::max(radius, 1)*2 + 1;
+
+    CV_Assert(src.depth() <= CV_32F && src.channels() <= 4);
+    const func_t func = funcs[src.depth()][src.channels() - 1];
+    CV_Assert(func != 0);
+
+    CV_Assert(borderMode == BORDER_REFLECT101 || borderMode == BORDER_REPLICATE || borderMode == BORDER_CONSTANT || borderMode == BORDER_REFLECT || borderMode == BORDER_WRAP);
+
+    int gpuBorderType;
+    CV_Assert(tryConvertToGpuBorderType(borderMode, gpuBorderType));
+
+    dst.create(src.size(), src.type());
+    func(src, dst, kernel_size, sigma_spatial, sigma_color, gpuBorderType, StreamAccessor::getStream(s));
+}
+
+void cv::gpu::nonLocalMeans(const GpuMat& src, GpuMat& dst, float h, int search_window_size, int block_size, int borderMode, Stream& s)
+{
+    using cv::gpu::device::imgproc::nlm_bruteforce_gpu;
+    typedef void (*func_t)(const PtrStepSzb& src, PtrStepSzb dst, int search_radius, int block_radius, float h, int borderMode, cudaStream_t stream);
+
+    static const func_t funcs[4] = { nlm_bruteforce_gpu<uchar>, 0 /*nlm_bruteforce_gpu<uchar2>*/ , nlm_bruteforce_gpu<uchar3>, 0/*nlm_bruteforce_gpu<uchar4>,*/ };
+
+    CV_Assert(src.type() == CV_8U || src.type() == CV_8UC3);
+
+    const func_t func = funcs[src.channels() - 1];
+    CV_Assert(func != 0);
+
+    int b = borderMode;
+    CV_Assert(b == BORDER_REFLECT101 || b == BORDER_REPLICATE || b == BORDER_CONSTANT || b == BORDER_REFLECT || b == BORDER_WRAP);
+
+    int gpuBorderType;
+    CV_Assert(tryConvertToGpuBorderType(borderMode, gpuBorderType));
+
+    int search_radius = search_window_size/2;
+    int block_radius = block_size/2;
+
+    dst.create(src.size(), src.type());
+    func(src, dst, search_radius, block_radius, h, gpuBorderType, StreamAccessor::getStream(s));
+}
+
+
+
+
+
+
+
+
+#endif
\ No newline at end of file
diff --git a/modules/gpu/src/hough.cpp b/modules/gpu/src/hough.cpp
index fd5305700..399de3684 100644
--- a/modules/gpu/src/hough.cpp
+++ b/modules/gpu/src/hough.cpp
@@ -239,8 +239,8 @@ void cv::gpu::HoughCircles(const GpuMat& src, GpuMat& circles, HoughCirclesBuf&
 
                     for(size_t j = 0; j < m.size(); ++j)
                     {
-                        float dx = p.x - m[j].x;
-                        float dy = p.y - m[j].y;
+                        float dx = (float)(p.x - m[j].x);
+                        float dy = (float)(p.y - m[j].y);
 
                         if (dx * dx + dy * dy < minDist)
                         {
diff --git a/modules/gpu/src/opencv2/gpu/device/functional.hpp b/modules/gpu/src/opencv2/gpu/device/functional.hpp
index 1b836c7a5..96e96bded 100644
--- a/modules/gpu/src/opencv2/gpu/device/functional.hpp
+++ b/modules/gpu/src/opencv2/gpu/device/functional.hpp
@@ -47,6 +47,7 @@
 #include "saturate_cast.hpp"
 #include "vec_traits.hpp"
 #include "type_traits.hpp"
+#include "device_functions.h"
 
 namespace cv { namespace gpu { namespace device
 {
@@ -408,6 +409,7 @@ namespace cv { namespace gpu { namespace device
     OPENCV_GPU_IMPLEMENT_BIN_FUNCTOR(pow, ::pow)
 
     #undef OPENCV_GPU_IMPLEMENT_UN_FUNCTOR
+    #undef OPENCV_GPU_IMPLEMENT_UN_FUNCTOR_NO_DOUBLE
     #undef OPENCV_GPU_IMPLEMENT_BIN_FUNCTOR
 
     template<typename T> struct hypot_sqr_func : binary_function<T, T, float>
diff --git a/modules/gpu/test/test_denoising.cpp b/modules/gpu/test/test_denoising.cpp
new file mode 100644
index 000000000..0f6cd69c5
--- /dev/null
+++ b/modules/gpu/test/test_denoising.cpp
@@ -0,0 +1,140 @@
+/*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.
+//
+//
+//                        Intel License Agreement
+//                For Open Source Computer Vision Library
+//
+// Copyright (C) 2000, Intel Corporation, 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 Intel Corporation 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
+
+////////////////////////////////////////////////////////
+// BilateralFilter
+
+PARAM_TEST_CASE(BilateralFilter, cv::gpu::DeviceInfo, cv::Size, MatType)
+{
+    cv::gpu::DeviceInfo devInfo;
+    cv::Size size;
+    int type;
+    int kernel_size;
+    float sigma_color;
+    float sigma_spatial;
+
+    virtual void SetUp()
+    {
+        devInfo = GET_PARAM(0);
+        size = GET_PARAM(1);
+        type = GET_PARAM(2);
+
+        kernel_size = 5;
+        sigma_color = 10.f;
+        sigma_spatial = 3.5f;
+
+        cv::gpu::setDevice(devInfo.deviceID());
+    }
+};
+
+TEST_P(BilateralFilter, Accuracy)
+{
+    cv::Mat src = randomMat(size, type);
+    //cv::Mat src = readImage("hog/road.png", cv::IMREAD_GRAYSCALE);
+    //cv::Mat src = readImage("csstereobp/aloe-R.png", cv::IMREAD_GRAYSCALE);
+
+    src.convertTo(src, type);
+    cv::gpu::GpuMat dst;
+
+    cv::gpu::bilateralFilter(loadMat(src), dst, kernel_size, sigma_color, sigma_spatial);
+
+    cv::Mat dst_gold;
+    cv::bilateralFilter(src, dst_gold, kernel_size, sigma_color, sigma_spatial);
+
+    EXPECT_MAT_NEAR(dst_gold, dst, src.depth() == CV_32F ? 1e-3 : 1.0);
+}
+
+INSTANTIATE_TEST_CASE_P(GPU_ImgProc, BilateralFilter, testing::Combine(
+    ALL_DEVICES,
+    testing::Values(cv::Size(128, 128), cv::Size(113, 113), cv::Size(639, 481)),
+    testing::Values(MatType(CV_8UC1), MatType(CV_8UC3), MatType(CV_32FC1), MatType(CV_32FC3))
+    ));
+
+
+////////////////////////////////////////////////////////
+// Brute Force Non local means
+
+struct NonLocalMeans: testing::TestWithParam<cv::gpu::DeviceInfo>
+{
+    cv::gpu::DeviceInfo devInfo;
+
+    virtual void SetUp()
+    {
+        devInfo = GetParam();
+        cv::gpu::setDevice(devInfo.deviceID());
+    }
+};
+
+TEST_P(NonLocalMeans, Regression)
+{
+    using cv::gpu::GpuMat;
+
+    cv::Mat bgr  = readImage("denoising/lena_noised_gaussian_sigma=20_multi_0.png", cv::IMREAD_COLOR);
+    ASSERT_FALSE(bgr.empty());
+    
+    cv::Mat gray;
+    cv::cvtColor(bgr, gray, CV_BGR2GRAY);
+
+    GpuMat dbgr, dgray;
+    cv::gpu::nonLocalMeans(GpuMat(bgr),  dbgr, 10);
+    cv::gpu::nonLocalMeans(GpuMat(gray), dgray, 10);
+
+#if 0
+    dumpImage("denoising/denoised_lena_bgr.png", cv::Mat(dbgr));
+    dumpImage("denoising/denoised_lena_gray.png", cv::Mat(dgray));
+#endif
+
+    cv::Mat bgr_gold  = readImage("denoising/denoised_lena_bgr.png", cv::IMREAD_COLOR);
+    cv::Mat gray_gold  = readImage("denoising/denoised_lena_gray.png", cv::IMREAD_GRAYSCALE);
+    ASSERT_FALSE(bgr_gold.empty() || gray_gold.empty());
+
+    EXPECT_MAT_NEAR(bgr_gold, dbgr, 1e-4);
+    EXPECT_MAT_NEAR(gray_gold, dgray, 1e-4);
+}
+
+INSTANTIATE_TEST_CASE_P(GPU_ImgProc, NonLocalMeans, ALL_DEVICES);
+
+
+#endif // HAVE_CUDA
\ No newline at end of file
diff --git a/modules/gpu/test/utility.cpp b/modules/gpu/test/utility.cpp
index cf3b0fc8c..a92d2c52f 100644
--- a/modules/gpu/test/utility.cpp
+++ b/modules/gpu/test/utility.cpp
@@ -127,6 +127,14 @@ Mat readImageType(const std::string& fname, int type)
     return src;
 }
 
+//////////////////////////////////////////////////////////////////////
+// Image dumping
+
+void dumpImage(const std::string& fileName, const cv::Mat& image)
+{
+    cv::imwrite(TS::ptr()->get_data_path() + fileName, image);
+}
+
 //////////////////////////////////////////////////////////////////////
 // Gpu devices
 
diff --git a/modules/gpu/test/utility.hpp b/modules/gpu/test/utility.hpp
index f509b786a..1d153fcf0 100644
--- a/modules/gpu/test/utility.hpp
+++ b/modules/gpu/test/utility.hpp
@@ -74,6 +74,11 @@ cv::Mat readImage(const std::string& fileName, int flags = cv::IMREAD_COLOR);
 //! read image from testdata folder and convert it to specified type
 cv::Mat readImageType(const std::string& fname, int type);
 
+//////////////////////////////////////////////////////////////////////
+// Image dumping
+
+void dumpImage(const std::string& fileName, const cv::Mat& image);
+
 //////////////////////////////////////////////////////////////////////
 // Gpu devices
 
diff --git a/modules/imgproc/src/smooth.cpp b/modules/imgproc/src/smooth.cpp
index 8ec6f6d79..13340511f 100644
--- a/modules/imgproc/src/smooth.cpp
+++ b/modules/imgproc/src/smooth.cpp
@@ -1285,6 +1285,8 @@ void cv::medianBlur( InputArray _src0, OutputArray _dst, int ksize )
                                    Bilateral Filtering
 \****************************************************************************************/
 
+#undef CV_SSE3
+
 namespace cv
 {