diff --git a/.gitignore b/.gitignore index 0a19f3ceeb..4fd406edd9 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ .DS_Store refman.rst OpenCV4Tegra/ +tegra/ *.user .sw[a-z] .*.swp diff --git a/3rdparty/ffmpeg/ffmpeg_version.cmake b/3rdparty/ffmpeg/ffmpeg_version.cmake index 3f27077d6a..e35e8c7a63 100644 --- a/3rdparty/ffmpeg/ffmpeg_version.cmake +++ b/3rdparty/ffmpeg/ffmpeg_version.cmake @@ -1,4 +1,3 @@ -set(NEW_FFMPEG 1) set(HAVE_FFMPEG_CODEC 1) set(HAVE_FFMPEG_FORMAT 1) set(HAVE_FFMPEG_UTIL 1) diff --git a/3rdparty/lib/armeabi-v7a/libnative_camera_r2.2.0.so b/3rdparty/lib/armeabi-v7a/libnative_camera_r2.2.0.so index f62e5961f2..6f28f2c554 100755 Binary files a/3rdparty/lib/armeabi-v7a/libnative_camera_r2.2.0.so and b/3rdparty/lib/armeabi-v7a/libnative_camera_r2.2.0.so differ diff --git a/3rdparty/lib/armeabi-v7a/libnative_camera_r2.3.3.so b/3rdparty/lib/armeabi-v7a/libnative_camera_r2.3.3.so index c0237c1d02..010641ed15 100755 Binary files a/3rdparty/lib/armeabi-v7a/libnative_camera_r2.3.3.so and b/3rdparty/lib/armeabi-v7a/libnative_camera_r2.3.3.so differ diff --git a/3rdparty/lib/armeabi-v7a/libnative_camera_r3.0.1.so b/3rdparty/lib/armeabi-v7a/libnative_camera_r3.0.1.so index 2c235d8249..5a145b25bd 100755 Binary files a/3rdparty/lib/armeabi-v7a/libnative_camera_r3.0.1.so and b/3rdparty/lib/armeabi-v7a/libnative_camera_r3.0.1.so differ diff --git a/3rdparty/lib/armeabi-v7a/libnative_camera_r4.0.0.so b/3rdparty/lib/armeabi-v7a/libnative_camera_r4.0.0.so index 4872588894..a524b743f7 100755 Binary files a/3rdparty/lib/armeabi-v7a/libnative_camera_r4.0.0.so and b/3rdparty/lib/armeabi-v7a/libnative_camera_r4.0.0.so differ diff --git a/3rdparty/lib/armeabi-v7a/libnative_camera_r4.0.3.so b/3rdparty/lib/armeabi-v7a/libnative_camera_r4.0.3.so index 169d97e774..a1802f1ff3 100755 Binary files a/3rdparty/lib/armeabi-v7a/libnative_camera_r4.0.3.so and b/3rdparty/lib/armeabi-v7a/libnative_camera_r4.0.3.so differ diff --git a/3rdparty/lib/armeabi-v7a/libnative_camera_r4.1.1.so b/3rdparty/lib/armeabi-v7a/libnative_camera_r4.1.1.so index bdd09fb065..089c7e9e2f 100755 Binary files a/3rdparty/lib/armeabi-v7a/libnative_camera_r4.1.1.so and b/3rdparty/lib/armeabi-v7a/libnative_camera_r4.1.1.so differ diff --git a/3rdparty/lib/armeabi-v7a/libnative_camera_r4.2.0.so b/3rdparty/lib/armeabi-v7a/libnative_camera_r4.2.0.so index 74bfdea5e0..a9ffa4b0cf 100755 Binary files a/3rdparty/lib/armeabi-v7a/libnative_camera_r4.2.0.so and b/3rdparty/lib/armeabi-v7a/libnative_camera_r4.2.0.so differ diff --git a/3rdparty/lib/armeabi-v7a/libnative_camera_r4.3.0.so b/3rdparty/lib/armeabi-v7a/libnative_camera_r4.3.0.so new file mode 100755 index 0000000000..8ff7177ada Binary files /dev/null and b/3rdparty/lib/armeabi-v7a/libnative_camera_r4.3.0.so differ diff --git a/3rdparty/lib/armeabi/libnative_camera_r2.2.0.so b/3rdparty/lib/armeabi/libnative_camera_r2.2.0.so index 7c061d9eee..b6ce0d5a5b 100755 Binary files a/3rdparty/lib/armeabi/libnative_camera_r2.2.0.so and b/3rdparty/lib/armeabi/libnative_camera_r2.2.0.so differ diff --git a/3rdparty/lib/armeabi/libnative_camera_r2.3.3.so b/3rdparty/lib/armeabi/libnative_camera_r2.3.3.so index 686bdfb615..635ce681a9 100755 Binary files a/3rdparty/lib/armeabi/libnative_camera_r2.3.3.so and b/3rdparty/lib/armeabi/libnative_camera_r2.3.3.so differ diff --git a/3rdparty/lib/armeabi/libnative_camera_r3.0.1.so b/3rdparty/lib/armeabi/libnative_camera_r3.0.1.so index 5a5c231737..caacf39d4a 100755 Binary files a/3rdparty/lib/armeabi/libnative_camera_r3.0.1.so and b/3rdparty/lib/armeabi/libnative_camera_r3.0.1.so differ diff --git a/3rdparty/lib/armeabi/libnative_camera_r4.0.0.so b/3rdparty/lib/armeabi/libnative_camera_r4.0.0.so index 694cfb80dd..fff4a8069b 100755 Binary files a/3rdparty/lib/armeabi/libnative_camera_r4.0.0.so and b/3rdparty/lib/armeabi/libnative_camera_r4.0.0.so differ diff --git a/3rdparty/lib/armeabi/libnative_camera_r4.0.3.so b/3rdparty/lib/armeabi/libnative_camera_r4.0.3.so index c6cc8ab5f9..3119265558 100755 Binary files a/3rdparty/lib/armeabi/libnative_camera_r4.0.3.so and b/3rdparty/lib/armeabi/libnative_camera_r4.0.3.so differ diff --git a/3rdparty/lib/armeabi/libnative_camera_r4.1.1.so b/3rdparty/lib/armeabi/libnative_camera_r4.1.1.so index 94966c82e7..7c18baf01f 100755 Binary files a/3rdparty/lib/armeabi/libnative_camera_r4.1.1.so and b/3rdparty/lib/armeabi/libnative_camera_r4.1.1.so differ diff --git a/3rdparty/lib/armeabi/libnative_camera_r4.2.0.so b/3rdparty/lib/armeabi/libnative_camera_r4.2.0.so index 8251510c49..8bb093a3d0 100755 Binary files a/3rdparty/lib/armeabi/libnative_camera_r4.2.0.so and b/3rdparty/lib/armeabi/libnative_camera_r4.2.0.so differ diff --git a/3rdparty/lib/armeabi/libnative_camera_r4.3.0.so b/3rdparty/lib/armeabi/libnative_camera_r4.3.0.so new file mode 100755 index 0000000000..a05f179172 Binary files /dev/null and b/3rdparty/lib/armeabi/libnative_camera_r4.3.0.so differ diff --git a/3rdparty/lib/mips/libnative_camera_r4.0.3.so b/3rdparty/lib/mips/libnative_camera_r4.0.3.so index c8c9e2c571..b9500441a0 100755 Binary files a/3rdparty/lib/mips/libnative_camera_r4.0.3.so and b/3rdparty/lib/mips/libnative_camera_r4.0.3.so differ diff --git a/3rdparty/lib/mips/libnative_camera_r4.1.1.so b/3rdparty/lib/mips/libnative_camera_r4.1.1.so index 6845d715d9..d11dcf036d 100755 Binary files a/3rdparty/lib/mips/libnative_camera_r4.1.1.so and b/3rdparty/lib/mips/libnative_camera_r4.1.1.so differ diff --git a/3rdparty/lib/mips/libnative_camera_r4.2.0.so b/3rdparty/lib/mips/libnative_camera_r4.2.0.so index b148d1621b..b06a6819f1 100755 Binary files a/3rdparty/lib/mips/libnative_camera_r4.2.0.so and b/3rdparty/lib/mips/libnative_camera_r4.2.0.so differ diff --git a/3rdparty/lib/mips/libnative_camera_r4.3.0.so b/3rdparty/lib/mips/libnative_camera_r4.3.0.so new file mode 100755 index 0000000000..844b806b9d Binary files /dev/null and b/3rdparty/lib/mips/libnative_camera_r4.3.0.so differ diff --git a/3rdparty/lib/x86/libnative_camera_r2.3.3.so b/3rdparty/lib/x86/libnative_camera_r2.3.3.so index d9400638b5..0dd8904ac9 100755 Binary files a/3rdparty/lib/x86/libnative_camera_r2.3.3.so and b/3rdparty/lib/x86/libnative_camera_r2.3.3.so differ diff --git a/3rdparty/lib/x86/libnative_camera_r3.0.1.so b/3rdparty/lib/x86/libnative_camera_r3.0.1.so index cf2e9908ca..105a19d0c5 100755 Binary files a/3rdparty/lib/x86/libnative_camera_r3.0.1.so and b/3rdparty/lib/x86/libnative_camera_r3.0.1.so differ diff --git a/3rdparty/lib/x86/libnative_camera_r4.0.3.so b/3rdparty/lib/x86/libnative_camera_r4.0.3.so index 420ec818fa..b01a4bd28c 100755 Binary files a/3rdparty/lib/x86/libnative_camera_r4.0.3.so and b/3rdparty/lib/x86/libnative_camera_r4.0.3.so differ diff --git a/3rdparty/lib/x86/libnative_camera_r4.1.1.so b/3rdparty/lib/x86/libnative_camera_r4.1.1.so index 5468d206c6..a59ae39b3c 100755 Binary files a/3rdparty/lib/x86/libnative_camera_r4.1.1.so and b/3rdparty/lib/x86/libnative_camera_r4.1.1.so differ diff --git a/3rdparty/lib/x86/libnative_camera_r4.2.0.so b/3rdparty/lib/x86/libnative_camera_r4.2.0.so index 9923310326..b90b826448 100755 Binary files a/3rdparty/lib/x86/libnative_camera_r4.2.0.so and b/3rdparty/lib/x86/libnative_camera_r4.2.0.so differ diff --git a/3rdparty/lib/x86/libnative_camera_r4.3.0.so b/3rdparty/lib/x86/libnative_camera_r4.3.0.so new file mode 100755 index 0000000000..6607e5da81 Binary files /dev/null and b/3rdparty/lib/x86/libnative_camera_r4.3.0.so differ diff --git a/3rdparty/tbb/CMakeLists.txt b/3rdparty/tbb/CMakeLists.txt index ce08195968..c728440f27 100644 --- a/3rdparty/tbb/CMakeLists.txt +++ b/3rdparty/tbb/CMakeLists.txt @@ -11,7 +11,7 @@ if (WIN32 AND ARM) set(tbb_url "http://threadingbuildingblocks.org/sites/default/files/software_releases/source/tbb41_20130613oss_src.tgz") set(tbb_md5 "108c8c1e481b0aaea61878289eb28b6a") set(tbb_version_file "version_string.ver") - ocv_warnings_disable(CMAKE_CXX_FLAGS -Wshadow -Wunused-parameter) + ocv_warnings_disable(CMAKE_CXX_FLAGS /wd4702) else() # 4.1 update 2 - works fine set(tbb_ver "tbb41_20130116oss") @@ -230,9 +230,15 @@ endif() ocv_warnings_disable(CMAKE_CXX_FLAGS -Wundef -Wmissing-declarations) string(REPLACE "-Werror=non-virtual-dtor" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") +if (WIN32) + set(tbb_debug_postfix "_debug") # to fit pragmas in _windef.h inside TBB +else() + set(tbb_debug_postfix ${OPENCV_DEBUG_POSTFIX}) +endif() + set_target_properties(tbb PROPERTIES OUTPUT_NAME tbb - DEBUG_POSTFIX "${OPENCV_DEBUG_POSTFIX}" + DEBUG_POSTFIX "${tbb_debug_postfix}" ARCHIVE_OUTPUT_DIRECTORY ${3P_LIBRARY_OUTPUT_PATH} RUNTIME_OUTPUT_DIRECTORY ${EXECUTABLE_OUTPUT_PATH} ) diff --git a/CMakeLists.txt b/CMakeLists.txt index f464b2263c..46881c4531 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -212,7 +212,7 @@ OCV_OPTION(ENABLE_SSE42 "Enable SSE4.2 instructions" OCV_OPTION(ENABLE_AVX "Enable AVX instructions" OFF IF ((MSVC OR 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_WINRT_MODE "Build with Windows Runtime support" OFF IF WIN32 ) # uncategorized options # =================================================== @@ -296,7 +296,6 @@ endif() # Path for build/platform -specific headers # ---------------------------------------------------------------------------- set(OPENCV_CONFIG_FILE_INCLUDE_DIR "${CMAKE_BINARY_DIR}/" CACHE PATH "Where to create the platform-dependant cvconfig.h") -add_definitions(-DHAVE_CVCONFIG_H) ocv_include_directories(${OPENCV_CONFIG_FILE_INCLUDE_DIR}) # ---------------------------------------------------------------------------- @@ -370,9 +369,6 @@ if(UNIX) include(CheckIncludeFile) if(NOT APPLE) - CHECK_INCLUDE_FILE(alloca.h HAVE_ALLOCA_H) - CHECK_FUNCTION_EXISTS(alloca HAVE_ALLOCA) - CHECK_INCLUDE_FILE(unistd.h HAVE_UNISTD_H) CHECK_INCLUDE_FILE(pthread.h HAVE_LIBPTHREAD) if(ANDROID) set(OPENCV_LINKER_LIBS ${OPENCV_LINKER_LIBS} dl m log) @@ -382,7 +378,7 @@ if(UNIX) set(OPENCV_LINKER_LIBS ${OPENCV_LINKER_LIBS} dl m pthread rt) endif() else() - add_definitions(-DHAVE_ALLOCA -DHAVE_ALLOCA_H -DHAVE_LIBPTHREAD -DHAVE_UNISTD_H) + set(HAVE_LIBPTHREAD YES) endif() endif() @@ -607,6 +603,16 @@ if(ANDROID) status(" Android examples:" BUILD_ANDROID_EXAMPLES AND CAN_BUILD_ANDROID_PROJECTS THEN YES ELSE NO) endif() +# ================== Windows RT features ================== +if(WIN32) +status("") + status(" Windows RT support:" HAVE_WINRT THEN YES ELSE NO) + if (ENABLE_WINRT_MODE) + status(" Windows SDK v8.0:" ${WINDOWS_SDK_PATH}) + status(" Visual Studio 2012:" ${VISUAL_STUDIO_PATH}) + endif() +endif(WIN32) + # ========================== GUI ========================== status("") status(" GUI: ") diff --git a/README b/README deleted file mode 100644 index 0799dff89f..0000000000 --- a/README +++ /dev/null @@ -1,17 +0,0 @@ -OpenCV: open source computer vision library - -Homepage: http://opencv.org -Online docs: http://docs.opencv.org -Q&A forum: http://answers.opencv.org -Dev zone: http://code.opencv.org - -Please read before starting work on a pull request: - http://code.opencv.org/projects/opencv/wiki/How_to_contribute - -Summary of guidelines: - -* One pull request per issue; -* Choose the right base branch; -* Include tests and documentation; -* Clean up "oops" commits before submitting; -* Follow the coding style guide. diff --git a/README.md b/README.md new file mode 100644 index 0000000000..403f118eed --- /dev/null +++ b/README.md @@ -0,0 +1,23 @@ +### OpenCV: Open Source Computer Vision Library + +#### Resources + +* Homepage: +* Docs: +* Q&A forum: +* Issue tracking: + +#### Contributing + +Please read before starting work on a pull request: + +Summary of guidelines: + +* One pull request per issue; +* Choose the right base branch; +* Include tests and documentation; +* Clean up "oops" commits before submitting; +* Follow the coding style guide. + +[![Donate OpenCV project](http://opencv.org/wp-content/uploads/2013/07/gittip1.png)](https://www.gittip.com/OpenCV/) +[![Donate OpenCV project](http://opencv.org/wp-content/uploads/2013/07/paypal-donate-button.png)](https://www.paypal.com/cgi-bin/webscr?item_name=Donation+to+OpenCV&cmd=_donations&business=accountant%40opencv.org) \ No newline at end of file diff --git a/cmake/OpenCVCRTLinkage.cmake b/cmake/OpenCVCRTLinkage.cmake index 7514285d9f..295b914b68 100644 --- a/cmake/OpenCVCRTLinkage.cmake +++ b/cmake/OpenCVCRTLinkage.cmake @@ -2,6 +2,40 @@ if(NOT MSVC) message(FATAL_ERROR "CRT options are available only for MSVC") endif() +#INCLUDE (CheckIncludeFiles) + +if (ENABLE_WINRT_MODE) + set(HAVE_WINRT True) + + # search Windows Platform SDK + message(STATUS "Checking for Windows Platfrom SDK") + GET_FILENAME_COMPONENT(WINDOWS_SDK_PATH "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v8.0;InstallationFolder]" ABSOLUTE CACHE) + if (WINDOWS_SDK_PATH STREQUAL "") + message(ERROR "Windows Platform SDK 8.0 was not found!") + set(HAVE_WINRT False) + endif() + + #search for Visual Studio 11.0 install directory + message(STATUS "Checking for Visual Studio 2012") + GET_FILENAME_COMPONENT(VISUAL_STUDIO_PATH [HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\11.0\\Setup\\VS;ProductDir] REALPATH CACHE) + if (VISUAL_STUDIO_PATH STREQUAL "") + message(ERROR "Visual Studio 2012 was not found!") + set(HAVE_WINRT False) + endif() + + if (HAVE_WINRT) + TRY_COMPILE(HAVE_WINRT + "${OPENCV_BINARY_DIR}/CMakeFiles/CMakeTmp" + "${OpenCV_SOURCE_DIR}/cmake/checks/winrttest.cpp" + CMAKE_FLAGS "\"kernel.lib\" \"user32.lib\"" + OUTPUT_VARIABLE OUTPUT) + endif() + + if (HAVE_WINRT) + add_definitions(/DWINVER=0x0602 /DNTDDI_VERSION=NTDDI_WIN8 /D_WIN32_WINNT=0x0602) + endif() +endif(ENABLE_WINRT_MODE) + if(NOT BUILD_SHARED_LIBS AND BUILD_WITH_STATIC_CRT) foreach(flag_var CMAKE_C_FLAGS CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE diff --git a/cmake/OpenCVDetectCUDA.cmake b/cmake/OpenCVDetectCUDA.cmake index 3b93f29329..212d344d5b 100644 --- a/cmake/OpenCVDetectCUDA.cmake +++ b/cmake/OpenCVDetectCUDA.cmake @@ -96,7 +96,11 @@ if(CUDA_FOUND) if(CUDA_GENERATION STREQUAL "Fermi") set(__cuda_arch_bin "2.0 2.1(2.0)") elseif(CUDA_GENERATION STREQUAL "Kepler") - set(__cuda_arch_bin "3.0") + if(${CUDA_VERSION} VERSION_LESS "5.0") + set(__cuda_arch_bin "3.0") + else() + set(__cuda_arch_bin "3.0 3.5") + endif() elseif(CUDA_GENERATION STREQUAL "Auto") execute_process( COMMAND "${CUDA_NVCC_EXECUTABLE}" "${OpenCV_SOURCE_DIR}/cmake/checks/OpenCVDetectCudaArch.cu" "--run" WORKING_DIRECTORY "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/" @@ -110,8 +114,12 @@ if(CUDA_FOUND) endif() if(NOT DEFINED __cuda_arch_bin) - set(__cuda_arch_bin "1.1 1.2 1.3 2.0 2.1(2.0) 3.0") - set(__cuda_arch_ptx "2.0 3.0") + if(${CUDA_VERSION} VERSION_LESS "5.0") + set(__cuda_arch_bin "1.1 1.2 1.3 2.0 2.1(2.0) 3.0") + else() + set(__cuda_arch_bin "1.1 1.2 1.3 2.0 2.1(2.0) 3.0 3.5") + endif() + set(__cuda_arch_ptx "3.0") endif() set(CUDA_ARCH_BIN ${__cuda_arch_bin} CACHE STRING "Specify 'real' GPU architectures to build binaries for, BIN(PTX) format is supported") diff --git a/cmake/OpenCVDetectPython.cmake b/cmake/OpenCVDetectPython.cmake index debaaec53b..54ddac15d1 100644 --- a/cmake/OpenCVDetectPython.cmake +++ b/cmake/OpenCVDetectPython.cmake @@ -108,7 +108,7 @@ if(PYTHON_EXECUTABLE) OUTPUT_QUIET ERROR_VARIABLE SPHINX_OUTPUT OUTPUT_STRIP_TRAILING_WHITESPACE) - if(SPHINX_OUTPUT MATCHES "^Sphinx v([0-9][^ \n]*)") + if(SPHINX_OUTPUT MATCHES "Sphinx v([0-9][^ \n]*)") set(SPHINX_VERSION "${CMAKE_MATCH_1}") set(HAVE_SPHINX 1) message(STATUS "Found Sphinx ${SPHINX_VERSION}: ${SPHINX_BUILD}") diff --git a/cmake/OpenCVFindIPP.cmake b/cmake/OpenCVFindIPP.cmake index d1af605653..9921d2503c 100644 --- a/cmake/OpenCVFindIPP.cmake +++ b/cmake/OpenCVFindIPP.cmake @@ -138,9 +138,14 @@ endfunction() # This is auxiliary function called from set_ipp_variables() # to set IPP_LIBRARIES variable in IPP 7.x style # ------------------------------------------------------------------------ -function(set_ipp_new_libraries) +function(set_ipp_new_libraries _LATEST_VERSION) set(IPP_PREFIX "ipp") - set(IPP_SUFFIX "_l") # static not threaded libs suffix + + if(${_LATEST_VERSION} VERSION_LESS "8.0") + set(IPP_SUFFIX "_l") # static not threaded libs suffix + else() + set(IPP_SUFFIX "") # static not threaded libs suffix + endif() set(IPP_THRD "_t") # static threaded libs suffix set(IPPCORE "core") # core functionality set(IPPSP "s") # signal processing @@ -199,7 +204,9 @@ function(set_ipp_variables _LATEST_VERSION) # set INCLUDE and LIB folders set(IPP_INCLUDE_DIRS ${IPP_ROOT_DIR}/include PARENT_SCOPE) - if (IPP_X64) + if (APPLE) + set(IPP_LIBRARY_DIRS ${IPP_ROOT_DIR}/lib PARENT_SCOPE) + elseif (IPP_X64) if(NOT EXISTS ${IPP_ROOT_DIR}/lib/intel64) message(SEND_ERROR "IPP EM64T libraries not found") endif() @@ -212,7 +219,7 @@ function(set_ipp_variables _LATEST_VERSION) endif() # set IPP_LIBRARIES variable (7.x lib names) - set_ipp_new_libraries() + set_ipp_new_libraries(${_LATEST_VERSION}) set(IPP_LIBRARIES ${IPP_LIBRARIES} PARENT_SCOPE) message(STATUS "IPP libs: ${IPP_LIBRARIES}") diff --git a/cmake/OpenCVFindLibsGUI.cmake b/cmake/OpenCVFindLibsGUI.cmake index d685d23feb..270853aeec 100644 --- a/cmake/OpenCVFindLibsGUI.cmake +++ b/cmake/OpenCVFindLibsGUI.cmake @@ -65,3 +65,12 @@ if(WITH_OPENGL) endif() endif() endif(WITH_OPENGL) + +# --- Carbon & Cocoa --- +if(APPLE) + if(WITH_CARBON) + set(HAVE_CARBON YES) + elseif(NOT IOS) + set(HAVE_COCOA YES) + endif() +endif() diff --git a/cmake/OpenCVFindLibsGrfmt.cmake b/cmake/OpenCVFindLibsGrfmt.cmake index 33e428b7c8..9381350c0b 100644 --- a/cmake/OpenCVFindLibsGrfmt.cmake +++ b/cmake/OpenCVFindLibsGrfmt.cmake @@ -36,56 +36,58 @@ if(WITH_TIFF) ocv_parse_header("${TIFF_INCLUDE_DIR}/tiff.h" TIFF_VERSION_LINES TIFF_VERSION_CLASSIC TIFF_VERSION_BIG TIFF_VERSION TIFF_BIGTIFF_VERSION) endif() endif() -endif() -if(WITH_TIFF AND NOT TIFF_FOUND) - ocv_clear_vars(TIFF_LIBRARY TIFF_LIBRARIES TIFF_INCLUDE_DIR) + if(NOT TIFF_FOUND) + ocv_clear_vars(TIFF_LIBRARY TIFF_LIBRARIES TIFF_INCLUDE_DIR) - set(TIFF_LIBRARY libtiff) - set(TIFF_LIBRARIES ${TIFF_LIBRARY}) - add_subdirectory("${OpenCV_SOURCE_DIR}/3rdparty/libtiff") - set(TIFF_INCLUDE_DIR "${${TIFF_LIBRARY}_SOURCE_DIR}" "${${TIFF_LIBRARY}_BINARY_DIR}") - ocv_parse_header("${${TIFF_LIBRARY}_SOURCE_DIR}/tiff.h" TIFF_VERSION_LINES TIFF_VERSION_CLASSIC TIFF_VERSION_BIG TIFF_VERSION TIFF_BIGTIFF_VERSION) -endif() + set(TIFF_LIBRARY libtiff) + set(TIFF_LIBRARIES ${TIFF_LIBRARY}) + add_subdirectory("${OpenCV_SOURCE_DIR}/3rdparty/libtiff") + set(TIFF_INCLUDE_DIR "${${TIFF_LIBRARY}_SOURCE_DIR}" "${${TIFF_LIBRARY}_BINARY_DIR}") + ocv_parse_header("${${TIFF_LIBRARY}_SOURCE_DIR}/tiff.h" TIFF_VERSION_LINES TIFF_VERSION_CLASSIC TIFF_VERSION_BIG TIFF_VERSION TIFF_BIGTIFF_VERSION) + endif() -if(TIFF_VERSION_CLASSIC AND NOT TIFF_VERSION) - set(TIFF_VERSION ${TIFF_VERSION_CLASSIC}) -endif() + if(TIFF_VERSION_CLASSIC AND NOT TIFF_VERSION) + set(TIFF_VERSION ${TIFF_VERSION_CLASSIC}) + endif() -if(TIFF_BIGTIFF_VERSION AND NOT TIFF_VERSION_BIG) - set(TIFF_VERSION_BIG ${TIFF_BIGTIFF_VERSION}) -endif() + if(TIFF_BIGTIFF_VERSION AND NOT TIFF_VERSION_BIG) + set(TIFF_VERSION_BIG ${TIFF_BIGTIFF_VERSION}) + endif() -if(NOT TIFF_VERSION_STRING AND TIFF_INCLUDE_DIR) - list(GET TIFF_INCLUDE_DIR 0 _TIFF_INCLUDE_DIR) - if(EXISTS "${_TIFF_INCLUDE_DIR}/tiffvers.h") - file(STRINGS "${_TIFF_INCLUDE_DIR}/tiffvers.h" tiff_version_str REGEX "^#define[\t ]+TIFFLIB_VERSION_STR[\t ]+\"LIBTIFF, Version .*") - string(REGEX REPLACE "^#define[\t ]+TIFFLIB_VERSION_STR[\t ]+\"LIBTIFF, Version +([^ \\n]*).*" "\\1" TIFF_VERSION_STRING "${tiff_version_str}") - unset(tiff_version_str) + if(NOT TIFF_VERSION_STRING AND TIFF_INCLUDE_DIR) + list(GET TIFF_INCLUDE_DIR 0 _TIFF_INCLUDE_DIR) + if(EXISTS "${_TIFF_INCLUDE_DIR}/tiffvers.h") + file(STRINGS "${_TIFF_INCLUDE_DIR}/tiffvers.h" tiff_version_str REGEX "^#define[\t ]+TIFFLIB_VERSION_STR[\t ]+\"LIBTIFF, Version .*") + string(REGEX REPLACE "^#define[\t ]+TIFFLIB_VERSION_STR[\t ]+\"LIBTIFF, Version +([^ \\n]*).*" "\\1" TIFF_VERSION_STRING "${tiff_version_str}") + unset(tiff_version_str) + endif() + unset(_TIFF_INCLUDE_DIR) endif() - unset(_TIFF_INCLUDE_DIR) + + set(HAVE_TIFF YES) endif() # --- libjpeg (optional) --- -if(WITH_JPEG AND NOT IOS) +if(WITH_JPEG) if(BUILD_JPEG) ocv_clear_vars(JPEG_FOUND) else() include(FindJPEG) endif() -endif() -if(WITH_JPEG AND NOT JPEG_FOUND) - ocv_clear_vars(JPEG_LIBRARY JPEG_LIBRARIES JPEG_INCLUDE_DIR) - - set(JPEG_LIBRARY libjpeg) - set(JPEG_LIBRARIES ${JPEG_LIBRARY}) - add_subdirectory("${OpenCV_SOURCE_DIR}/3rdparty/libjpeg") - set(JPEG_INCLUDE_DIR "${${JPEG_LIBRARY}_SOURCE_DIR}") -endif() + if(NOT JPEG_FOUND) + ocv_clear_vars(JPEG_LIBRARY JPEG_LIBRARIES JPEG_INCLUDE_DIR) -ocv_parse_header("${JPEG_INCLUDE_DIR}/jpeglib.h" JPEG_VERSION_LINES JPEG_LIB_VERSION) + set(JPEG_LIBRARY libjpeg) + set(JPEG_LIBRARIES ${JPEG_LIBRARY}) + add_subdirectory("${OpenCV_SOURCE_DIR}/3rdparty/libjpeg") + set(JPEG_INCLUDE_DIR "${${JPEG_LIBRARY}_SOURCE_DIR}") + endif() + ocv_parse_header("${JPEG_INCLUDE_DIR}/jpeglib.h" JPEG_VERSION_LINES JPEG_LIB_VERSION) + set(HAVE_JPEG YES) +endif() # --- libjasper (optional, should be searched after libjpeg) --- if(WITH_JASPER) @@ -94,19 +96,21 @@ if(WITH_JASPER) else() include(FindJasper) endif() -endif() -if(WITH_JASPER AND NOT JASPER_FOUND) - ocv_clear_vars(JASPER_LIBRARY JASPER_LIBRARIES JASPER_INCLUDE_DIR) + if(NOT JASPER_FOUND) + ocv_clear_vars(JASPER_LIBRARY JASPER_LIBRARIES JASPER_INCLUDE_DIR) - set(JASPER_LIBRARY libjasper) - set(JASPER_LIBRARIES ${JASPER_LIBRARY}) - add_subdirectory("${OpenCV_SOURCE_DIR}/3rdparty/libjasper") - set(JASPER_INCLUDE_DIR "${${JASPER_LIBRARY}_SOURCE_DIR}") -endif() + set(JASPER_LIBRARY libjasper) + set(JASPER_LIBRARIES ${JASPER_LIBRARY}) + add_subdirectory("${OpenCV_SOURCE_DIR}/3rdparty/libjasper") + set(JASPER_INCLUDE_DIR "${${JASPER_LIBRARY}_SOURCE_DIR}") + endif() + + set(HAVE_JASPER YES) -if(NOT JASPER_VERSION_STRING) - ocv_parse_header2(JASPER "${JASPER_INCLUDE_DIR}/jasper/jas_config.h" JAS_VERSION "") + if(NOT JASPER_VERSION_STRING) + ocv_parse_header2(JASPER "${JASPER_INCLUDE_DIR}/jasper/jas_config.h" JAS_VERSION "") + endif() endif() # --- libpng (optional, should be searched after zlib) --- @@ -117,29 +121,29 @@ if(WITH_PNG AND NOT IOS) include(FindPNG) if(PNG_FOUND) include(CheckIncludeFile) - check_include_file("${PNG_PNG_INCLUDE_DIR}/png.h" HAVE_PNG_H) check_include_file("${PNG_PNG_INCLUDE_DIR}/libpng/png.h" HAVE_LIBPNG_PNG_H) - if(HAVE_PNG_H) - ocv_parse_header("${PNG_PNG_INCLUDE_DIR}/png.h" PNG_VERSION_LINES PNG_LIBPNG_VER_MAJOR PNG_LIBPNG_VER_MINOR PNG_LIBPNG_VER_RELEASE) - elseif(HAVE_LIBPNG_PNG_H) + if(HAVE_LIBPNG_PNG_H) ocv_parse_header("${PNG_PNG_INCLUDE_DIR}/libpng/png.h" PNG_VERSION_LINES PNG_LIBPNG_VER_MAJOR PNG_LIBPNG_VER_MINOR PNG_LIBPNG_VER_RELEASE) + else() + ocv_parse_header("${PNG_PNG_INCLUDE_DIR}/png.h" PNG_VERSION_LINES PNG_LIBPNG_VER_MAJOR PNG_LIBPNG_VER_MINOR PNG_LIBPNG_VER_RELEASE) endif() endif() endif() -endif() -if(WITH_PNG AND NOT PNG_FOUND) - ocv_clear_vars(PNG_LIBRARY PNG_LIBRARIES PNG_INCLUDE_DIR PNG_PNG_INCLUDE_DIR HAVE_PNG_H HAVE_LIBPNG_PNG_H PNG_DEFINITIONS) + if(NOT PNG_FOUND) + ocv_clear_vars(PNG_LIBRARY PNG_LIBRARIES PNG_INCLUDE_DIR PNG_PNG_INCLUDE_DIR HAVE_LIBPNG_PNG_H PNG_DEFINITIONS) - set(PNG_LIBRARY libpng) - set(PNG_LIBRARIES ${PNG_LIBRARY}) - add_subdirectory("${OpenCV_SOURCE_DIR}/3rdparty/libpng") - set(PNG_INCLUDE_DIR "${${PNG_LIBRARY}_SOURCE_DIR}") - set(PNG_DEFINITIONS "") - ocv_parse_header("${PNG_INCLUDE_DIR}/png.h" PNG_VERSION_LINES PNG_LIBPNG_VER_MAJOR PNG_LIBPNG_VER_MINOR PNG_LIBPNG_VER_RELEASE) -endif() + set(PNG_LIBRARY libpng) + set(PNG_LIBRARIES ${PNG_LIBRARY}) + add_subdirectory("${OpenCV_SOURCE_DIR}/3rdparty/libpng") + set(PNG_INCLUDE_DIR "${${PNG_LIBRARY}_SOURCE_DIR}") + set(PNG_DEFINITIONS "") + ocv_parse_header("${PNG_INCLUDE_DIR}/png.h" PNG_VERSION_LINES PNG_LIBPNG_VER_MAJOR PNG_LIBPNG_VER_MINOR PNG_LIBPNG_VER_RELEASE) + endif() -set(PNG_VERSION "${PNG_LIBPNG_VER_MAJOR}.${PNG_LIBPNG_VER_MINOR}.${PNG_LIBPNG_VER_RELEASE}") + set(HAVE_PNG YES) + set(PNG_VERSION "${PNG_LIBPNG_VER_MAJOR}.${PNG_LIBPNG_VER_MINOR}.${PNG_LIBPNG_VER_RELEASE}") +endif() # --- OpenEXR (optional) --- if(WITH_OPENEXR) @@ -148,17 +152,24 @@ if(WITH_OPENEXR) else() include("${OpenCV_SOURCE_DIR}/cmake/OpenCVFindOpenEXR.cmake") endif() -endif() -if(WITH_OPENEXR AND NOT OPENEXR_FOUND) - ocv_clear_vars(OPENEXR_INCLUDE_PATHS OPENEXR_LIBRARIES OPENEXR_ILMIMF_LIBRARY OPENEXR_VERSION) + if(NOT OPENEXR_FOUND) + ocv_clear_vars(OPENEXR_INCLUDE_PATHS OPENEXR_LIBRARIES OPENEXR_ILMIMF_LIBRARY OPENEXR_VERSION) + + set(OPENEXR_LIBRARIES IlmImf) + set(OPENEXR_ILMIMF_LIBRARY IlmImf) + add_subdirectory("${OpenCV_SOURCE_DIR}/3rdparty/openexr") + endif() - set(OPENEXR_LIBRARIES IlmImf) - set(OPENEXR_ILMIMF_LIBRARY IlmImf) - add_subdirectory("${OpenCV_SOURCE_DIR}/3rdparty/openexr") + set(HAVE_OPENEXR YES) endif() #cmake 2.8.2 bug - it fails to determine zlib version if(ZLIB_FOUND) ocv_parse_header2(ZLIB "${ZLIB_INCLUDE_DIR}/zlib.h" ZLIB_VERSION) -endif() \ No newline at end of file +endif() + +# --- Apple ImageIO --- +if(WITH_IMAGEIO) + set(HAVE_IMAGEIO YES) +endif() diff --git a/cmake/OpenCVFindLibsVideo.cmake b/cmake/OpenCVFindLibsVideo.cmake index 0ca4828fe6..027b53668a 100644 --- a/cmake/OpenCVFindLibsVideo.cmake +++ b/cmake/OpenCVFindLibsVideo.cmake @@ -58,7 +58,14 @@ if(WITH_PVAPI) set(_PVAPI_LIBRARY "${_PVAPI_LIBRARY}/${CMAKE_OPENCV_GCC_VERSION_MAJOR}.${CMAKE_OPENCV_GCC_VERSION_MINOR}") endif() - set(PVAPI_LIBRARY "${_PVAPI_LIBRARY}/${CMAKE_STATIC_LIBRARY_PREFIX}PvAPI${CMAKE_STATIC_LIBRARY_SUFFIX}" CACHE PATH "The PvAPI library") + if(WIN32) + if(MINGW) + set(PVAPI_DEFINITIONS "-DPVDECL=__stdcall") + endif(MINGW) + set(PVAPI_LIBRARY "${_PVAPI_LIBRARY}/PvAPI.lib" CACHE PATH "The PvAPI library") + else(WIN32) + set(PVAPI_LIBRARY "${_PVAPI_LIBRARY}/${CMAKE_STATIC_LIBRARY_PREFIX}PvAPI${CMAKE_STATIC_LIBRARY_SUFFIX}" CACHE PATH "The PvAPI library") + endif(WIN32) if(EXISTS "${PVAPI_LIBRARY}") set(HAVE_PVAPI TRUE) endif() @@ -228,3 +235,13 @@ if(WIN32) list(APPEND HIGHGUI_LIBRARIES winmm) endif() endif(WIN32) + +# --- Apple AV Foundation --- +if(WITH_AVFOUNDATION) + set(HAVE_AVFOUNDATION YES) +endif() + +# --- QuickTime --- +if(WITH_QUICKTIME) + set(HAVE_QUICKTIME YES) +endif() diff --git a/cmake/OpenCVGenHeaders.cmake b/cmake/OpenCVGenHeaders.cmake index d2d38c90a7..c7129fefa3 100644 --- a/cmake/OpenCVGenHeaders.cmake +++ b/cmake/OpenCVGenHeaders.cmake @@ -1,13 +1,3 @@ -# ---------------------------------------------------------------------------- -# Variables for cvconfig.h.cmake -# ---------------------------------------------------------------------------- -set(PACKAGE "opencv") -set(PACKAGE_BUGREPORT "opencvlibrary-devel@lists.sourceforge.net") -set(PACKAGE_NAME "opencv") -set(PACKAGE_STRING "${PACKAGE} ${OPENCV_VERSION}") -set(PACKAGE_TARNAME "${PACKAGE}") -set(PACKAGE_VERSION "${OPENCV_VERSION}") - # platform-specific config file configure_file("${OpenCV_SOURCE_DIR}/cmake/templates/cvconfig.h.cmake" "${OPENCV_CONFIG_FILE_INCLUDE_DIR}/cvconfig.h") diff --git a/cmake/OpenCVGenPkgconfig.cmake b/cmake/OpenCVGenPkgconfig.cmake index 49d6707345..7bfc7bc5af 100644 --- a/cmake/OpenCVGenPkgconfig.cmake +++ b/cmake/OpenCVGenPkgconfig.cmake @@ -12,7 +12,6 @@ set(prefix "${CMAKE_INSTALL_PREFIX}") set(exec_prefix "\${prefix}") set(libdir "") #TODO: need link paths for OpenCV_EXTRA_COMPONENTS set(includedir "\${prefix}/${OPENCV_INCLUDE_INSTALL_PATH}") -set(VERSION ${OPENCV_VERSION}) if(CMAKE_BUILD_TYPE MATCHES "Release") set(ocv_optkind OPT) diff --git a/cmake/OpenCVModule.cmake b/cmake/OpenCVModule.cmake index 81340bd0eb..44e43fc2b2 100644 --- a/cmake/OpenCVModule.cmake +++ b/cmake/OpenCVModule.cmake @@ -470,8 +470,16 @@ endmacro() # ocv_create_module() # ocv_create_module(SKIP_LINK) macro(ocv_create_module) + # The condition we ought to be testing here is whether ocv_add_precompiled_headers will + # be called at some point in the future. We can't look into the future, though, + # so this will have to do. + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/src/precomp.hpp") + get_native_precompiled_header(${the_module} precomp.hpp) + endif() + add_library(${the_module} ${OPENCV_MODULE_TYPE} ${OPENCV_MODULE_${the_module}_HEADERS} ${OPENCV_MODULE_${the_module}_SOURCES} - "${OPENCV_CONFIG_FILE_INCLUDE_DIR}/cvconfig.h" "${OPENCV_CONFIG_FILE_INCLUDE_DIR}/opencv2/opencv_modules.hpp") + "${OPENCV_CONFIG_FILE_INCLUDE_DIR}/cvconfig.h" "${OPENCV_CONFIG_FILE_INCLUDE_DIR}/opencv2/opencv_modules.hpp" + ${${the_module}_pch}) if(NOT "${ARGN}" STREQUAL "SKIP_LINK") target_link_libraries(${the_module} ${OPENCV_MODULE_${the_module}_DEPS} ${OPENCV_MODULE_${the_module}_DEPS_EXT} ${OPENCV_LINKER_LIBS} ${IPP_LIBS} ${ARGN}) @@ -508,7 +516,8 @@ macro(ocv_create_module) ) endif() - if(BUILD_SHARED_LIBS) + if((NOT DEFINED OPENCV_MODULE_TYPE AND BUILD_SHARED_LIBS) + OR (DEFINED OPENCV_MODULE_TYPE AND OPENCV_MODULE_TYPE STREQUAL SHARED)) if(MSVC) set_target_properties(${the_module} PROPERTIES DEFINE_SYMBOL CVAPI_EXPORTS) else() @@ -636,7 +645,9 @@ function(ocv_add_perf_tests) set(OPENCV_PERF_${the_module}_SOURCES ${perf_srcs} ${perf_hdrs}) endif() - add_executable(${the_target} ${OPENCV_PERF_${the_module}_SOURCES}) + get_native_precompiled_header(${the_target} test_precomp.hpp) + + add_executable(${the_target} ${OPENCV_PERF_${the_module}_SOURCES} ${${the_target}_pch}) target_link_libraries(${the_target} ${OPENCV_MODULE_${the_module}_DEPS} ${perf_deps} ${OPENCV_LINKER_LIBS}) add_dependencies(opencv_perf_tests ${the_target}) @@ -684,7 +695,9 @@ function(ocv_add_accuracy_tests) set(OPENCV_TEST_${the_module}_SOURCES ${test_srcs} ${test_hdrs}) endif() - add_executable(${the_target} ${OPENCV_TEST_${the_module}_SOURCES}) + get_native_precompiled_header(${the_target} test_precomp.hpp) + + add_executable(${the_target} ${OPENCV_TEST_${the_module}_SOURCES} ${${the_target}_pch}) target_link_libraries(${the_target} ${OPENCV_MODULE_${the_module}_DEPS} ${test_deps} ${OPENCV_LINKER_LIBS}) add_dependencies(opencv_tests ${the_target}) diff --git a/cmake/OpenCVPCHSupport.cmake b/cmake/OpenCVPCHSupport.cmake index cfc4bfa724..9b849ebd79 100644 --- a/cmake/OpenCVPCHSupport.cmake +++ b/cmake/OpenCVPCHSupport.cmake @@ -272,12 +272,9 @@ ENDMACRO(ADD_PRECOMPILED_HEADER) MACRO(GET_NATIVE_PRECOMPILED_HEADER _targetName _input) if(CMAKE_GENERATOR MATCHES "^Visual.*$") - SET(_dummy_str "#include \"${_input}\"\n" -"// This is required to suppress LNK4221. Very annoying.\n" -"void *g_${_targetName}Dummy = 0\;\n") + set(_dummy_str "#include \"${_input}\"\n") - # Use of cxx extension for generated files (as Qt does) - SET(${_targetName}_pch ${CMAKE_CURRENT_BINARY_DIR}/${_targetName}_pch.cxx) + set(${_targetName}_pch ${CMAKE_CURRENT_BINARY_DIR}/${_targetName}_pch.cpp) if(EXISTS ${${_targetName}_pch}) # Check if contents is the same, if not rewrite # todo @@ -337,11 +334,7 @@ ENDMACRO(ADD_NATIVE_PRECOMPILED_HEADER) macro(ocv_add_precompiled_header_to_target the_target pch_header) if(PCHSupport_FOUND AND ENABLE_PRECOMPILED_HEADERS AND EXISTS "${pch_header}") - if(CMAKE_GENERATOR MATCHES Visual) - string(REGEX REPLACE "hpp$" "cpp" ${the_target}_pch "${pch_header}") - add_native_precompiled_header(${the_target} ${pch_header}) - unset(${the_target}_pch) - elseif(CMAKE_GENERATOR MATCHES Xcode) + if(CMAKE_GENERATOR MATCHES "^Visual" OR CMAKE_GENERATOR MATCHES Xcode) add_native_precompiled_header(${the_target} ${pch_header}) elseif(CMAKE_COMPILER_IS_GNUCXX AND CMAKE_GENERATOR MATCHES "Makefiles|Ninja") add_precompiled_header(${the_target} ${pch_header}) diff --git a/cmake/checks/winrttest.cpp b/cmake/checks/winrttest.cpp new file mode 100644 index 0000000000..4172afe557 --- /dev/null +++ b/cmake/checks/winrttest.cpp @@ -0,0 +1,6 @@ +#include + +int main(int, char**) +{ + return 0; +} \ No newline at end of file diff --git a/cmake/templates/cvconfig.h.cmake b/cmake/templates/cvconfig.h.cmake index f12730988d..7587eef6be 100644 --- a/cmake/templates/cvconfig.h.cmake +++ b/cmake/templates/cvconfig.h.cmake @@ -1,20 +1,20 @@ -/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP - systems. This function is required for `alloca.c' support on those systems. - */ -#cmakedefine CRAY_STACKSEG_END +/* OpenCV compiled as static or dynamic libs */ +#cmakedefine BUILD_SHARED_LIBS -/* Define to 1 if using `alloca.c'. */ -#cmakedefine C_ALLOCA +/* Compile for 'real' NVIDIA GPU architectures */ +#define CUDA_ARCH_BIN "${OPENCV_CUDA_ARCH_BIN}" -/* Define to 1 if you have `alloca', as a function or macro. */ -#cmakedefine HAVE_ALLOCA 1 +/* Create PTX or BIN for 1.0 compute capability */ +#cmakedefine CUDA_ARCH_BIN_OR_PTX_10 -/* Define to 1 if you have and it should be used (not on Ultrix). - */ -#cmakedefine HAVE_ALLOCA_H 1 +/* NVIDIA GPU features are used */ +#define CUDA_ARCH_FEATURES "${OPENCV_CUDA_ARCH_FEATURES}" -/* Video for Windows support */ -#cmakedefine HAVE_VFW +/* Compile for 'virtual' NVIDIA PTX architectures */ +#define CUDA_ARCH_PTX "${OPENCV_CUDA_ARCH_PTX}" + +/* AVFoundation video libraries */ +#cmakedefine HAVE_AVFOUNDATION /* V4L capturing support */ #cmakedefine HAVE_CAMV4L @@ -22,15 +22,30 @@ /* V4L2 capturing support */ #cmakedefine HAVE_CAMV4L2 -/* V4L2 capturing support in videoio.h */ -#cmakedefine HAVE_VIDEOIO - -/* V4L/V4L2 capturing support via libv4l */ -#cmakedefine HAVE_LIBV4L - /* Carbon windowing environment */ #cmakedefine HAVE_CARBON +/* AMD's Basic Linear Algebra Subprograms Library*/ +#cmakedefine HAVE_CLAMDBLAS + +/* AMD's OpenCL Fast Fourier Transform Library*/ +#cmakedefine HAVE_CLAMDFFT + +/* Cocoa API */ +#cmakedefine HAVE_COCOA + +/* C= */ +#cmakedefine HAVE_CSTRIPES + +/* NVidia Cuda Basic Linear Algebra Subprograms (BLAS) API*/ +#cmakedefine HAVE_CUBLAS + +/* NVidia Cuda Runtime API*/ +#cmakedefine HAVE_CUDA + +/* NVidia Cuda Fast Fourier Transform (FFT) API*/ +#cmakedefine HAVE_CUFFT + /* IEEE1394 capturing support */ #cmakedefine HAVE_DC1394 @@ -40,197 +55,109 @@ /* IEEE1394 capturing support - libdc1394 v2.x */ #cmakedefine HAVE_DC1394_2 -/* ffmpeg in Gentoo */ -#cmakedefine HAVE_GENTOO_FFMPEG +/* DirectShow Video Capture library */ +#cmakedefine HAVE_DSHOW -/* FFMpeg video library */ -#cmakedefine HAVE_FFMPEG +/* Eigen Matrix & Linear Algebra Library */ +#cmakedefine HAVE_EIGEN -/* FFMpeg version flag */ -#cmakedefine NEW_FFMPEG +/* FFMpeg video library */ +#cmakedefine HAVE_FFMPEG /* ffmpeg's libswscale */ -#cmakedefine HAVE_FFMPEG_SWSCALE +#cmakedefine HAVE_FFMPEG_SWSCALE + +/* ffmpeg in Gentoo */ +#cmakedefine HAVE_GENTOO_FFMPEG /* GStreamer multimedia framework */ -#cmakedefine HAVE_GSTREAMER +#cmakedefine HAVE_GSTREAMER /* GTK+ 2.0 Thread support */ -#cmakedefine HAVE_GTHREAD +#cmakedefine HAVE_GTHREAD + +/* Windows Runtime support */ +#cmakedefine HAVE_WINRT /* Win32 UI */ #cmakedefine HAVE_WIN32UI /* GTK+ 2.x toolkit */ -#cmakedefine HAVE_GTK - -/* OpenEXR codec */ -#cmakedefine HAVE_ILMIMF +#cmakedefine HAVE_GTK /* Apple ImageIO Framework */ -#cmakedefine HAVE_IMAGEIO +#cmakedefine HAVE_IMAGEIO -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_INTTYPES_H 1 +/* Intel Integrated Performance Primitives */ +#cmakedefine HAVE_IPP /* JPEG-2000 codec */ -#cmakedefine HAVE_JASPER +#cmakedefine HAVE_JASPER /* IJG JPEG codec */ -#cmakedefine HAVE_JPEG - -/* Define to 1 if you have the `dl' library (-ldl). */ -#cmakedefine HAVE_LIBDL 1 - -/* Define to 1 if you have the `gomp' library (-lgomp). */ -#cmakedefine HAVE_LIBGOMP 1 - -/* Define to 1 if you have the `m' library (-lm). */ -#cmakedefine HAVE_LIBM 1 +#cmakedefine HAVE_JPEG /* libpng/png.h needs to be included */ -#cmakedefine HAVE_LIBPNG_PNG_H - -/* Define to 1 if you have the `pthread' library (-lpthread). */ -#cmakedefine HAVE_LIBPTHREAD 1 - -/* Define to 1 if you have the `lrint' function. */ -#cmakedefine HAVE_LRINT 1 - -/* PNG codec */ -#cmakedefine HAVE_PNG - -/* Define to 1 if you have the `png_get_valid' function. */ -#cmakedefine HAVE_PNG_GET_VALID 1 - -/* png.h needs to be included */ -#cmakedefine HAVE_PNG_H +#cmakedefine HAVE_LIBPNG_PNG_H -/* Define to 1 if you have the `png_set_tRNS_to_alpha' function. */ -#cmakedefine HAVE_PNG_SET_TRNS_TO_ALPHA 1 - -/* QuickTime video libraries */ -#cmakedefine HAVE_QUICKTIME +/* V4L/V4L2 capturing support via libv4l */ +#cmakedefine HAVE_LIBV4L -/* AVFoundation video libraries */ -#cmakedefine HAVE_AVFOUNDATION +/* Microsoft Media Foundation Capture library */ +#cmakedefine HAVE_MSMF -/* TIFF codec */ -#cmakedefine HAVE_TIFF +/* NVidia Video Decoding API*/ +#cmakedefine HAVE_NVCUVID -/* Unicap video capture library */ -#cmakedefine HAVE_UNICAP +/* OpenCL Support */ +#cmakedefine HAVE_OPENCL -/* Define to 1 if you have the header file. */ -#cmakedefine HAVE_UNISTD_H 1 +/* OpenEXR codec */ +#cmakedefine HAVE_OPENEXR -/* Xine video library */ -#cmakedefine HAVE_XINE +/* OpenGL support*/ +#cmakedefine HAVE_OPENGL /* OpenNI library */ -#cmakedefine HAVE_OPENNI - -/* LZ77 compression/decompression library (used for PNG) */ -#cmakedefine HAVE_ZLIB - -/* Intel Integrated Performance Primitives */ -#cmakedefine HAVE_IPP - -/* OpenCV compiled as static or dynamic libs */ -#cmakedefine BUILD_SHARED_LIBS - -/* Name of package */ -#define PACKAGE "${PACKAGE}" - -/* Define to the address where bug reports for this package should be sent. */ -#define PACKAGE_BUGREPORT "${PACKAGE_BUGREPORT}" - -/* Define to the full name of this package. */ -#define PACKAGE_NAME "${PACKAGE_NAME}" - -/* Define to the full name and version of this package. */ -#define PACKAGE_STRING "${PACKAGE_STRING}" +#cmakedefine HAVE_OPENNI -/* Define to the one symbol short name of this package. */ -#define PACKAGE_TARNAME "${PACKAGE_TARNAME}" - -/* Define to the version of this package. */ -#define PACKAGE_VERSION "${PACKAGE_VERSION}" +/* PNG codec */ +#cmakedefine HAVE_PNG -/* If using the C implementation of alloca, define if you know the - direction of stack growth for your system; otherwise it will be - automatically deduced at runtime. - STACK_DIRECTION > 0 => grows toward higher addresses - STACK_DIRECTION < 0 => grows toward lower addresses - STACK_DIRECTION = 0 => direction of growth unknown */ -#cmakedefine STACK_DIRECTION +/* Qt support */ +#cmakedefine HAVE_QT -/* Version number of package */ -#define VERSION "${PACKAGE_VERSION}" +/* Qt OpenGL support */ +#cmakedefine HAVE_QT_OPENGL -/* Define to 1 if your processor stores words with the most significant byte - first (like Motorola and SPARC, unlike Intel and VAX). */ -#cmakedefine WORDS_BIGENDIAN +/* QuickTime video libraries */ +#cmakedefine HAVE_QUICKTIME /* Intel Threading Building Blocks */ -#cmakedefine HAVE_TBB - -/* C= */ -#cmakedefine HAVE_CSTRIPES - -/* Eigen Matrix & Linear Algebra Library */ -#cmakedefine HAVE_EIGEN - -/* NVidia Cuda Runtime API*/ -#cmakedefine HAVE_CUDA - -/* NVidia Cuda Fast Fourier Transform (FFT) API*/ -#cmakedefine HAVE_CUFFT - -/* NVidia Cuda Basic Linear Algebra Subprograms (BLAS) API*/ -#cmakedefine HAVE_CUBLAS - -/* NVidia Video Decoding API*/ -#cmakedefine HAVE_NVCUVID - -/* Compile for 'real' NVIDIA GPU architectures */ -#define CUDA_ARCH_BIN "${OPENCV_CUDA_ARCH_BIN}" +#cmakedefine HAVE_TBB -/* Compile for 'virtual' NVIDIA PTX architectures */ -#define CUDA_ARCH_PTX "${OPENCV_CUDA_ARCH_PTX}" - -/* NVIDIA GPU features are used */ -#define CUDA_ARCH_FEATURES "${OPENCV_CUDA_ARCH_FEATURES}" - -/* Create PTX or BIN for 1.0 compute capability */ -#cmakedefine CUDA_ARCH_BIN_OR_PTX_10 - -/* OpenCL Support */ -#cmakedefine HAVE_OPENCL +/* TIFF codec */ +#cmakedefine HAVE_TIFF -/* AMD's OpenCL Fast Fourier Transform Library*/ -#cmakedefine HAVE_CLAMDFFT +/* Unicap video capture library */ +#cmakedefine HAVE_UNICAP -/* AMD's Basic Linear Algebra Subprograms Library*/ -#cmakedefine HAVE_CLAMDBLAS +/* Video for Windows support */ +#cmakedefine HAVE_VFW -/* DirectShow Video Capture library */ -#cmakedefine HAVE_DSHOW +/* V4L2 capturing support in videoio.h */ +#cmakedefine HAVE_VIDEOIO -/* Microsoft Media Foundation Capture library */ -#cmakedefine HAVE_MSMF +/* Win32 UI */ +#cmakedefine HAVE_WIN32UI /* XIMEA camera support */ #cmakedefine HAVE_XIMEA -/* OpenGL support*/ -#cmakedefine HAVE_OPENGL - -/* Clp support */ -#cmakedefine HAVE_CLP +/* Xine video library */ +#cmakedefine HAVE_XINE -/* Qt support */ -#cmakedefine HAVE_QT +/* Define to 1 if your processor stores words with the most significant byte + first (like Motorola and SPARC, unlike Intel and VAX). */ +#cmakedefine WORDS_BIGENDIAN -/* Qt OpenGL support */ -#cmakedefine HAVE_QT_OPENGL diff --git a/cmake/templates/opencv-XXX.pc.cmake.in b/cmake/templates/opencv-XXX.pc.cmake.in index 4f6415cab4..c9dedb0da3 100644 --- a/cmake/templates/opencv-XXX.pc.cmake.in +++ b/cmake/templates/opencv-XXX.pc.cmake.in @@ -8,6 +8,6 @@ includedir_new=@includedir@ Name: OpenCV Description: Open Source Computer Vision Library -Version: @VERSION@ +Version: @OPENCV_VERSION@ Libs: @OpenCV_LIB_COMPONENTS@ Cflags: -I${includedir_old} -I${includedir_new} diff --git a/doc/CMakeLists.txt b/doc/CMakeLists.txt index 70f4809d22..63f3a451b3 100644 --- a/doc/CMakeLists.txt +++ b/doc/CMakeLists.txt @@ -49,7 +49,7 @@ if(BUILD_DOCS AND HAVE_SPHINX) set(toc_file "${OPENCV_MODULE_opencv_${mod}_LOCATION}/doc/${mod}.rst") if(EXISTS "${toc_file}") file(RELATIVE_PATH toc_file "${OpenCV_SOURCE_DIR}/modules" "${toc_file}") - set(OPENCV_REFMAN_TOC "${OPENCV_REFMAN_TOC} ${toc_file}\r\n") + set(OPENCV_REFMAN_TOC "${OPENCV_REFMAN_TOC} ${toc_file}\n") endif() endforeach() diff --git a/doc/tutorials/calib3d/camera_calibration/camera_calibration.rst b/doc/tutorials/calib3d/camera_calibration/camera_calibration.rst index 6637e2590c..0e2c764930 100644 --- a/doc/tutorials/calib3d/camera_calibration/camera_calibration.rst +++ b/doc/tutorials/calib3d/camera_calibration/camera_calibration.rst @@ -3,42 +3,42 @@ Camera calibration With OpenCV ****************************** -Cameras have been around for a long-long time. However, with the introduction of the cheap *pinhole* cameras in the late 20th century, they became a common occurrence in our everyday life. Unfortunately, this cheapness comes with its price: significant distortion. Luckily, these are constants and with a calibration and some remapping we can correct this. Furthermore, with calibration you may also determinate the relation between the camera's natural units (pixels) and the real world units (for example millimeters). +Cameras have been around for a long-long time. However, with the introduction of the cheap *pinhole* cameras in the late 20th century, they became a common occurrence in our everyday life. Unfortunately, this cheapness comes with its price: significant distortion. Luckily, these are constants and with a calibration and some remapping we can correct this. Furthermore, with calibration you may also determine the relation between the camera's natural units (pixels) and the real world units (for example millimeters). Theory ====== -For the distortion OpenCV takes into account the radial and tangential factors. For the radial one uses the following formula: +For the distortion OpenCV takes into account the radial and tangential factors. For the radial factor one uses the following formula: .. math:: x_{corrected} = x( 1 + k_1 r^2 + k_2 r^4 + k_3 r^6) \\ y_{corrected} = y( 1 + k_1 r^2 + k_2 r^4 + k_3 r^6) -So for an old pixel point at :math:`(x,y)` coordinate in the input image, for a corrected output image its position will be :math:`(x_{corrected} y_{corrected})` . The presence of the radial distortion manifests in form of the "barrel" or "fish-eye" effect. +So for an old pixel point at :math:`(x,y)` coordinates in the input image, its position on the corrected output image will be :math:`(x_{corrected} y_{corrected})`. The presence of the radial distortion manifests in form of the "barrel" or "fish-eye" effect. -Tangential distortion occurs because the image taking lenses are not perfectly parallel to the imaging plane. Correcting this is made via the formulas: +Tangential distortion occurs because the image taking lenses are not perfectly parallel to the imaging plane. It can be corrected via the formulas: .. math:: x_{corrected} = x + [ 2p_1xy + p_2(r^2+2x^2)] \\ y_{corrected} = y + [ p_1(r^2+ 2y^2)+ 2p_2xy] -So we have five distortion parameters, which in OpenCV are organized in a 5 column one row matrix: +So we have five distortion parameters which in OpenCV are presented as one row matrix with 5 columns: .. math:: Distortion_{coefficients}=(k_1 \hspace{10pt} k_2 \hspace{10pt} p_1 \hspace{10pt} p_2 \hspace{10pt} k_3) -Now for the unit conversion, we use the following formula: +Now for the unit conversion we use the following formula: .. math:: \left [ \begin{matrix} x \\ y \\ w \end{matrix} \right ] = \left [ \begin{matrix} f_x & 0 & c_x \\ 0 & f_y & c_y \\ 0 & 0 & 1 \end{matrix} \right ] \left [ \begin{matrix} X \\ Y \\ Z \end{matrix} \right ] -Here the presence of the :math:`w` is cause we use a homography coordinate system (and :math:`w=Z`). The unknown parameters are :math:`f_x` and :math:`f_y` (camera focal lengths) and :math:`(c_x, c_y)` what are the optical centers expressed in pixels coordinates. If for both axes a common focal length is used with a given :math:`a` aspect ratio (usually 1), then :math:`f_y=f_x*a` and in the upper formula we will have a single :math:`f` focal length. The matrix containing these four parameters is referred to as the *camera matrix*. While the distortion coefficients are the same regardless of the camera resolutions used, these should be scaled along with the current resolution from the calibrated resolution. +Here the presence of :math:`w` is explained by the use of homography coordinate system (and :math:`w=Z`). The unknown parameters are :math:`f_x` and :math:`f_y` (camera focal lengths) and :math:`(c_x, c_y)` which are the optical centers expressed in pixels coordinates. If for both axes a common focal length is used with a given :math:`a` aspect ratio (usually 1), then :math:`f_y=f_x*a` and in the upper formula we will have a single focal length :math:`f`. The matrix containing these four parameters is referred to as the *camera matrix*. While the distortion coefficients are the same regardless of the camera resolutions used, these should be scaled along with the current resolution from the calibrated resolution. -The process of determining these two matrices is the calibration. Calculating these parameters is done by some basic geometrical equations. The equations used depend on the calibrating objects used. Currently OpenCV supports three types of object for calibration: +The process of determining these two matrices is the calibration. Calculation of these parameters is done through basic geometrical equations. The equations used depend on the chosen calibrating objects. Currently OpenCV supports three types of objects for calibration: .. container:: enumeratevisibleitemswithsquare @@ -46,7 +46,7 @@ The process of determining these two matrices is the calibration. Calculating th + Symmetrical circle pattern + Asymmetrical circle pattern -Basically, you need to take snapshots of these patterns with your camera and let OpenCV find them. Each found pattern equals in a new equation. To solve the equation you need at least a predetermined number of pattern snapshots to form a well-posed equation system. This number is higher for the chessboard pattern and less for the circle ones. For example, in theory the chessboard one requires at least two. However, in practice we have a good amount of noise present in our input images, so for good results you will probably want at least 10 good snapshots of the input pattern in different position. +Basically, you need to take snapshots of these patterns with your camera and let OpenCV find them. Each found pattern results in a new equation. To solve the equation you need at least a predetermined number of pattern snapshots to form a well-posed equation system. This number is higher for the chessboard pattern and less for the circle ones. For example, in theory the chessboard pattern requires at least two snapshots. However, in practice we have a good amount of noise present in our input images, so for good results you will probably need at least 10 good snapshots of the input pattern in different positions. Goal ==== @@ -55,19 +55,19 @@ The sample application will: .. container:: enumeratevisibleitemswithsquare - + Determinate the distortion matrix - + Determinate the camera matrix - + Input from Camera, Video and Image file list - + Configuration from XML/YAML file + + Determine the distortion matrix + + Determine the camera matrix + + Take input from Camera, Video and Image file list + + Read configuration from XML/YAML file + Save the results into XML/YAML file + Calculate re-projection error Source code =========== -You may also find the source code in the :file:`samples/cpp/tutorial_code/calib3d/camera_calibration/` folder of the OpenCV source library or :download:`download it from here <../../../../samples/cpp/tutorial_code/calib3d/camera_calibration/camera_calibration.cpp>`. The program has a single argument. The name of its configuration file. If none given it will try to open the one named "default.xml". :download:`Here's a sample configuration file <../../../../samples/cpp/tutorial_code/calib3d/camera_calibration/in_VID5.xml>` in XML format. In the configuration file you may choose to use as input a camera, a video file or an image list. If you opt for the later one, you need to create a configuration file where you enumerate the images to use. Here's :download:`an example of this <../../../../samples/cpp/tutorial_code/calib3d/camera_calibration/VID5.xml>`. The important part to remember is that the images needs to be specified using the absolute path or the relative one from your applications working directory. You may find all this in the beforehand mentioned directory. +You may also find the source code in the :file:`samples/cpp/tutorial_code/calib3d/camera_calibration/` folder of the OpenCV source library or :download:`download it from here <../../../../samples/cpp/tutorial_code/calib3d/camera_calibration/camera_calibration.cpp>`. The program has a single argument: the name of its configuration file. If none is given then it will try to open the one named "default.xml". :download:`Here's a sample configuration file <../../../../samples/cpp/tutorial_code/calib3d/camera_calibration/in_VID5.xml>` in XML format. In the configuration file you may choose to use camera as an input, a video file or an image list. If you opt for the last one, you will need to create a configuration file where you enumerate the images to use. Here's :download:`an example of this <../../../../samples/cpp/tutorial_code/calib3d/camera_calibration/VID5.xml>`. The important part to remember is that the images need to be specified using the absolute path or the relative one from your application's working directory. You may find all this in the samples directory mentioned above. -The application starts up with reading the settings from the configuration file. Although, this is an important part of it, it has nothing to do with the subject of this tutorial: *camera calibration*. Therefore, I've chosen to do not post here the code part for that. The technical background on how to do this you can find in the :ref:`fileInputOutputXMLYAML` tutorial. +The application starts up with reading the settings from the configuration file. Although, this is an important part of it, it has nothing to do with the subject of this tutorial: *camera calibration*. Therefore, I've chosen not to post the code for that part here. Technical background on how to do this you can find in the :ref:`fileInputOutputXMLYAML` tutorial. Explanation =========== @@ -93,9 +93,9 @@ Explanation return -1; } - For this I've used simple OpenCV class input operation. After reading the file I've an additional post-process function that checks for the validity of the input. Only if all of them are good will be the *goodInput* variable true. + For this I've used simple OpenCV class input operation. After reading the file I've an additional post-processing function that checks validity of the input. Only if all inputs are good then *goodInput* variable will be true. -#. **Get next input, if it fails or we have enough of them calibrate**. After this we have a big loop where we do the following operations: get the next image from the image list, camera or video file. If this fails or we have enough images we run the calibration process. In case of image we step out of the loop and otherwise the remaining frames will be undistorted (if the option is set) via changing from *DETECTION* mode to *CALIBRATED* one. +#. **Get next input, if it fails or we have enough of them - calibrate**. After this we have a big loop where we do the following operations: get the next image from the image list, camera or video file. If this fails or we have enough images then we run the calibration process. In case of image we step out of the loop and otherwise the remaining frames will be undistorted (if the option is set) via changing from *DETECTION* mode to the *CALIBRATED* one. .. code-block:: cpp @@ -125,7 +125,7 @@ Explanation For some cameras we may need to flip the input image. Here we do this too. -#. **Find the pattern in the current input**. The formation of the equations I mentioned above consists of finding the major patterns in the input: in case of the chessboard this is their corners of the squares and for the circles, well, the circles itself. The position of these will form the result and is collected into the *pointBuf* vector. +#. **Find the pattern in the current input**. The formation of the equations I mentioned above aims to finding major patterns in the input: in case of the chessboard this are corners of the squares and for the circles, well, the circles themselves. The position of these will form the result which will be written into the *pointBuf* vector. .. code-block:: cpp @@ -146,9 +146,9 @@ Explanation break; } - Depending on the type of the input pattern you use either the :calib3d:`findChessboardCorners ` or the :calib3d:`findCirclesGrid ` function. For both of them you pass on the current image, the size of the board and you'll get back the positions of the patterns. Furthermore, they return a boolean variable that states if in the input we could find or not the pattern (we only need to take into account images where this is true!). + Depending on the type of the input pattern you use either the :calib3d:`findChessboardCorners ` or the :calib3d:`findCirclesGrid ` function. For both of them you pass the current image and the size of the board and you'll get the positions of the patterns. Furthermore, they return a boolean variable which states if the pattern was found in the input (we only need to take into account those images where this is true!). - Then again in case of cameras we only take camera images after an input delay time passed. This is in order to allow for the user to move the chessboard around and as getting different images. Same images mean same equations, and same equations at the calibration will form an ill-posed problem, so the calibration will fail. For square images the position of the corners are only approximate. We may improve this by calling the :feature2d:`cornerSubPix ` function. This way will get a better calibration result. After this we add a valid inputs result to the *imagePoints* vector to collect all of the equations into a single container. Finally, for visualization feedback purposes we will draw the found points on the input image with the :calib3d:`findChessboardCorners ` function. + Then again in case of cameras we only take camera images when an input delay time is passed. This is done in order to allow user moving the chessboard around and getting different images. Similar images result in similar equations, and similar equations at the calibration step will form an ill-posed problem, so the calibration will fail. For square images the positions of the corners are only approximate. We may improve this by calling the :feature2d:`cornerSubPix ` function. It will produce better calibration result. After this we add a valid inputs result to the *imagePoints* vector to collect all of the equations into a single container. Finally, for visualization feedback purposes we will draw the found points on the input image using :calib3d:`findChessboardCorners ` function. .. code-block:: cpp @@ -175,7 +175,7 @@ Explanation drawChessboardCorners( view, s.boardSize, Mat(pointBuf), found ); } -#. **Show state and result for the user, plus command line control of the application**. The showing part consists of a text output on the live feed, and for video or camera input to show the "capturing" frame we simply bitwise negate the input image. +#. **Show state and result to the user, plus command line control of the application**. This part shows text output on the image. .. code-block:: cpp @@ -199,7 +199,7 @@ Explanation if( blinkOutput ) bitwise_not(view, view); - If we only ran the calibration and got the camera matrix plus the distortion coefficients we may just as correct the image with the :imgproc_geometric:`undistort ` function: + If we ran calibration and got camera's matrix with the distortion coefficients we may want to correct the image using :imgproc_geometric:`undistort ` function: .. code-block:: cpp @@ -212,7 +212,7 @@ Explanation //------------------------------ Show image and check for input commands ------------------- imshow("Image View", view); - Then we wait for an input key and if this is *u* we toggle the distortion removal, if it is *g* we start all over the detection process (or simply start it), and finally for the *ESC* key quit the application: + Then we wait for an input key and if this is *u* we toggle the distortion removal, if it is *g* we start again the detection process, and finally for the *ESC* key we quit the application: .. code-block:: cpp @@ -229,7 +229,7 @@ Explanation imagePoints.clear(); } -#. **Show the distortion removal for the images too**. When you work with an image list it is not possible to remove the distortion inside the loop. Therefore, you must append this after the loop. Taking advantage of this now I'll expand the :imgproc_geometric:`undistort ` function, which is in fact first a call of the :imgproc_geometric:`initUndistortRectifyMap ` to find out the transformation matrices and then doing the transformation with the :imgproc_geometric:`remap ` function. Because, after a successful calibration the map calculation needs to be done only once, by using this expanded form you may speed up your application: +#. **Show the distortion removal for the images too**. When you work with an image list it is not possible to remove the distortion inside the loop. Therefore, you must do this after the loop. Taking advantage of this now I'll expand the :imgproc_geometric:`undistort ` function, which is in fact first calls :imgproc_geometric:`initUndistortRectifyMap ` to find transformation matrices and then performs transformation using :imgproc_geometric:`remap ` function. Because, after successful calibration map calculation needs to be done only once, by using this expanded form you may speed up your application: .. code-block:: cpp @@ -256,7 +256,7 @@ Explanation The calibration and save ======================== -Because the calibration needs to be only once per camera it makes sense to save them after a successful calibration. This way later on you can just load these values into your program. Due to this we first make the calibration, and if it succeeds we save the result into an OpenCV style XML or YAML file, depending on the extension you give in the configuration file. +Because the calibration needs to be done only once per camera, it makes sense to save it after a successful calibration. This way later on you can just load these values into your program. Due to this we first make the calibration, and if it succeeds we save the result into an OpenCV style XML or YAML file, depending on the extension you give in the configuration file. Therefore in the first function we just split up these two processes. Because we want to save many of the calibration variables we'll create these variables here and pass on both of them to the calibration and saving function. Again, I'll not show the saving part as that has little in common with the calibration. Explore the source file in order to find out how and what: @@ -280,7 +280,7 @@ Therefore in the first function we just split up these two processes. Because we return ok; } -We do the calibration with the help of the :calib3d:`calibrateCamera ` function. This has the following parameters: +We do the calibration with the help of the :calib3d:`calibrateCamera ` function. It has the following parameters: .. container:: enumeratevisibleitemswithsquare @@ -318,11 +318,11 @@ We do the calibration with the help of the :calib3d:`calibrateCamera ` or the :calib3d:`findCirclesGrid ` function returned. We just need to pass it on. + + The image points. This is a vector of *Point2f* vector which for each input image contains coordinates of the important points (corners for chessboard and centers of the circles for the circle pattern). We have already collected this from :calib3d:`findChessboardCorners ` or :calib3d:`findCirclesGrid ` function. We just need to pass it on. + The size of the image acquired from the camera, video file or the images. - + The camera matrix. If we used the fix aspect ratio option we need to set the :math:`f_x` to zero: + + The camera matrix. If we used the fixed aspect ratio option we need to set the :math:`f_x` to zero: .. code-block:: cpp @@ -336,16 +336,16 @@ We do the calibration with the help of the :calib3d:`calibrateCamera ` to first transform the object point to image point. Then we calculate the absolute norm between what we got with our transformation and the corner/circle finding algorithm. To find the average error we calculate the arithmetical mean of the errors calculate for all the calibration images. + + The function returns the average re-projection error. This number gives a good estimation of precision of the found parameters. This should be as close to zero as possible. Given the intrinsic, distortion, rotation and translation matrices we may calculate the error for one view by using the :calib3d:`projectPoints ` to first transform the object point to image point. Then we calculate the absolute norm between what we got with our transformation and the corner/circle finding algorithm. To find the average error we calculate the arithmetical mean of the errors calculated for all the calibration images. .. code-block:: cpp @@ -378,25 +378,25 @@ We do the calibration with the help of the :calib3d:`calibrateCamera ` that has a size of 9 X 6. I've used an AXIS IP camera to create a couple of snapshots of the board and saved it into a VID5 directory. I've put this inside the :file:`images/CameraCalibraation` folder of my working directory and created the following :file:`VID5.XML` file that describes which images to use: +Let there be :download:`this input chessboard pattern <../../../pattern.png>` which has a size of 9 X 6. I've used an AXIS IP camera to create a couple of snapshots of the board and saved it into VID5 directory. I've put this inside the :file:`images/CameraCalibration` folder of my working directory and created the following :file:`VID5.XML` file that describes which images to use: .. code-block:: xml - images/CameraCalibraation/VID5/xx1.jpg - images/CameraCalibraation/VID5/xx2.jpg - images/CameraCalibraation/VID5/xx3.jpg - images/CameraCalibraation/VID5/xx4.jpg - images/CameraCalibraation/VID5/xx5.jpg - images/CameraCalibraation/VID5/xx6.jpg - images/CameraCalibraation/VID5/xx7.jpg - images/CameraCalibraation/VID5/xx8.jpg + images/CameraCalibration/VID5/xx1.jpg + images/CameraCalibration/VID5/xx2.jpg + images/CameraCalibration/VID5/xx3.jpg + images/CameraCalibration/VID5/xx4.jpg + images/CameraCalibration/VID5/xx5.jpg + images/CameraCalibration/VID5/xx6.jpg + images/CameraCalibration/VID5/xx7.jpg + images/CameraCalibration/VID5/xx8.jpg -Then specified the :file:`images/CameraCalibraation/VID5/VID5.XML` as input in the configuration file. Here's a chessboard pattern found during the runtime of the application: +Then passed :file:`images/CameraCalibration/VID5/VID5.XML` as an input in the configuration file. Here's a chessboard pattern found during the runtime of the application: .. image:: images/fileListImage.jpg :alt: A found chessboard @@ -433,7 +433,7 @@ In both cases in the specified output XML/YAML file you'll find the camera and d -4.1802327176423804e-001 5.0715244063187526e-001 0. 0. -5.7843597214487474e-001 -Add these values as constants to your program, call the :imgproc_geometric:`initUndistortRectifyMap ` and the :imgproc_geometric:`remap ` function to remove distortion and enjoy distortion free inputs with cheap and low quality cameras. +Add these values as constants to your program, call the :imgproc_geometric:`initUndistortRectifyMap ` and the :imgproc_geometric:`remap ` function to remove distortion and enjoy distortion free inputs for cheap and low quality cameras. You may observe a runtime instance of this on the `YouTube here `_. diff --git a/doc/tutorials/features2d/feature_detection/feature_detection.rst b/doc/tutorials/features2d/feature_detection/feature_detection.rst index 26798f8f6f..1051fe5dee 100644 --- a/doc/tutorials/features2d/feature_detection/feature_detection.rst +++ b/doc/tutorials/features2d/feature_detection/feature_detection.rst @@ -31,6 +31,7 @@ This tutorial code's is shown lines below. You can also download it from `here < #include "opencv2/core/core.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/highgui/highgui.hpp" + #include "opencv2/nonfree/nonfree.hpp" using namespace cv; diff --git a/doc/tutorials/features2d/feature_flann_matcher/feature_flann_matcher.rst b/doc/tutorials/features2d/feature_flann_matcher/feature_flann_matcher.rst index 54d28890ab..3bf757fc00 100644 --- a/doc/tutorials/features2d/feature_flann_matcher/feature_flann_matcher.rst +++ b/doc/tutorials/features2d/feature_flann_matcher/feature_flann_matcher.rst @@ -28,6 +28,7 @@ This tutorial code's is shown lines below. You can also download it from `here < #include "opencv2/core/core.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/highgui/highgui.hpp" + #include "opencv2/nonfree/nonfree.hpp" using namespace cv; diff --git a/doc/tutorials/features2d/feature_homography/feature_homography.rst b/doc/tutorials/features2d/feature_homography/feature_homography.rst index ad764ce9b7..eb06083b05 100644 --- a/doc/tutorials/features2d/feature_homography/feature_homography.rst +++ b/doc/tutorials/features2d/feature_homography/feature_homography.rst @@ -30,6 +30,7 @@ This tutorial code's is shown lines below. You can also download it from `here < #include "opencv2/features2d/features2d.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/calib3d/calib3d.hpp" + #include "opencv2/nonfree/nonfree.hpp" using namespace cv; diff --git a/doc/tutorials/introduction/windows_install/windows_install.rst b/doc/tutorials/introduction/windows_install/windows_install.rst index cbfd0f66f4..8ed84197df 100644 --- a/doc/tutorials/introduction/windows_install/windows_install.rst +++ b/doc/tutorials/introduction/windows_install/windows_install.rst @@ -312,9 +312,13 @@ First we set an enviroment variable to make easier our work. This will hold the :: - setx -m OPENCV_DIR D:\OpenCV\Build\x86\vc10 - -Here the directory is where you have your OpenCV binaries (*extracted* or *built*). You can have different platform (e.g. x64 instead of x86) or compiler type, so substitute appropriate value. Inside this you should have folders like *bin* and *include*. The -m should be added if you wish to make the settings computer wise, instead of user wise. + setx -m OPENCV_DIR D:\OpenCV\Build\x86\vc10 (suggested for Visual Studio 2010 - 32 bit Windows) + setx -m OPENCV_DIR D:\OpenCV\Build\x64\vc10 (suggested for Visual Studio 2010 - 64 bit Windows) + + setx -m OPENCV_DIR D:\OpenCV\Build\x86\vc11 (suggested for Visual Studio 2012 - 32 bit Windows) + setx -m OPENCV_DIR D:\OpenCV\Build\x64\vc11 (suggested for Visual Studio 2012 - 64 bit Windows) + +Here the directory is where you have your OpenCV binaries (*extracted* or *built*). You can have different platform (e.g. x64 instead of x86) or compiler type, so substitute appropriate value. Inside this you should have two folders called *lib* and *bin*. The -m should be added if you wish to make the settings computer wise, instead of user wise. If you built static libraries then you are done. Otherwise, you need to add the *bin* folders path to the systems path. This is cause you will use the OpenCV library in form of *\"Dynamic-link libraries\"* (also known as **DLL**). Inside these are stored all the algorithms and information the OpenCV library contains. The operating system will load them only on demand, during runtime. However, to do this he needs to know where they are. The systems **PATH** contains a list of folders where DLLs can be found. Add the OpenCV library path to this and the OS will know where to look if he ever needs the OpenCV binaries. Otherwise, you will need to copy the used DLLs right beside the applications executable file (*exe*) for the OS to find it, which is highly unpleasent if you work on many projects. To do this start up again the |PathEditor|_ and add the following new entry (right click in the application to bring up the menu): diff --git a/doc/tutorials/introduction/windows_visual_studio_Opencv/images/PropertySheetOpenCVInclude.jpg b/doc/tutorials/introduction/windows_visual_studio_Opencv/images/PropertySheetOpenCVInclude.jpg index 5826f4dd6c..bc61d33862 100644 Binary files a/doc/tutorials/introduction/windows_visual_studio_Opencv/images/PropertySheetOpenCVInclude.jpg and b/doc/tutorials/introduction/windows_visual_studio_Opencv/images/PropertySheetOpenCVInclude.jpg differ diff --git a/doc/tutorials/introduction/windows_visual_studio_Opencv/windows_visual_studio_Opencv.rst b/doc/tutorials/introduction/windows_visual_studio_Opencv/windows_visual_studio_Opencv.rst index d5f80f2f1d..ccf35eb054 100644 --- a/doc/tutorials/introduction/windows_visual_studio_Opencv/windows_visual_studio_Opencv.rst +++ b/doc/tutorials/introduction/windows_visual_studio_Opencv/windows_visual_studio_Opencv.rst @@ -52,7 +52,7 @@ Use for example the *OpenCV_Debug* name. Then by selecting the sheet :menuselect .. code-block:: bash - $(OPENCV_DIR)\include + $(OPENCV_DIR)\..\..\include .. image:: images/PropertySheetOpenCVInclude.jpg :alt: Add the include dir like this. @@ -64,7 +64,7 @@ Next go to the :menuselection:`Linker --> General` and under the *"Additional Li .. code-block:: bash - $(OPENCV_DIR)\libs + $(OPENCV_DIR)\lib .. image:: images/PropertySheetOpenCVLib.jpg :alt: Add the library folder like this. diff --git a/modules/androidcamera/camera_wrapper/camera_wrapper.cpp b/modules/androidcamera/camera_wrapper/camera_wrapper.cpp index 2d0ebc7a14..ca631fc21e 100644 --- a/modules/androidcamera/camera_wrapper/camera_wrapper.cpp +++ b/modules/androidcamera/camera_wrapper/camera_wrapper.cpp @@ -1,5 +1,8 @@ -#if !defined(ANDROID_r2_2_0) && !defined(ANDROID_r2_3_3) && !defined(ANDROID_r3_0_1) && !defined(ANDROID_r4_0_0) && !defined(ANDROID_r4_0_3) && !defined(ANDROID_r4_1_1) && !defined(ANDROID_r4_2_0) -# error Building camera wrapper for your version of Android is not supported by OpenCV. You need to modify OpenCV sources in order to compile camera wrapper for your version of Android. +#if !defined(ANDROID_r2_2_0) && !defined(ANDROID_r2_3_3) && !defined(ANDROID_r3_0_1) && \ + !defined(ANDROID_r4_0_0) && !defined(ANDROID_r4_0_3) && !defined(ANDROID_r4_1_1) && \ + !defined(ANDROID_r4_2_0) && !defined(ANDROID_r4_3_0) +# error Building camera wrapper for your version of Android is not supported by OpenCV.\ + You need to modify OpenCV sources in order to compile camera wrapper for your version of Android. #endif #include @@ -16,17 +19,18 @@ //Include SurfaceTexture.h file with the SurfaceTexture class # include # define MAGIC_OPENCV_TEXTURE_ID (0x10) -#else // defined(ANDROID_r3_0_1) || defined(ANDROID_r4_0_0) || defined(ANDROID_r4_0_3) -//TODO: This is either 2.2 or 2.3. Include the headers for ISurface.h access -#if defined(ANDROID_r4_1_1) || defined(ANDROID_r4_2_0) -#include -#include +#elif defined(ANDROID_r4_1_1) || defined(ANDROID_r4_2_0) +# include +# include +#elif defined(ANDROID_r4_3_0) +# include +# include #else # include -#endif // defined(ANDROID_r4_1_1) -#endif // defined(ANDROID_r3_0_1) || defined(ANDROID_r4_0_0) || defined(ANDROID_r4_0_3) +#endif #include +#include //undef logging macro from /system/core/libcutils/loghack.h #ifdef LOGD @@ -45,7 +49,6 @@ # undef LOGE #endif - // LOGGING #include #define CAMERA_LOG_TAG "OpenCV_NativeCamera" @@ -60,7 +63,7 @@ using namespace android; void debugShowFPS(); -#if defined(ANDROID_r4_1_1) || defined(ANDROID_r4_2_0) +#if defined(ANDROID_r4_1_1) || defined(ANDROID_r4_2_0) || defined(ANDROID_r4_3_0) class ConsumerListenerStub: public BufferQueue::ConsumerListener { public: @@ -73,6 +76,29 @@ public: }; #endif +std::string getProcessName() +{ + std::string result; + std::ifstream f; + + f.open("/proc/self/cmdline"); + if (f.is_open()) + { + std::string fullPath; + std::getline(f, fullPath, '\0'); + if (!fullPath.empty()) + { + int i = fullPath.size()-1; + while ((i >= 0) && (fullPath[i] != '/')) i--; + result = fullPath.substr(i+1, std::string::npos); + } + } + + f.close(); + + return result; +} + void debugShowFPS() { static int mFrameCount = 0; @@ -280,7 +306,7 @@ public: } virtual void postData(int32_t msgType, const sp& dataPtr - #if defined(ANDROID_r4_0_0) || defined(ANDROID_r4_0_3) || defined(ANDROID_r4_1_1) || defined(ANDROID_r4_2_0) + #if defined(ANDROID_r4_0_0) || defined(ANDROID_r4_0_3) || defined(ANDROID_r4_1_1) || defined(ANDROID_r4_2_0) || defined(ANDROID_r4_3_0) ,camera_frame_metadata_t* #endif ) @@ -361,7 +387,9 @@ CameraHandler* CameraHandler::initCameraConnect(const CameraCallback& callback, typedef sp (*Android22ConnectFuncType)(); typedef sp (*Android23ConnectFuncType)(int); typedef sp (*Android3DConnectFuncType)(int, int); + typedef sp (*Android43ConnectFuncType)(int, const String16&, int); + const int ANY_CAMERA_INDEX = -1; const int BACK_CAMERA_INDEX = 99; const int FRONT_CAMERA_INDEX = 98; @@ -372,14 +400,24 @@ CameraHandler* CameraHandler::initCameraConnect(const CameraCallback& callback, CAMERA_SUPPORT_MODE_ZSL = 0x08 /* Camera Sensor supports ZSL mode. */ }; + // used for Android 4.3 + enum { + USE_CALLING_UID = -1 + }; + const char Android22ConnectName[] = "_ZN7android6Camera7connectEv"; const char Android23ConnectName[] = "_ZN7android6Camera7connectEi"; const char Android3DConnectName[] = "_ZN7android6Camera7connectEii"; + const char Android43ConnectName[] = "_ZN7android6Camera7connectEiRKNS_8String16Ei"; int localCameraIndex = cameraId; + if (cameraId == ANY_CAMERA_INDEX) + { + localCameraIndex = 0; + } #if !defined(ANDROID_r2_2_0) - if (cameraId == BACK_CAMERA_INDEX) + else if (cameraId == BACK_CAMERA_INDEX) { LOGD("Back camera selected"); for (int i = 0; i < Camera::getNumberOfCameras(); i++) @@ -450,6 +488,12 @@ CameraHandler* CameraHandler::initCameraConnect(const CameraCallback& callback, LOGD("Connecting to CameraService v 3D"); camera = Android3DConnect(localCameraIndex, CAMERA_SUPPORT_MODE_2D); } + else if (Android43ConnectFuncType Android43Connect = (Android43ConnectFuncType)dlsym(CameraHALHandle, Android43ConnectName)) + { + std::string currentProcName = getProcessName(); + LOGD("Current process name for camera init: %s", currentProcName.c_str()); + camera = Android43Connect(localCameraIndex, String16(currentProcName.c_str()), USE_CALLING_UID); + } else { dlclose(CameraHALHandle); @@ -471,7 +515,7 @@ CameraHandler* CameraHandler::initCameraConnect(const CameraCallback& callback, handler->camera = camera; handler->cameraId = localCameraIndex; - if (prevCameraParameters != 0) + if (prevCameraParameters != NULL) { LOGI("initCameraConnect: Setting paramers from previous camera handler"); camera->setParameters(prevCameraParameters->flatten()); @@ -503,11 +547,11 @@ CameraHandler* CameraHandler::initCameraConnect(const CameraCallback& callback, const char* available_focus_modes = handler->params.get(CameraParameters::KEY_SUPPORTED_FOCUS_MODES); if (available_focus_modes != 0) { - if (strstr(available_focus_modes, "continuous-video") != NULL) - { - handler->params.set(CameraParameters::KEY_FOCUS_MODE, CameraParameters::FOCUS_MODE_CONTINUOUS_VIDEO); + if (strstr(available_focus_modes, "continuous-video") != NULL) + { + handler->params.set(CameraParameters::KEY_FOCUS_MODE, CameraParameters::FOCUS_MODE_CONTINUOUS_VIDEO); - status_t resParams = handler->camera->setParameters(handler->params.flatten()); + status_t resParams = handler->camera->setParameters(handler->params.flatten()); if (resParams != 0) { @@ -517,8 +561,8 @@ CameraHandler* CameraHandler::initCameraConnect(const CameraCallback& callback, { LOGD("initCameraConnect: autofocus is set to mode \"continuous-video\""); } + } } - } #endif //check if yuv420sp format available. Set this format as preview format. @@ -560,26 +604,25 @@ CameraHandler* CameraHandler::initCameraConnect(const CameraCallback& callback, } } - status_t pdstatus; + status_t bufferStatus; #if defined(ANDROID_r2_2_0) - pdstatus = camera->setPreviewDisplay(sp(0 /*new DummySurface*/)); - if (pdstatus != 0) - LOGE("initCameraConnect: failed setPreviewDisplay(0) call; camera migth not work correctly on some devices"); + bufferStatus = camera->setPreviewDisplay(sp(0 /*new DummySurface*/)); + if (bufferStatus != 0) + LOGE("initCameraConnect: failed setPreviewDisplay(0) call (status %d); camera might not work correctly on some devices", bufferStatus); #elif defined(ANDROID_r2_3_3) /* Do nothing in case of 2.3 for now */ - #elif defined(ANDROID_r3_0_1) || defined(ANDROID_r4_0_0) || defined(ANDROID_r4_0_3) sp surfaceTexture = new SurfaceTexture(MAGIC_OPENCV_TEXTURE_ID); - pdstatus = camera->setPreviewTexture(surfaceTexture); - if (pdstatus != 0) - LOGE("initCameraConnect: failed setPreviewTexture call; camera migth not work correctly"); -#elif defined(ANDROID_r4_1_1) || defined(ANDROID_r4_2_0) + bufferStatus = camera->setPreviewTexture(surfaceTexture); + if (bufferStatus != 0) + LOGE("initCameraConnect: failed setPreviewTexture call (status %d); camera might not work correctly", bufferStatus); +#elif defined(ANDROID_r4_1_1) || defined(ANDROID_r4_2_0) || defined(ANDROID_r4_3_0) sp bufferQueue = new BufferQueue(); sp queueListener = new ConsumerListenerStub(); bufferQueue->consumerConnect(queueListener); - pdstatus = camera->setPreviewTexture(bufferQueue); - if (pdstatus != 0) - LOGE("initCameraConnect: failed setPreviewTexture call; camera migth not work correctly"); + bufferStatus = camera->setPreviewTexture(bufferQueue); + if (bufferStatus != 0) + LOGE("initCameraConnect: failed setPreviewTexture call; camera might not work correctly"); #endif #if (defined(ANDROID_r2_2_0) || defined(ANDROID_r2_3_3) || defined(ANDROID_r3_0_1)) @@ -595,9 +638,9 @@ CameraHandler* CameraHandler::initCameraConnect(const CameraCallback& callback, #endif //!(defined(ANDROID_r4_0_0) || defined(ANDROID_r4_0_3)) LOGD("Starting preview"); - status_t resStart = camera->startPreview(); + status_t previewStatus = camera->startPreview(); - if (resStart != 0) + if (previewStatus != 0) { LOGE("initCameraConnect: startPreview() fails. Closing camera connection..."); handler->closeCameraConnect(); @@ -605,7 +648,7 @@ CameraHandler* CameraHandler::initCameraConnect(const CameraCallback& callback, } else { - LOGD("Preview started successfully"); + LOGD("Preview started successfully"); } return handler; @@ -620,9 +663,11 @@ void CameraHandler::closeCameraConnect() } camera->stopPreview(); +#if defined(ANDROID_r4_0_0) || defined(ANDROID_r4_0_3) || defined(ANDROID_r4_1_1) || defined(ANDROID_r4_2_0) || defined(ANDROID_r4_3_0) + camera->setPreviewCallbackFlags(CAMERA_FRAME_CALLBACK_FLAG_NOOP); +#endif camera->disconnect(); camera.clear(); - camera=NULL; // ATTENTION!!!!!!!!!!!!!!!!!!!!!!!!!! // When we set @@ -863,14 +908,60 @@ void CameraHandler::applyProperties(CameraHandler** ppcameraHandler) if (*ppcameraHandler == 0) { - LOGE("applyProperties: Passed null *ppcameraHandler"); + LOGE("applyProperties: Passed NULL *ppcameraHandler"); return; } - LOGD("CameraHandler::applyProperties()"); - CameraHandler* previousCameraHandler=*ppcameraHandler; - CameraParameters curCameraParameters(previousCameraHandler->params.flatten()); + CameraParameters curCameraParameters((*ppcameraHandler)->params.flatten()); + +#if defined(ANDROID_r4_0_0) || defined(ANDROID_r4_0_3) || defined(ANDROID_r4_1_1) || defined(ANDROID_r4_2_0) || defined(ANDROID_r4_3_0) + CameraHandler* handler=*ppcameraHandler; + + handler->camera->stopPreview(); + handler->camera->setPreviewCallbackFlags(CAMERA_FRAME_CALLBACK_FLAG_NOOP); + + status_t reconnectStatus = handler->camera->reconnect(); + if (reconnectStatus != 0) + { + LOGE("applyProperties: failed to reconnect camera (status %d)", reconnectStatus); + return; + } + + handler->camera->setParameters(curCameraParameters.flatten()); + handler->params.unflatten(curCameraParameters.flatten()); + + status_t bufferStatus; +# if defined(ANDROID_r4_0_0) || defined(ANDROID_r4_0_3) + sp surfaceTexture = new SurfaceTexture(MAGIC_OPENCV_TEXTURE_ID); + bufferStatus = handler->camera->setPreviewTexture(surfaceTexture); + if (bufferStatus != 0) + LOGE("applyProperties: failed setPreviewTexture call (status %d); camera might not work correctly", bufferStatus); +# elif defined(ANDROID_r4_1_1) || defined(ANDROID_r4_2_0) || defined(ANDROID_r4_3_0) + sp bufferQueue = new BufferQueue(); + sp queueListener = new ConsumerListenerStub(); + bufferQueue->consumerConnect(queueListener); + bufferStatus = handler->camera->setPreviewTexture(bufferQueue); + if (bufferStatus != 0) + LOGE("applyProperties: failed setPreviewTexture call; camera might not work correctly"); +# endif + handler->camera->setPreviewCallbackFlags( CAMERA_FRAME_CALLBACK_FLAG_ENABLE_MASK | CAMERA_FRAME_CALLBACK_FLAG_COPY_OUT_MASK);//with copy + + LOGD("Starting preview"); + status_t previewStatus = handler->camera->startPreview(); + + if (previewStatus != 0) + { + LOGE("initCameraConnect: startPreview() fails. Closing camera connection..."); + handler->closeCameraConnect(); + handler = NULL; + } + else + { + LOGD("Preview started successfully"); + } +#else + CameraHandler* previousCameraHandler=*ppcameraHandler; CameraCallback cameraCallback=previousCameraHandler->cameraCallback; void* userData=previousCameraHandler->userData; int cameraId=previousCameraHandler->cameraId; @@ -879,7 +970,6 @@ void CameraHandler::applyProperties(CameraHandler** ppcameraHandler) previousCameraHandler->closeCameraConnect(); LOGD("CameraHandler::applyProperties(): after previousCameraHandler->closeCameraConnect"); - LOGD("CameraHandler::applyProperties(): before initCameraConnect"); CameraHandler* handler=initCameraConnect(cameraCallback, cameraId, userData, &curCameraParameters); LOGD("CameraHandler::applyProperties(): after initCameraConnect, handler=0x%x", (int)handler); @@ -892,6 +982,7 @@ void CameraHandler::applyProperties(CameraHandler** ppcameraHandler) } } (*ppcameraHandler)=handler; +#endif } diff --git a/modules/androidcamera/src/camera_activity.cpp b/modules/androidcamera/src/camera_activity.cpp index 508159b17f..84db3e1f33 100644 --- a/modules/androidcamera/src/camera_activity.cpp +++ b/modules/androidcamera/src/camera_activity.cpp @@ -431,14 +431,14 @@ void CameraActivity::applyProperties() int CameraActivity::getFrameWidth() { if (frameWidth <= 0) - frameWidth = getProperty(ANDROID_CAMERA_PROPERTY_FRAMEWIDTH); + frameWidth = getProperty(ANDROID_CAMERA_PROPERTY_FRAMEWIDTH); return frameWidth; } int CameraActivity::getFrameHeight() { if (frameHeight <= 0) - frameHeight = getProperty(ANDROID_CAMERA_PROPERTY_FRAMEHEIGHT); + frameHeight = getProperty(ANDROID_CAMERA_PROPERTY_FRAMEHEIGHT); return frameHeight; } diff --git a/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.rst b/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.rst index b90fba7e12..11a0802d0d 100644 --- a/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.rst +++ b/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.rst @@ -105,7 +105,16 @@ The functions below use the above model to do the following: * Estimate the relative position and orientation of the stereo camera "heads" and compute the *rectification* transformation that makes the camera optical axes parallel. +.. note:: + + * A calibration sample for 3 cameras in horizontal position can be found at opencv_source_code/samples/cpp/3calibration.cpp + * A calibration sample based on a sequence of images can be found at opencv_source_code/samples/cpp/calibration.cpp + * A calibration sample in order to do 3D reconstruction can be found at opencv_source_code/samples/cpp/build3dmodel.cpp + * A calibration sample of an artificially generated camera and chessboard patterns can be found at opencv_source_code/samples/cpp/calibration_artificial.cpp + * A calibration example on stereo calibration can be found at opencv_source_code/samples/cpp/stereo_calib.cpp + * A calibration example on stereo matching can be found at opencv_source_code/samples/cpp/stereo_match.cpp + * (Python) A camera calibration sample can be found at opencv_source_code/samples/python2/calibrate.py calibrateCamera --------------- @@ -579,7 +588,9 @@ Finds an object pose from 3D-2D point correspondences. The function estimates the object pose given a set of object points, their corresponding image projections, as well as the camera matrix and the distortion coefficients. +.. note:: + * An example of how to use solvePNP for planar augmented reality can be found at opencv_source_code/samples/python2/plane_ar.py solvePnPRansac ------------------ @@ -766,6 +777,9 @@ Homography matrix is determined up to a scale. Thus, it is normalized so that :ocv:func:`warpPerspective`, :ocv:func:`perspectiveTransform` +.. note:: + + * A example on calculating a homography for image matching can be found at opencv_source_code/samples/cpp/video_homography.cpp estimateAffine3D -------------------- @@ -1072,6 +1086,9 @@ Class for computing stereo correspondence using the block matching algorithm. :: The class is a C++ wrapper for the associated functions. In particular, :ocv:funcx:`StereoBM::operator()` is the wrapper for :ocv:cfunc:`cvFindStereoCorrespondenceBM`. +.. Sample code: + + (Ocl) An example for using the stereoBM matching algorithm can be found at opencv_source_code/samples/ocl/stereo_match.cpp StereoBM::StereoBM ------------------ @@ -1171,7 +1188,9 @@ The class implements the modified H. Hirschmuller algorithm [HH08]_ that differs * Some pre- and post- processing steps from K. Konolige algorithm :ocv:funcx:`StereoBM::operator()` are included, for example: pre-filtering (``CV_STEREO_BM_XSOBEL`` type) and post-filtering (uniqueness check, quadratic interpolation and speckle filtering). +.. note:: + * (Python) An example illustrating the use of the StereoSGBM matching algorithm can be found at opencv_source_code/samples/python2/stereo_match.py StereoSGBM::StereoSGBM -------------------------- diff --git a/modules/calib3d/perf/perf_precomp.cpp b/modules/calib3d/perf/perf_precomp.cpp deleted file mode 100644 index 8552ac3d42..0000000000 --- a/modules/calib3d/perf/perf_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "perf_precomp.hpp" diff --git a/modules/calib3d/src/precomp.cpp b/modules/calib3d/src/precomp.cpp deleted file mode 100644 index 3e0ec42de9..0000000000 --- a/modules/calib3d/src/precomp.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/*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 "precomp.hpp" - -/* End of file. */ diff --git a/modules/calib3d/src/precomp.hpp b/modules/calib3d/src/precomp.hpp index 9b1f433ad4..e96ba533fa 100644 --- a/modules/calib3d/src/precomp.hpp +++ b/modules/calib3d/src/precomp.hpp @@ -42,9 +42,7 @@ #ifndef __OPENCV_PRECOMP_H__ #define __OPENCV_PRECOMP_H__ -#ifdef HAVE_CVCONFIG_H #include "cvconfig.h" -#endif #include "opencv2/calib3d/calib3d.hpp" #include "opencv2/imgproc/imgproc.hpp" diff --git a/modules/calib3d/test/test_precomp.cpp b/modules/calib3d/test/test_precomp.cpp deleted file mode 100644 index 5956e13e3e..0000000000 --- a/modules/calib3d/test/test_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "test_precomp.hpp" diff --git a/modules/contrib/doc/facerec/facerec_api.rst b/modules/contrib/doc/facerec/facerec_api.rst index 8bea7070ae..9e8170d486 100644 --- a/modules/contrib/doc/facerec/facerec_api.rst +++ b/modules/contrib/doc/facerec/facerec_api.rst @@ -3,6 +3,12 @@ FaceRecognizer .. highlight:: cpp +.. Sample code:: + + * An example using the FaceRecognizer class can be found at opencv_source_code/samples/cpp/facerec_demo.cpp + + * (Python) An example using the FaceRecognizer class can be found at opencv_source_code/samples/python2/facerec_demo.py + FaceRecognizer -------------- diff --git a/modules/contrib/doc/openfabmap.rst b/modules/contrib/doc/openfabmap.rst index 2f2ad40745..e2f157a075 100644 --- a/modules/contrib/doc/openfabmap.rst +++ b/modules/contrib/doc/openfabmap.rst @@ -9,6 +9,10 @@ FAB-MAP is an approach to appearance-based place recognition. FAB-MAP compares i openFABMAP requires training data (e.g. a collection of images from a similar but not identical environment) to construct a visual vocabulary for the visual bag-of-words model, along with a Chow-Liu tree representation of feature likelihood and for use in the Sampled new place method (see below). +.. note:: + + * An example using the openFABMAP package can be found at opencv_source_code/samples/cpp/fabmap_sample.cpp + of2::FabMap -------------------- diff --git a/modules/contrib/doc/retina/index.rst b/modules/contrib/doc/retina/index.rst index a3a5bc82fc..3d1f59c8e9 100644 --- a/modules/contrib/doc/retina/index.rst +++ b/modules/contrib/doc/retina/index.rst @@ -63,6 +63,11 @@ The retina can be settled up with various parameters, by default, the retina can void activateContoursProcessing (const bool activate); }; +.. Sample code:: + + * An example on retina tone mapping can be found at opencv_source_code/samples/cpp/OpenEXRimages_HighDynamicRange_Retina_toneMapping.cpp + * An example on retina tone mapping on video input can be found at opencv_source_code/samples/cpp/OpenEXRimages_HighDynamicRange_Retina_toneMapping.cpp + * A complete example illustrating the retina interface can be found at opencv_source_code/samples/cpp/retinaDemo.cpp Description +++++++++++ diff --git a/modules/contrib/src/ba.cpp b/modules/contrib/src/ba.cpp index 80047877b4..0e2afd95bb 100644 --- a/modules/contrib/src/ba.cpp +++ b/modules/contrib/src/ba.cpp @@ -744,7 +744,7 @@ static void fjac(int /*i*/, int /*j*/, CvMat *point_params, CvMat* cam_params, C CvMat* _mp = cvCreateMat(1, 1, CV_64FC2 ); //projection of the point //split camera params into different matrices - CvMat _ri, _ti, _k; + CvMat _ri, _ti, _k = cvMat(0, 0, CV_64F, NULL); // dummy initialization to fix warning of cl.exe cvGetRows( cam_params, &_ri, 0, 3 ); cvGetRows( cam_params, &_ti, 3, 6 ); diff --git a/modules/contrib/src/featuretracker.cpp b/modules/contrib/src/featuretracker.cpp index 44d5610526..87cccf4b7c 100644 --- a/modules/contrib/src/featuretracker.cpp +++ b/modules/contrib/src/featuretracker.cpp @@ -59,6 +59,7 @@ CvFeatureTracker::CvFeatureTracker(CvFeatureTrackerParams _params) : dd->set("nOctaveLayers", 5); dd->set("contrastThreshold", 0.04); dd->set("edgeThreshold", 10.7); + break; case CvFeatureTrackerParams::SURF: dd = Algorithm::create("Feature2D.SURF"); if( dd.empty() ) @@ -66,8 +67,10 @@ CvFeatureTracker::CvFeatureTracker(CvFeatureTrackerParams _params) : dd->set("hessianThreshold", 400); dd->set("nOctaves", 3); dd->set("nOctaveLayers", 4); + break; default: CV_Error(CV_StsBadArg, "Unknown feature type"); + break; } matcher = new BFMatcher(NORM_L2); diff --git a/modules/contrib/src/inputoutput.cpp b/modules/contrib/src/inputoutput.cpp index a711f242ad..e04740faee 100644 --- a/modules/contrib/src/inputoutput.cpp +++ b/modules/contrib/src/inputoutput.cpp @@ -1,5 +1,6 @@ #include "opencv2/contrib/contrib.hpp" +#include #if defined(WIN32) || defined(_WIN32) #include @@ -16,10 +17,22 @@ namespace cv list.clear(); std::string path_f = path + "/" + exten; #ifdef WIN32 - WIN32_FIND_DATA FindFileData; - HANDLE hFind; - - hFind = FindFirstFile((LPCSTR)path_f.c_str(), &FindFileData); + #ifdef HAVE_WINRT + WIN32_FIND_DATAW FindFileData; + #else + WIN32_FIND_DATAA FindFileData; + #endif + HANDLE hFind; + + #ifdef HAVE_WINRT + size_t size = mbstowcs(NULL, path_f.c_str(), path_f.size()); + Ptr wpath = new wchar_t[size+1]; + wpath[size] = 0; + mbstowcs(wpath, path_f.c_str(), path_f.size()); + hFind = FindFirstFileExW(wpath, FindExInfoStandard, &FindFileData, FindExSearchNameMatch, NULL, 0); + #else + hFind = FindFirstFileA((LPCSTR)path_f.c_str(), &FindFileData); + #endif if (hFind == INVALID_HANDLE_VALUE) { return list; @@ -34,13 +47,26 @@ namespace cv FindFileData.dwFileAttributes == FILE_ATTRIBUTE_SYSTEM || FindFileData.dwFileAttributes == FILE_ATTRIBUTE_READONLY) { + cv::Ptr fname; + #ifdef HAVE_WINRT + size_t asize = wcstombs(NULL, FindFileData.cFileName, 0); + fname = new char[asize+1]; + fname[asize] = 0; + wcstombs(fname, FindFileData.cFileName, asize); + #else + fname = FindFileData.cFileName; + #endif if (addPath) - list.push_back(path + "/" + FindFileData.cFileName); + list.push_back(path + "/" + std::string(fname)); else - list.push_back(FindFileData.cFileName); + list.push_back(std::string(fname)); } } - while(FindNextFile(hFind, &FindFileData)); + #ifdef HAVE_WINRT + while(FindNextFileW(hFind, &FindFileData)); + #else + while(FindNextFileA(hFind, &FindFileData)); + #endif FindClose(hFind); } #else @@ -75,10 +101,22 @@ namespace cv std::string path_f = path + "/" + exten; list.clear(); #ifdef WIN32 - WIN32_FIND_DATA FindFileData; + #ifdef HAVE_WINRT + WIN32_FIND_DATAW FindFileData; + #else + WIN32_FIND_DATAA FindFileData; + #endif HANDLE hFind; - hFind = FindFirstFile((LPCSTR)path_f.c_str(), &FindFileData); + #ifdef HAVE_WINRT + size_t size = mbstowcs(NULL, path_f.c_str(), path_f.size()); + Ptr wpath = new wchar_t[size+1]; + wpath[size] = 0; + mbstowcs(wpath, path_f.c_str(), path_f.size()); + hFind = FindFirstFileExW(wpath, FindExInfoStandard, &FindFileData, FindExSearchNameMatch, NULL, 0); + #else + hFind = FindFirstFileA((LPCSTR)path_f.c_str(), &FindFileData); + #endif if (hFind == INVALID_HANDLE_VALUE) { return list; @@ -87,17 +125,37 @@ namespace cv { do { +#ifdef HAVE_WINRT + if (FindFileData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY && + wcscmp(FindFileData.cFileName, L".") != 0 && + wcscmp(FindFileData.cFileName, L"..") != 0) +#else if (FindFileData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY && strcmp(FindFileData.cFileName, ".") != 0 && strcmp(FindFileData.cFileName, "..") != 0) +#endif { + cv::Ptr fname; + #ifdef HAVE_WINRT + size_t asize = wcstombs(NULL, FindFileData.cFileName, 0); + fname = new char[asize+1]; + fname[asize] = 0; + wcstombs(fname, FindFileData.cFileName, asize); + #else + fname = FindFileData.cFileName; + #endif + if (addPath) - list.push_back(path + "/" + FindFileData.cFileName); + list.push_back(path + "/" + std::string(fname)); else - list.push_back(FindFileData.cFileName); + list.push_back(std::string(fname)); } } - while(FindNextFile(hFind, &FindFileData)); + #ifdef HAVE_WINRT + while(FindNextFileW(hFind, &FindFileData)); + #else + while(FindNextFileA(hFind, &FindFileData)); + #endif FindClose(hFind); } diff --git a/modules/contrib/src/precomp.cpp b/modules/contrib/src/precomp.cpp deleted file mode 100644 index 3e0ec42de9..0000000000 --- a/modules/contrib/src/precomp.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/*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 "precomp.hpp" - -/* End of file. */ diff --git a/modules/contrib/src/precomp.hpp b/modules/contrib/src/precomp.hpp index 7c8e6bdf81..30232f763c 100644 --- a/modules/contrib/src/precomp.hpp +++ b/modules/contrib/src/precomp.hpp @@ -43,9 +43,7 @@ #ifndef __OPENCV_PRECOMP_H__ #define __OPENCV_PRECOMP_H__ -#ifdef HAVE_CVCONFIG_H #include "cvconfig.h" -#endif #include "opencv2/contrib/contrib.hpp" #include "opencv2/features2d/features2d.hpp" diff --git a/modules/contrib/test/test_precomp.cpp b/modules/contrib/test/test_precomp.cpp deleted file mode 100644 index 5956e13e3e..0000000000 --- a/modules/contrib/test/test_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "test_precomp.hpp" diff --git a/modules/core/CMakeLists.txt b/modules/core/CMakeLists.txt index dc62a884fa..fe13daabbc 100644 --- a/modules/core/CMakeLists.txt +++ b/modules/core/CMakeLists.txt @@ -2,6 +2,10 @@ set(the_description "The Core Functionality") ocv_add_module(core ${ZLIB_LIBRARIES}) ocv_module_include_directories(${ZLIB_INCLUDE_DIR}) +if (HAVE_WINRT) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /ZW /GS /Gm- /AI\"${WINDOWS_SDK_PATH}/References/CommonConfiguration/Neutral\" /AI\"${VISUAL_STUDIO_PATH}/vcpackages\"") +endif() + if(HAVE_CUDA) ocv_include_directories("${OpenCV_SOURCE_DIR}/modules/gpu/include") ocv_warnings_disable(CMAKE_CXX_FLAGS -Wundef) diff --git a/modules/core/doc/basic_structures.rst b/modules/core/doc/basic_structures.rst index 3705879228..981ac5c7f2 100644 --- a/modules/core/doc/basic_structures.rst +++ b/modules/core/doc/basic_structures.rst @@ -803,6 +803,9 @@ Finally, there are STL-style iterators that are smart enough to skip gaps betwee The matrix iterators are random-access iterators, so they can be passed to any STL algorithm, including ``std::sort()`` . +.. note:: + + * An example demonstrating the serial out capabilities of cv::Mat can be found at opencv_source_code/samples/cpp/cout_mat.cpp .. _MatrixExpressions: diff --git a/modules/core/doc/clustering.rst b/modules/core/doc/clustering.rst index f58e99ce2c..090a75d31a 100644 --- a/modules/core/doc/clustering.rst +++ b/modules/core/doc/clustering.rst @@ -66,6 +66,12 @@ Basically, you can use only the core of the function, set the number of attempts to 1, initialize labels each time using a custom algorithm, pass them with the ( ``flags`` = ``KMEANS_USE_INITIAL_LABELS`` ) flag, and then choose the best (most-compact) clustering. +.. note:: + + * An example on K-means clustering can be found at opencv_source_code/samples/cpp/kmeans.cpp + + * (Python) An example on K-means clustering can be found at opencv_source_code/samples/python2/kmeans.py + partition ------------- Splits an element set into equivalency classes. diff --git a/modules/core/doc/core.rst b/modules/core/doc/core.rst index 7eb4e3e63a..fc1afa644f 100644 --- a/modules/core/doc/core.rst +++ b/modules/core/doc/core.rst @@ -14,4 +14,5 @@ core. The Core Functionality old_xml_yaml_persistence clustering utility_and_system_functions_and_macros + opengl_interop diff --git a/modules/core/doc/drawing_functions.rst b/modules/core/doc/drawing_functions.rst index 342301db97..472ebfd51f 100644 --- a/modules/core/doc/drawing_functions.rst +++ b/modules/core/doc/drawing_functions.rst @@ -26,6 +26,10 @@ If a drawn figure is partially or completely outside the image, the drawing func .. note:: The functions do not support alpha-transparency when the target image is 4-channel. In this case, the ``color[3]`` is simply copied to the repainted pixels. Thus, if you want to paint semi-transparent shapes, you can paint them in a separate buffer and then blend it with the main image. +.. note:: + + * An example on using variate drawing functions like line, rectangle, ... can be found at opencv_source_code/samples/cpp/drawing.cpp + circle ---------- Draws a circle. diff --git a/modules/core/doc/opengl_interop.rst b/modules/core/doc/opengl_interop.rst new file mode 100644 index 0000000000..e0db36aec4 --- /dev/null +++ b/modules/core/doc/opengl_interop.rst @@ -0,0 +1,543 @@ +OpenGL interoperability +======================= + +.. highlight:: cpp + + + +General Information +------------------- +This section describes OpenGL interoperability. + +To enable OpenGL support, configure OpenCV using ``CMake`` with ``WITH_OPENGL=ON`` . +Currently OpenGL is supported only with WIN32, GTK and Qt backends on Windows and Linux (MacOS and Android are not supported). +For GTK backend ``gtkglext-1.0`` library is required. + +To use OpenGL functionality you should first create OpenGL context (window or frame buffer). +You can do this with :ocv:func:`namedWindow` function or with other OpenGL toolkit (GLUT, for example). + + + +ogl::Buffer +----------- +Smart pointer for OpenGL buffer object with reference counting. + +.. ocv:class:: ogl::Buffer + +Buffer Objects are OpenGL objects that store an array of unformatted memory allocated by the OpenGL context. +These can be used to store vertex data, pixel data retrieved from images or the framebuffer, and a variety of other things. + +``ogl::Buffer`` has interface similar with :ocv:class:`Mat` interface and represents 2D array memory. + +``ogl::Buffer`` supports memory transfers between host and device and also can be mapped to CUDA memory. + + + +ogl::Buffer::Target +------------------- +The target defines how you intend to use the buffer object. + +.. ocv:enum:: ogl::Buffer::Target + + .. ocv:emember:: ARRAY_BUFFER + + The buffer will be used as a source for vertex data. + + .. ocv:emember:: ELEMENT_ARRAY_BUFFER + + The buffer will be used for indices (in ``glDrawElements`` or :ocv:func:`ogl::render`, for example). + + .. ocv:emember:: PIXEL_PACK_BUFFER + + The buffer will be used for reading from OpenGL textures. + + .. ocv:emember:: PIXEL_UNPACK_BUFFER + + The buffer will be used for writing to OpenGL textures. + + + +ogl::Buffer::Buffer +------------------- +The constructors. + +.. ocv:function:: ogl::Buffer::Buffer() + +.. ocv:function:: ogl::Buffer::Buffer(int arows, int acols, int atype, unsigned int abufId, bool autoRelease = false) + +.. ocv:function:: ogl::Buffer::Buffer(Size asize, int atype, unsigned int abufId, bool autoRelease = false) + +.. ocv:function:: ogl::Buffer::Buffer(int arows, int acols, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false) + +.. ocv:function:: ogl::Buffer::Buffer(Size asize, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false) + +.. ocv:function:: ogl::Buffer::Buffer(InputArray arr, Target target = ARRAY_BUFFER, bool autoRelease = false) + + :param arows: Number of rows in a 2D array. + + :param acols: Number of columns in a 2D array. + + :param asize: 2D array size. + + :param atype: Array type ( ``CV_8UC1, ..., CV_64FC4`` ). See :ocv:class:`Mat` for details. + + :param abufId: Buffer object name. + + :param arr: Input array (host or device memory, it can be :ocv:class:`Mat` , :ocv:class:`gpu::GpuMat` or ``std::vector`` ). + + :param target: Buffer usage. See :ocv:enum:`ogl::Buffer::Target` . + + :param autoRelease: Auto release mode (if true, release will be called in object's destructor). + +Creates empty ``ogl::Buffer`` object, creates ``ogl::Buffer`` object from existed buffer ( ``abufId`` parameter), +allocates memory for ``ogl::Buffer`` object or copies from host/device memory. + + + +ogl::Buffer::create +------------------- +Allocates memory for ``ogl::Buffer`` object. + +.. ocv:function:: void ogl::Buffer::create(int arows, int acols, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false) + +.. ocv:function:: void ogl::Buffer::create(Size asize, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false) + + :param arows: Number of rows in a 2D array. + + :param acols: Number of columns in a 2D array. + + :param asize: 2D array size. + + :param atype: Array type ( ``CV_8UC1, ..., CV_64FC4`` ). See :ocv:class:`Mat` for details. + + :param target: Buffer usage. See :ocv:enum:`ogl::Buffer::Target` . + + :param autoRelease: Auto release mode (if true, release will be called in object's destructor). + + + +ogl::Buffer::release +-------------------- +Decrements the reference counter and destroys the buffer object if needed. + +.. ocv:function:: void ogl::Buffer::release() + + + +ogl::Buffer::setAutoRelease +--------------------------- +Sets auto release mode. + +.. ocv:function:: void ogl::Buffer::setAutoRelease(bool flag) + + :param flag: Auto release mode (if true, release will be called in object's destructor). + +The lifetime of the OpenGL object is tied to the lifetime of the context. +If OpenGL context was bound to a window it could be released at any time (user can close a window). +If object's destructor is called after destruction of the context it will cause an error. +Thus ``ogl::Buffer`` doesn't destroy OpenGL object in destructor by default (all OpenGL resources will be released with OpenGL context). +This function can force ``ogl::Buffer`` destructor to destroy OpenGL object. + + + +ogl::Buffer::copyFrom +--------------------- +Copies from host/device memory to OpenGL buffer. + +.. ocv:function:: void ogl::Buffer::copyFrom(InputArray arr, Target target = ARRAY_BUFFER, bool autoRelease = false) + + :param arr: Input array (host or device memory, it can be :ocv:class:`Mat` , :ocv:class:`gpu::GpuMat` or ``std::vector`` ). + + :param target: Buffer usage. See :ocv:enum:`ogl::Buffer::Target` . + + :param autoRelease: Auto release mode (if true, release will be called in object's destructor). + + + +ogl::Buffer::copyTo +------------------- +Copies from OpenGL buffer to host/device memory or another OpenGL buffer object. + +.. ocv:function:: void ogl::Buffer::copyTo(OutputArray arr, Target target = ARRAY_BUFFER, bool autoRelease = false) const + + :param arr: Destination array (host or device memory, can be :ocv:class:`Mat` , :ocv:class:`gpu::GpuMat` , ``std::vector`` or ``ogl::Buffer`` ). + + :param target: Buffer usage for destination buffer (if ``arr`` is OpenGL buffer). + + :param autoRelease: Auto release mode for destination buffer (if ``arr`` is OpenGL buffer). + + + +ogl::Buffer::clone +------------------ +Creates a full copy of the buffer object and the underlying data. + +.. ocv:function:: Buffer ogl::Buffer::clone(Target target = ARRAY_BUFFER, bool autoRelease = false) const + + :param target: Buffer usage for destination buffer. + + :param autoRelease: Auto release mode for destination buffer. + + + +ogl::Buffer::bind +----------------- +Binds OpenGL buffer to the specified buffer binding point. + +.. ocv:function:: void ogl::Buffer::bind(Target target) const + + :param target: Binding point. See :ocv:enum:`ogl::Buffer::Target` . + + + +ogl::Buffer::unbind +------------------- +Unbind any buffers from the specified binding point. + +.. ocv:function:: static void ogl::Buffer::unbind(Target target) + + :param target: Binding point. See :ocv:enum:`ogl::Buffer::Target` . + + + +ogl::Buffer::mapHost +-------------------- +Maps OpenGL buffer to host memory. + +.. ocv:function:: Mat ogl::Buffer::mapHost(Access access) + + :param access: Access policy, indicating whether it will be possible to read from, write to, or both read from and write to the buffer object's mapped data store. The symbolic constant must be ``ogl::Buffer::READ_ONLY`` , ``ogl::Buffer::WRITE_ONLY`` or ``ogl::Buffer::READ_WRITE`` . + +``mapHost`` maps to the client's address space the entire data store of the buffer object. +The data can then be directly read and/or written relative to the returned pointer, depending on the specified ``access`` policy. + +A mapped data store must be unmapped with :ocv:func:`ogl::Buffer::unmapHost` before its buffer object is used. + +This operation can lead to memory transfers between host and device. + +Only one buffer object can be mapped at a time. + + + +ogl::Buffer::unmapHost +---------------------- +Unmaps OpenGL buffer. + +.. ocv:function:: void ogl::Buffer::unmapHost() + + + +ogl::Buffer::mapDevice +---------------------- +Maps OpenGL buffer to CUDA device memory. + +.. ocv:function:: gpu::GpuMat ogl::Buffer::mapDevice() + +This operatation doesn't copy data. +Several buffer objects can be mapped to CUDA memory at a time. + +A mapped data store must be unmapped with :ocv:func:`ogl::Buffer::unmapDevice` before its buffer object is used. + + + +ogl::Buffer::unmapDevice +------------------------ +Unmaps OpenGL buffer. + +.. ocv:function:: void ogl::Buffer::unmapDevice() + + + +ogl::Texture2D +-------------- +Smart pointer for OpenGL 2D texture memory with reference counting. + +.. ocv:class:: ogl::Texture2D + + + +ogl::Texture2D::Format +---------------------- +An Image Format describes the way that the images in Textures store their data. + +.. ocv:enum:: ogl::Texture2D::Format + + .. ocv:emember:: NONE + .. ocv:emember:: DEPTH_COMPONENT + .. ocv:emember:: RGB + .. ocv:emember:: RGBA + + + +ogl::Texture2D::Texture2D +------------------------- +The constructors. + +.. ocv:function:: ogl::Texture2D::Texture2D() + +.. ocv:function:: ogl::Texture2D::Texture2D(int arows, int acols, Format aformat, unsigned int atexId, bool autoRelease = false) + +.. ocv:function:: ogl::Texture2D::Texture2D(Size asize, Format aformat, unsigned int atexId, bool autoRelease = false) + +.. ocv:function:: ogl::Texture2D::Texture2D(int arows, int acols, Format aformat, bool autoRelease = false) + +.. ocv:function:: ogl::Texture2D::Texture2D(Size asize, Format aformat, bool autoRelease = false) + +.. ocv:function:: ogl::Texture2D::Texture2D(InputArray arr, bool autoRelease = false) + + :param arows: Number of rows. + + :param acols: Number of columns. + + :param asize: 2D array size. + + :param aformat: Image format. See :ocv:enum:`ogl::Texture2D::Format` . + + :param arr: Input array (host or device memory, it can be :ocv:class:`Mat` , :ocv:class:`gpu::GpuMat` or :ocv:class:`ogl::Buffer` ). + + :param autoRelease: Auto release mode (if true, release will be called in object's destructor). + +Creates empty ``ogl::Texture2D`` object, allocates memory for ``ogl::Texture2D`` object or copies from host/device memory. + + + +ogl::Texture2D::create +---------------------- +Allocates memory for ``ogl::Texture2D`` object. + +.. ocv:function:: void ogl::Texture2D::create(int arows, int acols, Format aformat, bool autoRelease = false) + +.. ocv:function:: void ogl::Texture2D::create(Size asize, Format aformat, bool autoRelease = false) + + :param arows: Number of rows. + + :param acols: Number of columns. + + :param asize: 2D array size. + + :param aformat: Image format. See :ocv:enum:`ogl::Texture2D::Format` . + + :param autoRelease: Auto release mode (if true, release will be called in object's destructor). + + + +ogl::Texture2D::release +----------------------- +Decrements the reference counter and destroys the texture object if needed. + +.. ocv:function:: void ogl::Texture2D::release() + + + +ogl::Texture2D::setAutoRelease +------------------------------ +Sets auto release mode. + +.. ocv:function:: void ogl::Texture2D::setAutoRelease(bool flag) + + :param flag: Auto release mode (if true, release will be called in object's destructor). + +The lifetime of the OpenGL object is tied to the lifetime of the context. +If OpenGL context was bound to a window it could be released at any time (user can close a window). +If object's destructor is called after destruction of the context it will cause an error. +Thus ``ogl::Texture2D`` doesn't destroy OpenGL object in destructor by default (all OpenGL resources will be released with OpenGL context). +This function can force ``ogl::Texture2D`` destructor to destroy OpenGL object. + + + +ogl::Texture2D::copyFrom +------------------------ +Copies from host/device memory to OpenGL texture. + +.. ocv:function:: void ogl::Texture2D::copyFrom(InputArray arr, bool autoRelease = false) + + :param arr: Input array (host or device memory, it can be :ocv:class:`Mat` , :ocv:class:`gpu::GpuMat` or :ocv:class:`ogl::Buffer` ). + + :param autoRelease: Auto release mode (if true, release will be called in object's destructor). + + + +ogl::Texture2D::copyTo +---------------------- +Copies from OpenGL texture to host/device memory or another OpenGL texture object. + +.. ocv:function:: void ogl::Texture2D::copyTo(OutputArray arr, int ddepth = CV_32F, bool autoRelease = false) const + + :param arr: Destination array (host or device memory, can be :ocv:class:`Mat` , :ocv:class:`gpu::GpuMat` , :ocv:class:`ogl::Buffer` or ``ogl::Texture2D`` ). + + :param ddepth: Destination depth. + + :param autoRelease: Auto release mode for destination buffer (if ``arr`` is OpenGL buffer or texture). + + + +ogl::Texture2D::bind +-------------------- +Binds texture to current active texture unit for ``GL_TEXTURE_2D`` target. + +.. ocv:function:: void ogl::Texture2D::bind() const + + + +ogl::Arrays +----------- +Wrapper for OpenGL Client-Side Vertex arrays. + +.. ocv:class:: ogl::Arrays + +``ogl::Arrays`` stores vertex data in :ocv:class:`ogl::Buffer` objects. + + + +ogl::Arrays::setVertexArray +--------------------------- +Sets an array of vertex coordinates. + +.. ocv:function:: void ogl::Arrays::setVertexArray(InputArray vertex) + + :param vertex: array with vertex coordinates, can be both host and device memory. + + + +ogl::Arrays::resetVertexArray +----------------------------- +Resets vertex coordinates. + +.. ocv:function:: void ogl::Arrays::resetVertexArray() + + + +ogl::Arrays::setColorArray +-------------------------- +Sets an array of vertex colors. + +.. ocv:function:: void ogl::Arrays::setColorArray(InputArray color) + + :param color: array with vertex colors, can be both host and device memory. + + + +ogl::Arrays::resetColorArray +---------------------------- +Resets vertex colors. + +.. ocv:function:: void ogl::Arrays::resetColorArray() + + + +ogl::Arrays::setNormalArray +--------------------------- +Sets an array of vertex normals. + +.. ocv:function:: void ogl::Arrays::setNormalArray(InputArray normal) + + :param normal: array with vertex normals, can be both host and device memory. + + + +ogl::Arrays::resetNormalArray +----------------------------- +Resets vertex normals. + +.. ocv:function:: void ogl::Arrays::resetNormalArray() + + + +ogl::Arrays::setTexCoordArray +----------------------------- +Sets an array of vertex texture coordinates. + +.. ocv:function:: void ogl::Arrays::setTexCoordArray(InputArray texCoord) + + :param texCoord: array with vertex texture coordinates, can be both host and device memory. + + + +ogl::Arrays::resetTexCoordArray +------------------------------- +Resets vertex texture coordinates. + +.. ocv:function:: void ogl::Arrays::resetTexCoordArray() + + + +ogl::Arrays::release +-------------------- +Releases all inner buffers. + +.. ocv:function:: void ogl::Arrays::release() + + + +ogl::Arrays::setAutoRelease +--------------------------- +Sets auto release mode all inner buffers. + +.. ocv:function:: void ogl::Arrays::setAutoRelease(bool flag) + + :param flag: Auto release mode. + + + +ogl::Arrays::bind +----------------- +Binds all vertex arrays. + +.. ocv:function:: void ogl::Arrays::bind() const + + + +ogl::Arrays::size +----------------- +Returns the vertex count. + +.. ocv:function:: int ogl::Arrays::size() const + + + +ogl::render +----------- +Render OpenGL texture or primitives. + +.. ocv:function:: void ogl::render(const Texture2D& tex, Rect_ wndRect = Rect_(0.0, 0.0, 1.0, 1.0), Rect_ texRect = Rect_(0.0, 0.0, 1.0, 1.0)) + +.. ocv:function:: void ogl::render(const Arrays& arr, int mode = POINTS, Scalar color = Scalar::all(255)) + +.. ocv:function:: void ogl::render(const Arrays& arr, InputArray indices, int mode = POINTS, Scalar color = Scalar::all(255)) + + :param tex: Texture to draw. + + :param wndRect: Region of window, where to draw a texture (normalized coordinates). + + :param texRect: Region of texture to draw (normalized coordinates). + + :param arr: Array of privitives vertices. + + :param indices: Array of vertices indices (host or device memory). + + :param mode: Render mode. Available options: + + * **POINTS** + * **LINES** + * **LINE_LOOP** + * **LINE_STRIP** + * **TRIANGLES** + * **TRIANGLE_STRIP** + * **TRIANGLE_FAN** + * **QUADS** + * **QUAD_STRIP** + * **POLYGON** + + :param color: Color for all vertices. Will be used if ``arr`` doesn't contain color array. + + + +gpu::setGlDevice +---------------- +Sets a CUDA device and initializes it for the current thread with OpenGL interoperability. + +.. ocv:function:: void gpu::setGlDevice( int device = 0 ) + + :param device: System index of a GPU device starting with 0. + +This function should be explicitly called after OpenGL context creation and before any CUDA calls. diff --git a/modules/core/doc/operations_on_arrays.rst b/modules/core/doc/operations_on_arrays.rst index bd55993afe..a312818daf 100644 --- a/modules/core/doc/operations_on_arrays.rst +++ b/modules/core/doc/operations_on_arrays.rst @@ -532,7 +532,7 @@ Performs the per-element comparison of two arrays or an array and scalar value. :param value: scalar value. - :param dst: output array that has the same size as the input arrays and type= ``CV_8UC1`` . + :param dst: output array that has the same size and type as the input arrays. :param cmpop: a flag, that specifies correspondence between the arrays: @@ -997,6 +997,12 @@ All of the above improvements have been implemented in :ocv:func:`matchTemplate` .. seealso:: :ocv:func:`dct` , :ocv:func:`getOptimalDFTSize` , :ocv:func:`mulSpectrums`, :ocv:func:`filter2D` , :ocv:func:`matchTemplate` , :ocv:func:`flip` , :ocv:func:`cartToPolar` , :ocv:func:`magnitude` , :ocv:func:`phase` +.. note:: + + * An example using the discrete fourier transform can be found at opencv_source_code/samples/cpp/dft.cpp + + * (Python) An example using the dft functionality to perform Wiener deconvolution can be found at opencv_source/samples/python2/deconvolution.py + * (Python) An example rearranging the quadrants of a Fourier image can be found at opencv_source/samples/python2/dft.py divide @@ -2262,7 +2268,9 @@ The sample below is the function that takes two matrices. The first function sto :ocv:func:`dft`, :ocv:func:`dct` +.. note:: + * An example using PCA for dimensionality reduction while maintaining an amount of variance can be found at opencv_source_code/samples/cpp/pca.cpp PCA::PCA -------- diff --git a/modules/core/doc/xml_yaml_persistence.rst b/modules/core/doc/xml_yaml_persistence.rst index 28bae24508..01a1188297 100644 --- a/modules/core/doc/xml_yaml_persistence.rst +++ b/modules/core/doc/xml_yaml_persistence.rst @@ -11,7 +11,7 @@ You can store and then restore various OpenCV data structures to/from XML (http: Use the following procedure to write something to XML or YAML: #. Create new :ocv:class:`FileStorage` and open it for writing. It can be done with a single call to :ocv:func:`FileStorage::FileStorage` constructor that takes a filename, or you can use the default constructor and then call :ocv:func:`FileStorage::open`. Format of the file (XML or YAML) is determined from the filename extension (".xml" and ".yml"/".yaml", respectively) - #. Write all the data you want using the streaming operator ``>>``, just like in the case of STL streams. + #. Write all the data you want using the streaming operator ``<<``, just like in the case of STL streams. #. Close the file using :ocv:func:`FileStorage::release`. ``FileStorage`` destructor also closes the file. Here is an example: :: @@ -91,6 +91,10 @@ Several things can be noted by looking at the sample code and the output: * In YAML (but not XML), mappings and sequences can be written in a compact Python-like inline form. In the sample above matrix elements, as well as each feature, including its lbp value, is stored in such inline form. To store a mapping/sequence in a compact form, put ":" after the opening character, e.g. use **"{:"** instead of **"{"** and **"[:"** instead of **"["**. When the data is written to XML, those extra ":" are ignored. +.. note:: + + * A complete example using the FileStorage interface can be found at opencv_source_code/samples/cpp/filestorage.cpp + Reading data from a file storage. --------------------------------- diff --git a/modules/core/include/opencv2/core/internal.hpp b/modules/core/include/opencv2/core/internal.hpp index 606c62f8f5..2f26e7cb61 100644 --- a/modules/core/include/opencv2/core/internal.hpp +++ b/modules/core/include/opencv2/core/internal.hpp @@ -136,7 +136,13 @@ CV_INLINE IppiSize ippiSize(int width, int height) # endif #endif -#ifdef __ARM_NEON__ + +#if (defined WIN32 || defined _WIN32) && defined(_M_ARM) +# include +# include "arm_neon.h" +# define CV_NEON 1 +# define CPU_HAS_NEON_FEATURE (true) +#elif defined(__ARM_NEON__) # include # define CV_NEON 1 # define CPU_HAS_NEON_FEATURE (true) @@ -340,25 +346,6 @@ namespace cv * Common declarations * \****************************************************************************************/ -/* get alloca declaration */ -#ifdef __GNUC__ -# undef alloca -# define alloca __builtin_alloca -# define CV_HAVE_ALLOCA 1 -#elif defined WIN32 || defined _WIN32 || \ - defined WINCE || defined _MSC_VER || defined __BORLANDC__ -# include -# define CV_HAVE_ALLOCA 1 -#elif defined HAVE_ALLOCA_H -# include -# define CV_HAVE_ALLOCA 1 -#elif defined HAVE_ALLOCA -# include -# define CV_HAVE_ALLOCA 1 -#else -# undef CV_HAVE_ALLOCA -#endif - #ifdef __GNUC__ # define CV_DECL_ALIGNED(x) __attribute__ ((aligned (x))) #elif defined _MSC_VER @@ -367,11 +354,6 @@ namespace cv # define CV_DECL_ALIGNED(x) #endif -#if CV_HAVE_ALLOCA -/* ! DO NOT make it an inline function */ -# define cvStackAlloc(size) cvAlignPtr( alloca((size) + CV_MALLOC_ALIGN), CV_MALLOC_ALIGN ) -#endif - #ifndef CV_IMPL # define CV_IMPL CV_EXTERN_C #endif diff --git a/modules/core/include/opencv2/core/types_c.h b/modules/core/include/opencv2/core/types_c.h index 8db2fe7661..27e53cd001 100644 --- a/modules/core/include/opencv2/core/types_c.h +++ b/modules/core/include/opencv2/core/types_c.h @@ -137,7 +137,7 @@ #ifndef CV_INLINE # if defined __cplusplus # define CV_INLINE inline -# elif (defined WIN32 || defined _WIN32 || defined WINCE) && !defined __GNUC__ +# elif defined _MSC_VER # define CV_INLINE __inline # else # define CV_INLINE static @@ -317,7 +317,7 @@ CV_INLINE int cvRound( double value ) return t; #elif defined _MSC_VER && defined _M_ARM && defined HAVE_TEGRA_OPTIMIZATION TEGRA_ROUND(value); -#elif defined HAVE_LRINT || defined CV_ICC || defined __GNUC__ +#elif defined CV_ICC || defined __GNUC__ # ifdef HAVE_TEGRA_OPTIMIZATION TEGRA_ROUND(value); # else diff --git a/modules/core/include/opencv2/core/version.hpp b/modules/core/include/opencv2/core/version.hpp index 0a7760873c..ba71a82592 100644 --- a/modules/core/include/opencv2/core/version.hpp +++ b/modules/core/include/opencv2/core/version.hpp @@ -50,7 +50,7 @@ #define CV_VERSION_EPOCH 2 #define CV_VERSION_MAJOR 4 #define CV_VERSION_MINOR 6 -#define CV_VERSION_REVISION 0 +#define CV_VERSION_REVISION 1 #define CVAUX_STR_EXP(__A) #__A #define CVAUX_STR(__A) CVAUX_STR_EXP(__A) diff --git a/modules/core/perf/perf_precomp.cpp b/modules/core/perf/perf_precomp.cpp deleted file mode 100644 index 8552ac3d42..0000000000 --- a/modules/core/perf/perf_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "perf_precomp.hpp" diff --git a/modules/core/perf/perf_stat.cpp b/modules/core/perf/perf_stat.cpp index b7fc43d120..9698076ad5 100644 --- a/modules/core/perf/perf_stat.cpp +++ b/modules/core/perf/perf_stat.cpp @@ -33,7 +33,7 @@ PERF_TEST_P(Size_MatType, mean, TYPICAL_MATS) TEST_CYCLE() s = mean(src); - SANITY_CHECK(s, 1e-6); + SANITY_CHECK(s, 1e-5); } PERF_TEST_P(Size_MatType, mean_mask, TYPICAL_MATS) @@ -49,7 +49,7 @@ PERF_TEST_P(Size_MatType, mean_mask, TYPICAL_MATS) TEST_CYCLE() s = mean(src, mask); - SANITY_CHECK(s, 1e-6); + SANITY_CHECK(s, 5e-5); } PERF_TEST_P(Size_MatType, meanStdDev, TYPICAL_MATS) diff --git a/modules/core/src/alloc.cpp b/modules/core/src/alloc.cpp index 1944ed17de..37b1e0db94 100644 --- a/modules/core/src/alloc.cpp +++ b/modules/core/src/alloc.cpp @@ -94,9 +94,20 @@ void fastFree(void* ptr) #define STAT(stmt) #ifdef WIN32 +#if (_WIN32_WINNT >= 0x0602) +#include +#endif + struct CriticalSection { - CriticalSection() { InitializeCriticalSection(&cs); } + CriticalSection() + { +#if (_WIN32_WINNT >= 0x0600) + InitializeCriticalSectionEx(&cs, 1000, 0); +#else + InitializeCriticalSection(&cs); +#endif + } ~CriticalSection() { DeleteCriticalSection(&cs); } void lock() { EnterCriticalSection(&cs); } void unlock() { LeaveCriticalSection(&cs); } diff --git a/modules/core/src/drawing.cpp b/modules/core/src/drawing.cpp index 9e33408973..144fa964fd 100644 --- a/modules/core/src/drawing.cpp +++ b/modules/core/src/drawing.cpp @@ -886,11 +886,13 @@ void ellipse2Poly( Point center, Size axes, int angle, Point pt; pt.x = cvRound( cx + x * alpha - y * beta ); pt.y = cvRound( cy + x * beta + y * alpha ); - if( pt != prevPt ) + if( pt != prevPt ){ pts.push_back(pt); + prevPt = pt; + } } - if( pts.size() < 2 ) + if( pts.size() == 1 ) pts.push_back(pts[0]); } diff --git a/modules/core/src/dxt.cpp b/modules/core/src/dxt.cpp index b3c2b833b4..c76705f1b3 100644 --- a/modules/core/src/dxt.cpp +++ b/modules/core/src/dxt.cpp @@ -1458,6 +1458,10 @@ static void CCSIDFT_64f( const double* src, double* dst, int n, int nf, int* fac } +#ifdef HAVE_IPP +typedef IppStatus (CV_STDCALL* IppDFTGetSizeFunc)(int, int, IppHintAlgorithm, int*, int*, int*); +typedef IppStatus (CV_STDCALL* IppDFTInitFunc)(int, int, IppHintAlgorithm, void*, uchar*); +#endif void cv::dft( InputArray _src0, OutputArray _dst, int flags, int nonzero_rows ) { @@ -1483,7 +1487,7 @@ void cv::dft( InputArray _src0, OutputArray _dst, int flags, int nonzero_rows ) int factors[34]; bool inplace_transform = false; #ifdef HAVE_IPP - void *spec_r = 0, *spec_c = 0; + AutoBuffer ippbuf; int ipp_norm_flag = !(flags & DFT_SCALE) ? 8 : inv ? 2 : 1; #endif @@ -1543,52 +1547,51 @@ void cv::dft( InputArray _src0, OutputArray _dst, int flags, int nonzero_rows ) spec = 0; #ifdef HAVE_IPP - if( len*count >= 64 ) // use IPP DFT if available + if( +#if IPP_VERSION_MAJOR >= 7 + depth == CV_32F && // IPP 7.x and 8.0 have bug somewhere in double-precision DFT +#endif + len*count >= 64 ) // use IPP DFT if available { - int ipp_sz = 0; + int specsize=0, initsize=0, worksize=0; + IppDFTGetSizeFunc getSizeFunc = 0; + IppDFTInitFunc initFunc = 0; if( real_transform && stage == 0 ) { if( depth == CV_32F ) { - if( spec_r ) - IPPI_CALL( ippsDFTFree_R_32f( (IppsDFTSpec_R_32f*)spec_r )); - IPPI_CALL( ippsDFTInitAlloc_R_32f( - (IppsDFTSpec_R_32f**)&spec_r, len, ipp_norm_flag, ippAlgHintNone )); - IPPI_CALL( ippsDFTGetBufSize_R_32f( (IppsDFTSpec_R_32f*)spec_r, &ipp_sz )); + getSizeFunc = ippsDFTGetSize_R_32f; + initFunc = (IppDFTInitFunc)ippsDFTInit_R_32f; } else { - if( spec_r ) - IPPI_CALL( ippsDFTFree_R_64f( (IppsDFTSpec_R_64f*)spec_r )); - IPPI_CALL( ippsDFTInitAlloc_R_64f( - (IppsDFTSpec_R_64f**)&spec_r, len, ipp_norm_flag, ippAlgHintNone )); - IPPI_CALL( ippsDFTGetBufSize_R_64f( (IppsDFTSpec_R_64f*)spec_r, &ipp_sz )); + getSizeFunc = ippsDFTGetSize_R_64f; + initFunc = (IppDFTInitFunc)ippsDFTInit_R_64f; } - spec = spec_r; } else { if( depth == CV_32F ) { - if( spec_c ) - IPPI_CALL( ippsDFTFree_C_32fc( (IppsDFTSpec_C_32fc*)spec_c )); - IPPI_CALL( ippsDFTInitAlloc_C_32fc( - (IppsDFTSpec_C_32fc**)&spec_c, len, ipp_norm_flag, ippAlgHintNone )); - IPPI_CALL( ippsDFTGetBufSize_C_32fc( (IppsDFTSpec_C_32fc*)spec_c, &ipp_sz )); + getSizeFunc = ippsDFTGetSize_C_32fc; + initFunc = (IppDFTInitFunc)ippsDFTInit_C_32fc; } else { - if( spec_c ) - IPPI_CALL( ippsDFTFree_C_64fc( (IppsDFTSpec_C_64fc*)spec_c )); - IPPI_CALL( ippsDFTInitAlloc_C_64fc( - (IppsDFTSpec_C_64fc**)&spec_c, len, ipp_norm_flag, ippAlgHintNone )); - IPPI_CALL( ippsDFTGetBufSize_C_64fc( (IppsDFTSpec_C_64fc*)spec_c, &ipp_sz )); + getSizeFunc = ippsDFTGetSize_C_64fc; + initFunc = (IppDFTInitFunc)ippsDFTInit_C_64fc; } - spec = spec_c; } - - sz += ipp_sz; + if( getSizeFunc(len, ipp_norm_flag, ippAlgHintNone, &specsize, &initsize, &worksize) >= 0 ) + { + ippbuf.allocate(specsize + initsize + 64); + spec = alignPtr(&ippbuf[0], 32); + uchar* initbuf = alignPtr((uchar*)spec + specsize, 32); + if( initFunc(len, ipp_norm_flag, ippAlgHintNone, spec, initbuf) < 0 ) + spec = 0; + sz += worksize; + } } else #endif @@ -1862,24 +1865,6 @@ void cv::dft( InputArray _src0, OutputArray _dst, int flags, int nonzero_rows ) src = dst; } } - -#ifdef HAVE_IPP - if( spec_c ) - { - if( depth == CV_32F ) - ippsDFTFree_C_32fc( (IppsDFTSpec_C_32fc*)spec_c ); - else - ippsDFTFree_C_64fc( (IppsDFTSpec_C_64fc*)spec_c ); - } - - if( spec_r ) - { - if( depth == CV_32F ) - ippsDFTFree_R_32f( (IppsDFTSpec_R_32f*)spec_r ); - else - ippsDFTFree_R_64f( (IppsDFTSpec_R_64f*)spec_r ); - } -#endif } diff --git a/modules/core/src/glob.cpp b/modules/core/src/glob.cpp index 368f304ef2..e39cba0163 100644 --- a/modules/core/src/glob.cpp +++ b/modules/core/src/glob.cpp @@ -56,16 +56,39 @@ namespace struct DIR { +#ifdef HAVE_WINRT + WIN32_FIND_DATAW data; +#else WIN32_FIND_DATA data; +#endif HANDLE handle; dirent ent; +#ifdef HAVE_WINRT + DIR() {}; + ~DIR() + { + if (ent.d_name) + delete[] ent.d_name; + } +#endif }; DIR* opendir(const char* path) { DIR* dir = new DIR; dir->ent.d_name = 0; - dir->handle = ::FindFirstFileA((cv::String(path) + "\\*").c_str(), &dir->data); +#ifdef HAVE_WINRT + cv::String full_path = cv::String(path) + "\\*"; + size_t size = mbstowcs(NULL, full_path.c_str(), full_path.size()); + cv::Ptr wfull_path = new wchar_t[size+1]; + wfull_path[size] = 0; + mbstowcs(wfull_path, full_path.c_str(), full_path.size()); + dir->handle = ::FindFirstFileExW(wfull_path, FindExInfoStandard, + &dir->data, FindExSearchNameMatch, NULL, 0); +#else + dir->handle = ::FindFirstFileExA((cv::String(path) + "\\*").c_str(), + FindExInfoStandard, &dir->data, FindExSearchNameMatch, NULL, 0); +#endif if(dir->handle == INVALID_HANDLE_VALUE) { /*closedir will do all cleanup*/ @@ -76,12 +99,25 @@ namespace dirent* readdir(DIR* dir) { +#ifdef HAVE_WINRT if (dir->ent.d_name != 0) { - if (::FindNextFile(dir->handle, &dir->data) != TRUE) + if (::FindNextFileW(dir->handle, &dir->data) != TRUE) + return 0; + } + size_t asize = wcstombs(NULL, dir->data.cFileName, 0); + char* aname = new char[asize+1]; + aname[asize] = 0; + wcstombs(aname, dir->data.cFileName, asize); + dir->ent.d_name = aname; +#else + if (dir->ent.d_name != 0) + { + if (::FindNextFileA(dir->handle, &dir->data) != TRUE) return 0; } dir->ent.d_name = dir->data.cFileName; +#endif return &dir->ent; } @@ -107,7 +143,19 @@ static bool isDir(const cv::String& path, DIR* dir) if (dir) attributes = dir->data.dwFileAttributes; else - attributes = ::GetFileAttributes(path.c_str()); + { + WIN32_FILE_ATTRIBUTE_DATA all_attrs; +#ifdef HAVE_WINRT + size_t size = mbstowcs(NULL, path.c_str(), path.size()); + cv::Ptr wpath = new wchar_t[size+1]; + wpath[size] = 0; + mbstowcs(wpath, path.c_str(), path.size()); + ::GetFileAttributesExW(wpath, GetFileExInfoStandard, &all_attrs); +#else + ::GetFileAttributesExA(path.c_str(), GetFileExInfoStandard, &all_attrs); +#endif + attributes = all_attrs.dwFileAttributes; + } return (attributes != INVALID_FILE_ATTRIBUTES) && ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0); #else diff --git a/modules/core/src/parallel.cpp b/modules/core/src/parallel.cpp index 0a9ed09871..1ae8c96314 100644 --- a/modules/core/src/parallel.cpp +++ b/modules/core/src/parallel.cpp @@ -453,7 +453,11 @@ int cv::getNumberOfCPUs(void) { #if defined WIN32 || defined _WIN32 SYSTEM_INFO sysinfo; +#if defined(_M_ARM) || defined(_M_X64) || defined(HAVE_WINRT) + GetNativeSystemInfo( &sysinfo ); +#else GetSystemInfo( &sysinfo ); +#endif return (int)sysinfo.dwNumberOfProcessors; #elif defined ANDROID diff --git a/modules/core/src/persistence.cpp b/modules/core/src/persistence.cpp index a16b63e135..bf6a64c978 100644 --- a/modules/core/src/persistence.cpp +++ b/modules/core/src/persistence.cpp @@ -59,7 +59,6 @@ #endif #if USE_ZLIB -# undef HAVE_UNISTD_H //to avoid redefinition # ifndef _LFS64_LARGEFILE # define _LFS64_LARGEFILE 0 # endif diff --git a/modules/core/src/precomp.cpp b/modules/core/src/precomp.cpp deleted file mode 100644 index e540cc5e8a..0000000000 --- a/modules/core/src/precomp.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "precomp.hpp" - -/* End of file. */ diff --git a/modules/core/src/precomp.hpp b/modules/core/src/precomp.hpp index 84f7f5e2be..c53224e0aa 100644 --- a/modules/core/src/precomp.hpp +++ b/modules/core/src/precomp.hpp @@ -43,9 +43,7 @@ #ifndef __OPENCV_PRECOMP_H__ #define __OPENCV_PRECOMP_H__ -#ifdef HAVE_CVCONFIG_H #include "cvconfig.h" -#endif #include "opencv2/core/core.hpp" #include "opencv2/core/core_c.h" diff --git a/modules/core/src/rand.cpp b/modules/core/src/rand.cpp index 2cdbe3916d..54bb753a15 100644 --- a/modules/core/src/rand.cpp +++ b/modules/core/src/rand.cpp @@ -726,33 +726,54 @@ void RNG::fill( InputOutputArray _mat, int disttype, } #ifdef WIN32 + + +#ifdef HAVE_WINRT +// using C++11 thread attribute for local thread data +__declspec( thread ) RNG* rng = NULL; + + void deleteThreadRNGData() + { + if (rng) + delete rng; +} + +RNG& theRNG() +{ + if (!rng) + { + rng = new RNG; + } + return *rng; +} +#else #ifdef WINCE # define TLS_OUT_OF_INDEXES ((DWORD)0xFFFFFFFF) #endif static DWORD tlsRNGKey = TLS_OUT_OF_INDEXES; -void deleteThreadRNGData() -{ - if( tlsRNGKey != TLS_OUT_OF_INDEXES ) - delete (RNG*)TlsGetValue( tlsRNGKey ); + void deleteThreadRNGData() + { + if( tlsRNGKey != TLS_OUT_OF_INDEXES ) + delete (RNG*)TlsGetValue( tlsRNGKey ); } RNG& theRNG() { if( tlsRNGKey == TLS_OUT_OF_INDEXES ) { - tlsRNGKey = TlsAlloc(); - CV_Assert(tlsRNGKey != TLS_OUT_OF_INDEXES); + tlsRNGKey = TlsAlloc(); + CV_Assert(tlsRNGKey != TLS_OUT_OF_INDEXES); } RNG* rng = (RNG*)TlsGetValue( tlsRNGKey ); if( !rng ) { - rng = new RNG; - TlsSetValue( tlsRNGKey, rng ); + rng = new RNG; + TlsSetValue( tlsRNGKey, rng ); } return *rng; } - +#endif //HAVE_WINRT #else static pthread_key_t tlsRNGKey = 0; diff --git a/modules/core/src/stat.cpp b/modules/core/src/stat.cpp index e069e52985..d8f28e204f 100644 --- a/modules/core/src/stat.cpp +++ b/modules/core/src/stat.cpp @@ -439,6 +439,45 @@ cv::Scalar cv::sum( InputArray _src ) { Mat src = _src.getMat(); int k, cn = src.channels(), depth = src.depth(); + +#if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7) + size_t total_size = src.total(); + int rows = src.size[0], cols = (int)(total_size/rows); + if( src.dims == 2 || (src.isContinuous() && cols > 0 && (size_t)rows*cols == total_size) ) + { + IppiSize sz = { cols, rows }; + int type = src.type(); + typedef IppStatus (CV_STDCALL* ippiSumFunc)(const void*, int, IppiSize, double *, int); + ippiSumFunc ippFunc = + type == CV_8UC1 ? (ippiSumFunc)ippiSum_8u_C1R : + type == CV_8UC3 ? (ippiSumFunc)ippiSum_8u_C3R : + type == CV_8UC4 ? (ippiSumFunc)ippiSum_8u_C4R : + type == CV_16UC1 ? (ippiSumFunc)ippiSum_16u_C1R : + type == CV_16UC3 ? (ippiSumFunc)ippiSum_16u_C3R : + type == CV_16UC4 ? (ippiSumFunc)ippiSum_16u_C4R : + type == CV_16SC1 ? (ippiSumFunc)ippiSum_16s_C1R : + type == CV_16SC3 ? (ippiSumFunc)ippiSum_16s_C3R : + type == CV_16SC4 ? (ippiSumFunc)ippiSum_16s_C4R : + type == CV_32FC1 ? (ippiSumFunc)ippiSum_32f_C1R : + type == CV_32FC3 ? (ippiSumFunc)ippiSum_32f_C3R : + type == CV_32FC4 ? (ippiSumFunc)ippiSum_32f_C4R : + 0; + if( ippFunc ) + { + Ipp64f res[4]; + if( ippFunc(src.data, src.step[0], sz, res, ippAlgHintAccurate) >= 0 ) + { + Scalar sc; + for( int i = 0; i < cn; i++ ) + { + sc[i] = res[i]; + } + return sc; + } + } + } +#endif + SumFunc func = sumTab[depth]; CV_Assert( cn <= 4 && func != 0 ); @@ -512,6 +551,81 @@ cv::Scalar cv::mean( InputArray _src, InputArray _mask ) CV_Assert( mask.empty() || mask.type() == CV_8U ); int k, cn = src.channels(), depth = src.depth(); + +#if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7) + size_t total_size = src.total(); + int rows = src.size[0], cols = (int)(total_size/rows); + if( src.dims == 2 || (src.isContinuous() && mask.isContinuous() && cols > 0 && (size_t)rows*cols == total_size) ) + { + IppiSize sz = { cols, rows }; + int type = src.type(); + if( !mask.empty() ) + { + typedef IppStatus (CV_STDCALL* ippiMaskMeanFuncC1)(const void *, int, void *, int, IppiSize, Ipp64f *); + ippiMaskMeanFuncC1 ippFuncC1 = + type == CV_8UC1 ? (ippiMaskMeanFuncC1)ippiMean_8u_C1MR : + type == CV_16UC1 ? (ippiMaskMeanFuncC1)ippiMean_16u_C1MR : + type == CV_32FC1 ? (ippiMaskMeanFuncC1)ippiMean_32f_C1MR : + 0; + if( ippFuncC1 ) + { + Ipp64f res; + if( ippFuncC1(src.data, src.step[0], mask.data, mask.step[0], sz, &res) >= 0 ) + { + return Scalar(res); + } + } + typedef IppStatus (CV_STDCALL* ippiMaskMeanFuncC3)(const void *, int, void *, int, IppiSize, int, Ipp64f *); + ippiMaskMeanFuncC3 ippFuncC3 = + type == CV_8UC3 ? (ippiMaskMeanFuncC3)ippiMean_8u_C3CMR : + type == CV_16UC3 ? (ippiMaskMeanFuncC3)ippiMean_16u_C3CMR : + type == CV_32FC3 ? (ippiMaskMeanFuncC3)ippiMean_32f_C3CMR : + 0; + if( ippFuncC3 ) + { + Ipp64f res1, res2, res3; + if( ippFuncC3(src.data, src.step[0], mask.data, mask.step[0], sz, 1, &res1) >= 0 && + ippFuncC3(src.data, src.step[0], mask.data, mask.step[0], sz, 2, &res2) >= 0 && + ippFuncC3(src.data, src.step[0], mask.data, mask.step[0], sz, 3, &res3) >= 0 ) + { + return Scalar(res1, res2, res3); + } + } + } + else + { + typedef IppStatus (CV_STDCALL* ippiMeanFunc)(const void*, int, IppiSize, double *, int); + ippiMeanFunc ippFunc = + type == CV_8UC1 ? (ippiMeanFunc)ippiMean_8u_C1R : + type == CV_8UC3 ? (ippiMeanFunc)ippiMean_8u_C3R : + type == CV_8UC4 ? (ippiMeanFunc)ippiMean_8u_C4R : + type == CV_16UC1 ? (ippiMeanFunc)ippiMean_16u_C1R : + type == CV_16UC3 ? (ippiMeanFunc)ippiMean_16u_C3R : + type == CV_16UC4 ? (ippiMeanFunc)ippiMean_16u_C4R : + type == CV_16SC1 ? (ippiMeanFunc)ippiMean_16s_C1R : + type == CV_16SC3 ? (ippiMeanFunc)ippiMean_16s_C3R : + type == CV_16SC4 ? (ippiMeanFunc)ippiMean_16s_C4R : + type == CV_32FC1 ? (ippiMeanFunc)ippiMean_32f_C1R : + type == CV_32FC3 ? (ippiMeanFunc)ippiMean_32f_C3R : + type == CV_32FC4 ? (ippiMeanFunc)ippiMean_32f_C4R : + 0; + if( ippFunc ) + { + Ipp64f res[4]; + if( ippFunc(src.data, src.step[0], sz, res, ippAlgHintAccurate) >= 0 ) + { + Scalar sc; + for( int i = 0; i < cn; i++ ) + { + sc[i] = res[i]; + } + return sc; + } + } + } + } +#endif + SumFunc func = sumTab[depth]; CV_Assert( cn <= 4 && func != 0 ); diff --git a/modules/core/src/system.cpp b/modules/core/src/system.cpp index a891e94cce..7e01ca5ea4 100644 --- a/modules/core/src/system.cpp +++ b/modules/core/src/system.cpp @@ -47,6 +47,9 @@ #define _WIN32_WINNT 0x0400 // http://msdn.microsoft.com/en-us/library/ms686857(VS.85).aspx #endif #include +#if (_WIN32_WINNT >= 0x0602) + #include +#endif #undef small #undef min #undef max @@ -75,6 +78,30 @@ } #endif #endif + +#ifdef HAVE_WINRT +#include + +std::wstring GetTempPathWinRT() +{ + return std::wstring(Windows::Storage::ApplicationData::Current->TemporaryFolder->Path->Data()); +} + +std::wstring GetTempFileNameWinRT(std::wstring prefix) +{ + wchar_t guidStr[40]; + GUID g; + CoCreateGuid(&g); + wchar_t* mask = L"%08x_%04x_%04x_%02x%02x_%02x%02x%02x%02x%02x%02x"; + swprintf(&guidStr[0], sizeof(guidStr)/sizeof(wchar_t), mask, + g.Data1, g.Data2, g.Data3, UINT(g.Data4[0]), UINT(g.Data4[1]), + UINT(g.Data4[2]), UINT(g.Data4[3]), UINT(g.Data4[4]), + UINT(g.Data4[5]), UINT(g.Data4[6]), UINT(g.Data4[7])); + + return prefix + std::wstring(guidStr); +} + +#endif #else #include #include @@ -359,10 +386,38 @@ string format( const char* fmt, ... ) string tempfile( const char* suffix ) { +#ifdef HAVE_WINRT + std::wstring temp_dir = L""; + const wchar_t* opencv_temp_dir = _wgetenv(L"OPENCV_TEMP_PATH"); + if (opencv_temp_dir) + temp_dir = std::wstring(opencv_temp_dir); +#else const char *temp_dir = getenv("OPENCV_TEMP_PATH"); +#endif string fname; #if defined WIN32 || defined _WIN32 +#ifdef HAVE_WINRT + RoInitialize(RO_INIT_MULTITHREADED); + std::wstring temp_dir2; + if (temp_dir.empty()) + temp_dir = GetTempPathWinRT(); + + std::wstring temp_file; + temp_file = GetTempFileNameWinRT(L"ocv"); + if (temp_file.empty()) + return std::string(); + + temp_file = temp_dir + std::wstring(L"\\") + temp_file; + DeleteFileW(temp_file.c_str()); + + size_t asize = wcstombs(NULL, temp_file.c_str(), 0); + Ptr aname = new char[asize+1]; + aname[asize] = 0; + wcstombs(aname, temp_file.c_str(), asize); + fname = std::string(aname); + RoUninitialize(); +#else char temp_dir2[MAX_PATH + 1] = { 0 }; char temp_file[MAX_PATH + 1] = { 0 }; @@ -377,6 +432,7 @@ string tempfile( const char* suffix ) DeleteFileA(temp_file); fname = temp_file; +#endif # else # ifdef ANDROID //char defaultTemplate[] = "/mnt/sdcard/__opencv_temp.XXXXXX"; @@ -469,40 +525,6 @@ redirectError( CvErrorCallback errCallback, void* userdata, void** prevUserdata) } -/*CV_IMPL int -cvGuiBoxReport( int code, const char *func_name, const char *err_msg, - const char *file, int line, void* ) -{ -#if (!defined WIN32 && !defined _WIN32) || defined WINCE - return cvStdErrReport( code, func_name, err_msg, file, line, 0 ); -#else - if( code != CV_StsBackTrace && code != CV_StsAutoTrace ) - { - size_t msg_len = strlen(err_msg ? err_msg : "") + 1024; - char* message = (char*)alloca(msg_len); - char title[100]; - - wsprintf( message, "%s (%s)\nin function %s, %s(%d)\n\n" - "Press \"Abort\" to terminate application.\n" - "Press \"Retry\" to debug (if the app is running under debugger).\n" - "Press \"Ignore\" to continue (this is not safe).\n", - cvErrorStr(code), err_msg ? err_msg : "no description", - func_name, file, line ); - - wsprintf( title, "OpenCV GUI Error Handler" ); - - int answer = MessageBox( NULL, message, title, MB_ICONERROR|MB_ABORTRETRYIGNORE|MB_SYSTEMMODAL ); - - if( answer == IDRETRY ) - { - CV_DBG_BREAK(); - } - return answer != IDIGNORE; - } - return 0; -#endif -}*/ - CV_IMPL int cvCheckHardwareSupport(int feature) { CV_DbgAssert( 0 <= feature && feature <= CV_HARDWARE_MAX_FEATURE ); @@ -779,7 +801,11 @@ cvGetModuleInfo( const char* name, const char **version, const char **plugin_lis *plugin_list = plugin_list_buf; } -#if defined BUILD_SHARED_LIBS && defined CVAPI_EXPORTS && defined WIN32 && !defined WINCE +#if defined CVAPI_EXPORTS && defined WIN32 && !defined WINCE +#ifdef HAVE_WINRT + #pragma warning(disable:4447) // Disable warning 'main' signature found without threading model +#endif + BOOL WINAPI DllMain( HINSTANCE, DWORD fdwReason, LPVOID ); BOOL WINAPI DllMain( HINSTANCE, DWORD fdwReason, LPVOID ) @@ -800,7 +826,15 @@ namespace cv struct Mutex::Impl { - Impl() { InitializeCriticalSection(&cs); refcount = 1; } + Impl() + { +#if (_WIN32_WINNT >= 0x0600) + ::InitializeCriticalSectionEx(&cs, 1000, 0); +#else + ::InitializeCriticalSection(&cs); +#endif + refcount = 1; + } ~Impl() { DeleteCriticalSection(&cs); } void lock() { EnterCriticalSection(&cs); } @@ -904,4 +938,4 @@ bool Mutex::trylock() { return impl->trylock(); } } -/* End of file. */ \ No newline at end of file +/* End of file. */ diff --git a/modules/core/test/test_arithm.cpp b/modules/core/test/test_arithm.cpp index a3e61f22a3..0bb185d2d2 100644 --- a/modules/core/test/test_arithm.cpp +++ b/modules/core/test/test_arithm.cpp @@ -1123,7 +1123,7 @@ struct MeanOp : public BaseElemWiseOp } double getMaxErr(int) { - return 1e-6; + return 1e-5; } }; diff --git a/modules/core/test/test_main.cpp b/modules/core/test/test_main.cpp index 6b24993447..3294fab2b0 100644 --- a/modules/core/test/test_main.cpp +++ b/modules/core/test/test_main.cpp @@ -1,3 +1,7 @@ +#ifdef HAVE_WINRT + #pragma warning(disable:4447) // Disable warning 'main' signature found without threading model +#endif + #include "test_precomp.hpp" CV_TEST_MAIN("cv") diff --git a/modules/core/test/test_precomp.cpp b/modules/core/test/test_precomp.cpp deleted file mode 100644 index 5956e13e3e..0000000000 --- a/modules/core/test/test_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "test_precomp.hpp" diff --git a/modules/features2d/doc/common_interfaces_of_descriptor_extractors.rst b/modules/features2d/doc/common_interfaces_of_descriptor_extractors.rst index 63e56f6786..3639bd6002 100644 --- a/modules/features2d/doc/common_interfaces_of_descriptor_extractors.rst +++ b/modules/features2d/doc/common_interfaces_of_descriptor_extractors.rst @@ -9,7 +9,10 @@ represented as vectors in a multidimensional space. All objects that implement t descriptor extractors inherit the :ocv:class:`DescriptorExtractor` interface. +.. note:: + * An example explaining keypoint extraction can be found at opencv_source_code/samples/cpp/descriptor_extractor_matcher.cpp + * An example on descriptor evaluation can be found at opencv_source_code/samples/cpp/detector_descriptor_evaluation.cpp DescriptorExtractor ------------------- @@ -78,9 +81,10 @@ The current implementation supports the following types of a descriptor extracto * ``"SIFT"`` -- :ocv:class:`SIFT` * ``"SURF"`` -- :ocv:class:`SURF` - * ``"ORB"`` -- :ocv:class:`ORB` - * ``"BRISK"`` -- :ocv:class:`BRISK` * ``"BRIEF"`` -- :ocv:class:`BriefDescriptorExtractor` + * ``"BRISK"`` -- :ocv:class:`BRISK` + * ``"ORB"`` -- :ocv:class:`ORB` + * ``"FREAK"`` -- :ocv:class:`FREAK` A combined format is also supported: descriptor extractor adapter name ( ``"Opponent"`` -- :ocv:class:`OpponentColorDescriptorExtractor` ) + descriptor extractor name (see above), @@ -137,4 +141,6 @@ Strecha C., Fua P. *BRIEF: Binary Robust Independent Elementary Features* , ... }; +.. note:: + * A complete BRIEF extractor sample can be found at opencv_source_code/samples/cpp/brief_match_test.cpp diff --git a/modules/features2d/doc/common_interfaces_of_descriptor_matchers.rst b/modules/features2d/doc/common_interfaces_of_descriptor_matchers.rst index d7e5eb4c29..264d3a1bbf 100644 --- a/modules/features2d/doc/common_interfaces_of_descriptor_matchers.rst +++ b/modules/features2d/doc/common_interfaces_of_descriptor_matchers.rst @@ -9,6 +9,12 @@ that are represented as vectors in a multidimensional space. All objects that im descriptor matchers inherit the :ocv:class:`DescriptorMatcher` interface. +.. note:: + + * An example explaining keypoint matching can be found at opencv_source_code/samples/cpp/descriptor_extractor_matcher.cpp + * An example on descriptor matching evaluation can be found at opencv_source_code/samples/cpp/detector_descriptor_matcher_evaluation.cpp + * An example on one to many image matching can be found at opencv_source_code/samples/cpp/matching_to_many_images.cpp + DMatch ------ .. ocv:struct:: DMatch diff --git a/modules/features2d/doc/common_interfaces_of_feature_detectors.rst b/modules/features2d/doc/common_interfaces_of_feature_detectors.rst index 81c72d3a81..51efca5ce9 100644 --- a/modules/features2d/doc/common_interfaces_of_feature_detectors.rst +++ b/modules/features2d/doc/common_interfaces_of_feature_detectors.rst @@ -8,6 +8,11 @@ between different algorithms solving the same problem. All objects that implemen inherit the :ocv:class:`FeatureDetector` interface. +.. note:: + + * An example explaining keypoint detection can be found at opencv_source_code/samples/cpp/descriptor_extractor_matcher.cpp + + KeyPoint -------- .. ocv:class:: KeyPoint @@ -220,7 +225,7 @@ StarFeatureDetector ------------------- .. ocv:class:: StarFeatureDetector : public FeatureDetector -The class implements the keypoint detector introduced by K. Konolige, synonym of ``StarDetector``. :: +The class implements the keypoint detector introduced by [Agrawal08]_, synonym of ``StarDetector``. :: class StarFeatureDetector : public FeatureDetector { @@ -234,6 +239,9 @@ The class implements the keypoint detector introduced by K. Konolige, synonym of ... }; +.. [Agrawal08] Agrawal, M., Konolige, K., & Blas, M. R. (2008). Censure: Center surround extremas for realtime feature detection and matching. In Computer Vision–ECCV 2008 (pp. 102-115). Springer Berlin Heidelberg. + + DenseFeatureDetector -------------------- .. ocv:class:: DenseFeatureDetector : public FeatureDetector diff --git a/modules/features2d/doc/common_interfaces_of_generic_descriptor_matchers.rst b/modules/features2d/doc/common_interfaces_of_generic_descriptor_matchers.rst index a306c66067..fcdc8b9b0e 100644 --- a/modules/features2d/doc/common_interfaces_of_generic_descriptor_matchers.rst +++ b/modules/features2d/doc/common_interfaces_of_generic_descriptor_matchers.rst @@ -11,7 +11,11 @@ Every descriptor with the :ocv:class:`VectorDescriptorMatcher` ). There are descriptors such as the One-way descriptor and Ferns that have the ``GenericDescriptorMatcher`` interface implemented but do not support ``DescriptorExtractor``. +.. note:: + * An example explaining keypoint description can be found at opencv_source_code/samples/cpp/descriptor_extractor_matcher.cpp + * An example on descriptor matching evaluation can be found at opencv_source_code/samples/cpp/detector_descriptor_matcher_evaluation.cpp + * An example on one to many image matching can be found at opencv_source_code/samples/cpp/matching_to_many_images.cpp GenericDescriptorMatcher ------------------------ diff --git a/modules/features2d/doc/feature_detection_and_description.rst b/modules/features2d/doc/feature_detection_and_description.rst index 80a1de04a4..a0272026d6 100644 --- a/modules/features2d/doc/feature_detection_and_description.rst +++ b/modules/features2d/doc/feature_detection_and_description.rst @@ -3,6 +3,10 @@ Feature Detection and Description .. highlight:: cpp +.. note:: + + * An example explaining keypoint detection and description can be found at opencv_source_code/samples/cpp/descriptor_extractor_matcher.cpp + FAST ---- Detects corners using the FAST algorithm @@ -51,6 +55,10 @@ Maximally stable extremal region extractor. :: The class encapsulates all the parameters of the MSER extraction algorithm (see http://en.wikipedia.org/wiki/Maximally_stable_extremal_regions). Also see http://code.opencv.org/projects/opencv/wiki/MSER for useful comments and parameters description. +.. note:: + + * (Python) A complete example showing the use of the MSER detector can be found at opencv_source_code/samples/python2/mser.py + ORB --- @@ -158,6 +166,10 @@ Class implementing the FREAK (*Fast Retina Keypoint*) keypoint descriptor, descr .. [AOV12] A. Alahi, R. Ortiz, and P. Vandergheynst. FREAK: Fast Retina Keypoint. In IEEE Conference on Computer Vision and Pattern Recognition, 2012. CVPR 2012 Open Source Award Winner. +.. note:: + + * An example on how to use the FREAK descriptor can be found at opencv_source_code/samples/cpp/freak_demo.cpp + FREAK::FREAK ------------ The FREAK constructor diff --git a/modules/features2d/doc/object_categorization.rst b/modules/features2d/doc/object_categorization.rst index d7b34aff5f..cf10460f69 100644 --- a/modules/features2d/doc/object_categorization.rst +++ b/modules/features2d/doc/object_categorization.rst @@ -5,6 +5,12 @@ Object Categorization This section describes approaches based on local 2D features and used to categorize objects. +.. note:: + + * A complete Bag-Of-Words sample can be found at opencv_source_code/samples/cpp/bagofwords_classification.cpp + + * (Python) An example using the features2D framework to perform object categorization can be found at opencv_source_code/samples/python2/find_obj.py + BOWTrainer ---------- .. ocv:class:: BOWTrainer diff --git a/modules/features2d/include/opencv2/features2d/features2d.hpp b/modules/features2d/include/opencv2/features2d/features2d.hpp index c1967f813c..d4649baab9 100644 --- a/modules/features2d/include/opencv2/features2d/features2d.hpp +++ b/modules/features2d/include/opencv2/features2d/features2d.hpp @@ -263,6 +263,8 @@ public: OutputArray descriptors, bool useProvidedKeypoints=false ) const = 0; + CV_WRAP void compute( const Mat& image, CV_OUT CV_IN_OUT std::vector& keypoints, CV_OUT Mat& descriptors ) const; + // Create feature detector and descriptor extractor by name. CV_WRAP static Ptr create( const string& name ); }; diff --git a/modules/features2d/perf/perf_precomp.cpp b/modules/features2d/perf/perf_precomp.cpp deleted file mode 100644 index 8552ac3d42..0000000000 --- a/modules/features2d/perf/perf_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "perf_precomp.hpp" diff --git a/modules/features2d/src/bagofwords.cpp b/modules/features2d/src/bagofwords.cpp index 9770064c90..898c6342dd 100644 --- a/modules/features2d/src/bagofwords.cpp +++ b/modules/features2d/src/bagofwords.cpp @@ -149,7 +149,7 @@ void BOWImgDescriptorExtractor::compute( const Mat& image, vector& key int clusterCount = descriptorSize(); // = vocabulary.rows // Compute descriptors for the image. - Mat descriptors = _descriptors ? *_descriptors : Mat(); + Mat descriptors; dextractor->compute( image, keypoints, descriptors ); // Match keypoint descriptors to cluster center (to vocabulary) @@ -178,6 +178,11 @@ void BOWImgDescriptorExtractor::compute( const Mat& image, vector& key // Normalize image descriptor. imgDescriptor /= descriptors.rows; + + // Add the descriptors of image keypoints + if (_descriptors) { + *_descriptors = descriptors.clone(); + } } int BOWImgDescriptorExtractor::descriptorSize() const diff --git a/modules/features2d/src/brisk.cpp b/modules/features2d/src/brisk.cpp index d1fa0c9c8b..622f772290 100644 --- a/modules/features2d/src/brisk.cpp +++ b/modules/features2d/src/brisk.cpp @@ -525,7 +525,11 @@ BRISK::operator()( InputArray _image, InputArray _mask, vector& keypoi bool doOrientation=true; if (useProvidedKeypoints) doOrientation = false; - computeDescriptorsAndOrOrientation(_image, _mask, keypoints, _descriptors, true, doOrientation, + + // If the user specified cv::noArray(), this will yield false. Otherwise it will return true. + bool doDescriptors = _descriptors.needed(); + + computeDescriptorsAndOrOrientation(_image, _mask, keypoints, _descriptors, doDescriptors, doOrientation, useProvidedKeypoints); } diff --git a/modules/features2d/src/descriptors.cpp b/modules/features2d/src/descriptors.cpp index 06efe97913..c9e87c2ba8 100644 --- a/modules/features2d/src/descriptors.cpp +++ b/modules/features2d/src/descriptors.cpp @@ -106,6 +106,12 @@ Ptr DescriptorExtractor::create(const string& descriptorExt return Algorithm::create("Feature2D." + descriptorExtractorType); } + +CV_WRAP void Feature2D::compute( const Mat& image, CV_OUT CV_IN_OUT std::vector& keypoints, CV_OUT Mat& descriptors ) const +{ + DescriptorExtractor::compute(image, keypoints, descriptors); +} + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// /****************************************************************************************\ diff --git a/modules/features2d/src/precomp.cpp b/modules/features2d/src/precomp.cpp deleted file mode 100644 index 3e0ec42de9..0000000000 --- a/modules/features2d/src/precomp.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/*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 "precomp.hpp" - -/* End of file. */ diff --git a/modules/features2d/src/precomp.hpp b/modules/features2d/src/precomp.hpp index cbc1eb690a..72f6186000 100644 --- a/modules/features2d/src/precomp.hpp +++ b/modules/features2d/src/precomp.hpp @@ -43,9 +43,7 @@ #ifndef __OPENCV_PRECOMP_H__ #define __OPENCV_PRECOMP_H__ -#ifdef HAVE_CVCONFIG_H #include "cvconfig.h" -#endif #include "opencv2/features2d/features2d.hpp" #include "opencv2/imgproc/imgproc.hpp" diff --git a/modules/features2d/test/test_precomp.cpp b/modules/features2d/test/test_precomp.cpp deleted file mode 100644 index 5956e13e3e..0000000000 --- a/modules/features2d/test/test_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "test_precomp.hpp" diff --git a/modules/flann/include/opencv2/flann/dist.h b/modules/flann/include/opencv2/flann/dist.h index 7380d0c5d5..80ae2dc916 100644 --- a/modules/flann/include/opencv2/flann/dist.h +++ b/modules/flann/include/opencv2/flann/dist.h @@ -43,8 +43,12 @@ typedef unsigned __int64 uint64_t; #include "defines.h" +#if (defined WIN32 || defined _WIN32) && defined(_M_ARM) +# include +#endif + #ifdef __ARM_NEON__ -#include "arm_neon.h" +# include "arm_neon.h" #endif namespace cvflann diff --git a/modules/flann/src/precomp.cpp b/modules/flann/src/precomp.cpp deleted file mode 100644 index c149df18f9..0000000000 --- a/modules/flann/src/precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "precomp.hpp" diff --git a/modules/flann/src/precomp.hpp b/modules/flann/src/precomp.hpp index fb5ee3f982..76d83992e5 100644 --- a/modules/flann/src/precomp.hpp +++ b/modules/flann/src/precomp.hpp @@ -5,9 +5,7 @@ #include #include -#ifdef HAVE_CVCONFIG_H # include "cvconfig.h" -#endif #include "opencv2/core/core.hpp" #include "opencv2/core/internal.hpp" diff --git a/modules/flann/test/test_precomp.cpp b/modules/flann/test/test_precomp.cpp deleted file mode 100644 index 5956e13e3e..0000000000 --- a/modules/flann/test/test_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "test_precomp.hpp" diff --git a/modules/gpu/doc/camera_calibration_and_3d_reconstruction.rst b/modules/gpu/doc/camera_calibration_and_3d_reconstruction.rst index 587c253d2a..d99def207c 100644 --- a/modules/gpu/doc/camera_calibration_and_3d_reconstruction.rst +++ b/modules/gpu/doc/camera_calibration_and_3d_reconstruction.rst @@ -44,8 +44,12 @@ The class also performs pre- and post-filtering steps: Sobel pre-filtering (if ` This means that the input left image is low textured. +.. note:: - + * A basic stereo matching example can be found at opencv_source_code/samples/gpu/stereo_match.cpp + * A stereo matching example using several GPU's can be found at opencv_source_code/samples/gpu/stereo_multi.cpp + * A stereo matching example using several GPU's and driver API can be found at opencv_source_code/samples/gpu/driver_api_stereo_multi.cpp + gpu::StereoBM_GPU::StereoBM_GPU ----------------------------------- Enables :ocv:class:`gpu::StereoBM_GPU` constructors. diff --git a/modules/gpu/doc/image_filtering.rst b/modules/gpu/doc/image_filtering.rst index 348a42510e..824fbfa4f0 100644 --- a/modules/gpu/doc/image_filtering.rst +++ b/modules/gpu/doc/image_filtering.rst @@ -5,7 +5,9 @@ Image Filtering Functions and classes described in this section are used to perform various linear or non-linear filtering operations on 2D images. +.. note:: + * An example containing all basic morphology operators like erode and dilate can be found at opencv_source_code/samples/gpu/morphology.cpp gpu::BaseRowFilter_GPU ---------------------- diff --git a/modules/gpu/doc/image_processing.rst b/modules/gpu/doc/image_processing.rst index 0b3254033d..abf4fdabae 100644 --- a/modules/gpu/doc/image_processing.rst +++ b/modules/gpu/doc/image_processing.rst @@ -966,7 +966,9 @@ Composites two images using alpha opacity values contained in each image. :param stream: Stream for the asynchronous version. +.. note:: + * An example demonstrating the use of alphaComp can be found at opencv_source_code/samples/gpu/alpha_comp.cpp gpu::Canny ------------------- @@ -1028,7 +1030,9 @@ Finds lines in a binary image using the classical Hough transform. .. seealso:: :ocv:func:`HoughLines` +.. note:: + * An example using the Hough lines detector can be found at opencv_source_code/samples/gpu/houghlines.cpp gpu::HoughLinesDownload ----------------------- diff --git a/modules/gpu/doc/object_detection.rst b/modules/gpu/doc/object_detection.rst index 133660236a..c8e2dbf0a7 100644 --- a/modules/gpu/doc/object_detection.rst +++ b/modules/gpu/doc/object_detection.rst @@ -62,7 +62,12 @@ The class implements Histogram of Oriented Gradients ([Dalal2005]_) object detec Interfaces of all methods are kept similar to the ``CPU HOG`` descriptor and detector analogues as much as possible. +.. note:: + * An example applying the HOG descriptor for people detection can be found at opencv_source_code/samples/cpp/peopledetect.cpp + * A GPU example applying the HOG descriptor for people detection can be found at opencv_source_code/samples/gpu/hog.cpp + + * (Python) An example applying the HOG descriptor for people detection can be found at opencv_source_code/samples/python2/peopledetect.py gpu::HOGDescriptor::HOGDescriptor ------------------------------------- @@ -230,7 +235,10 @@ Cascade classifier class used for object detection. Supports HAAR and LBP cascad Size getClassifierSize() const; }; +.. note:: + * A cascade classifier example can be found at opencv_source_code/samples/gpu/cascadeclassifier.cpp + * A Nvidea API specific cascade classifier example can be found at opencv_source_code/samples/gpu/cascadeclassifier_nvidia_api.cpp gpu::CascadeClassifier_GPU::CascadeClassifier_GPU ----------------------------------------------------- diff --git a/modules/gpu/doc/video.rst b/modules/gpu/doc/video.rst index 284bb17fa9..7b8dde6016 100644 --- a/modules/gpu/doc/video.rst +++ b/modules/gpu/doc/video.rst @@ -3,8 +3,11 @@ Video Analysis .. highlight:: cpp +.. note:: - + * A general optical flow example can be found at opencv_source_code/samples/gpu/optical_flow.cpp + * A general optical flow example using the Nvidia API can be found at opencv_source_code/samples/gpu/opticalflow_nvidia_api.cpp + gpu::BroxOpticalFlow -------------------- .. ocv:class:: gpu::BroxOpticalFlow @@ -44,7 +47,9 @@ Class computing the optical flow for two images using Brox et al Optical Flow al GpuMat buf; }; +.. note:: + * An example illustrating the Brox et al optical flow algorithm can be found at opencv_source_code/samples/gpu/brox_optical_flow.cpp gpu::GoodFeaturesToTrackDetector_GPU ------------------------------------ @@ -213,7 +218,9 @@ The class can calculate an optical flow for a sparse feature set or dense optica .. seealso:: :ocv:func:`calcOpticalFlowPyrLK` +.. note:: + * An example of the Lucas Kanade optical flow algorithm can be found at opencv_source_code/samples/gpu/pyrlk_optical_flow.cpp gpu::PyrLKOpticalFlow::sparse ----------------------------- @@ -418,7 +425,9 @@ The class discriminates between foreground and background pixels by building and .. seealso:: :ocv:class:`BackgroundSubtractorMOG` +.. note:: + * An example on gaussian mixture based background/foreground segmantation can be found at opencv_source_code/samples/gpu/bgfg_segm.cpp gpu::MOG_GPU::MOG_GPU --------------------- @@ -697,7 +706,9 @@ The class uses H264 video codec. .. note:: Currently only Windows platform is supported. +.. note:: + * An example on how to use the videoWriter class can be found at opencv_source_code/samples/gpu/video_writer.cpp gpu::VideoWriter_GPU::VideoWriter_GPU ------------------------------------- @@ -910,7 +921,9 @@ Class for reading video from files. .. note:: Currently only Windows and Linux platforms are supported. +.. note:: + * An example on how to use the videoReader class can be found at opencv_source_code/samples/gpu/video_reader.cpp gpu::VideoReader_GPU::Codec --------------------------- diff --git a/modules/gpu/perf/perf_imgproc.cpp b/modules/gpu/perf/perf_imgproc.cpp index ee4601277f..c7fb2a17c0 100644 --- a/modules/gpu/perf/perf_imgproc.cpp +++ b/modules/gpu/perf/perf_imgproc.cpp @@ -562,7 +562,17 @@ PERF_TEST_P(Sz, ImgProc_CalcHist, } else { - FAIL_NO_CPU(); + cv::Mat dst; + + const int hbins = 256; + const float hranges[] = {0.0f, 256.0f}; + const int histSize[] = {hbins}; + const float* ranges[] = {hranges}; + const int channels[] = {0}; + + TEST_CYCLE() cv::calcHist(&src, 1, channels, cv::Mat(), dst, 1, histSize, ranges); + + CPU_SANITY_CHECK(dst); } } diff --git a/modules/gpu/perf/perf_precomp.cpp b/modules/gpu/perf/perf_precomp.cpp deleted file mode 100644 index 81f16e8f14..0000000000 --- a/modules/gpu/perf/perf_precomp.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "perf_precomp.hpp" diff --git a/modules/gpu/perf4au/main.cpp b/modules/gpu/perf4au/main.cpp index f6a65ad636..8c68385e1e 100644 --- a/modules/gpu/perf4au/main.cpp +++ b/modules/gpu/perf4au/main.cpp @@ -42,9 +42,7 @@ #include -#ifdef HAVE_CVCONFIG_H #include "cvconfig.h" -#endif #include "opencv2/ts/ts.hpp" #include "opencv2/ts/gpu_perf.hpp" @@ -55,16 +53,12 @@ #include "opencv2/video/video.hpp" #include "opencv2/legacy/legacy.hpp" -int main(int argc, char* argv[]) -{ - perf::printCudaInfo(); - - perf::Regression::Init("gpu_perf4au"); - perf::TestBase::Init(argc, argv); - testing::InitGoogleTest(&argc, argv); +static const char * impls[] = { + "cuda", + "plain" +}; - return RUN_ALL_TESTS(); -} +CV_PERF_TEST_MAIN_WITH_IMPLS(gpu_perf4au, impls, perf::printCudaInfo()) ////////////////////////////////////////////////////////// // HoughLinesP diff --git a/modules/gpu/src/cuda/hist.cu b/modules/gpu/src/cuda/hist.cu index 8b8a1e8c63..d0ec257c47 100644 --- a/modules/gpu/src/cuda/hist.cu +++ b/modules/gpu/src/cuda/hist.cu @@ -109,6 +109,86 @@ namespace hist ///////////////////////////////////////////////////////////////////////// +namespace hist +{ + __device__ __forceinline__ void histEvenInc(int* shist, uint data, int binSize, int lowerLevel, int upperLevel) + { + if (data >= lowerLevel && data <= upperLevel) + { + const uint ind = (data - lowerLevel) / binSize; + Emulation::smem::atomicAdd(shist + ind, 1); + } + } + + __global__ void histEven8u(const uchar* src, const size_t step, const int rows, const int cols, + int* hist, const int binCount, const int binSize, const int lowerLevel, const int upperLevel) + { + extern __shared__ int shist[]; + + const int y = blockIdx.x * blockDim.y + threadIdx.y; + const int tid = threadIdx.y * blockDim.x + threadIdx.x; + + if (tid < binCount) + shist[tid] = 0; + + __syncthreads(); + + if (y < rows) + { + const uchar* rowPtr = src + y * step; + const uint* rowPtr4 = (uint*) rowPtr; + + const int cols_4 = cols / 4; + for (int x = threadIdx.x; x < cols_4; x += blockDim.x) + { + const uint data = rowPtr4[x]; + + histEvenInc(shist, (data >> 0) & 0xFFU, binSize, lowerLevel, upperLevel); + histEvenInc(shist, (data >> 8) & 0xFFU, binSize, lowerLevel, upperLevel); + histEvenInc(shist, (data >> 16) & 0xFFU, binSize, lowerLevel, upperLevel); + histEvenInc(shist, (data >> 24) & 0xFFU, binSize, lowerLevel, upperLevel); + } + + if (cols % 4 != 0 && threadIdx.x == 0) + { + for (int x = cols_4 * 4; x < cols; ++x) + { + const uchar data = rowPtr[x]; + histEvenInc(shist, data, binSize, lowerLevel, upperLevel); + } + } + } + + __syncthreads(); + + if (tid < binCount) + { + const int histVal = shist[tid]; + + if (histVal > 0) + ::atomicAdd(hist + tid, histVal); + } + } + + void histEven8u(PtrStepSzb src, int* hist, int binCount, int lowerLevel, int upperLevel, cudaStream_t stream) + { + const dim3 block(32, 8); + const dim3 grid(divUp(src.rows, block.y)); + + const int binSize = divUp(upperLevel - lowerLevel, binCount); + + const size_t smem_size = binCount * sizeof(int); + + histEven8u<<>>(src.data, src.step, src.rows, src.cols, hist, binCount, binSize, lowerLevel, upperLevel); + cudaSafeCall( cudaGetLastError() ); + + if (stream == 0) + cudaSafeCall( cudaDeviceSynchronize() ); + } +} + +///////////////////////////////////////////////////////////////////////// + namespace hist { __constant__ int c_lut[256]; diff --git a/modules/gpu/src/cuda/imgproc.cu b/modules/gpu/src/cuda/imgproc.cu index b23e0a6653..067dfaf640 100644 --- a/modules/gpu/src/cuda/imgproc.cu +++ b/modules/gpu/src/cuda/imgproc.cu @@ -619,6 +619,7 @@ namespace cv { namespace gpu { namespace device ////////////////////////////////////////////////////////////////////////// // mulSpectrums +#ifdef HAVE_CUFFT __global__ void mulSpectrumsKernel(const PtrStep a, const PtrStep b, PtrStepSz c) { const int x = blockIdx.x * blockDim.x + threadIdx.x; @@ -642,11 +643,13 @@ namespace cv { namespace gpu { namespace device if (stream == 0) cudaSafeCall( cudaDeviceSynchronize() ); } +#endif ////////////////////////////////////////////////////////////////////////// // mulSpectrums_CONJ +#ifdef HAVE_CUFFT __global__ void mulSpectrumsKernel_CONJ(const PtrStep a, const PtrStep b, PtrStepSz c) { const int x = blockIdx.x * blockDim.x + threadIdx.x; @@ -670,11 +673,13 @@ namespace cv { namespace gpu { namespace device if (stream == 0) cudaSafeCall( cudaDeviceSynchronize() ); } +#endif ////////////////////////////////////////////////////////////////////////// // mulAndScaleSpectrums +#ifdef HAVE_CUFFT __global__ void mulAndScaleSpectrumsKernel(const PtrStep a, const PtrStep b, float scale, PtrStepSz c) { const int x = blockIdx.x * blockDim.x + threadIdx.x; @@ -699,11 +704,13 @@ namespace cv { namespace gpu { namespace device if (stream) cudaSafeCall( cudaDeviceSynchronize() ); } +#endif ////////////////////////////////////////////////////////////////////////// // mulAndScaleSpectrums_CONJ +#ifdef HAVE_CUFFT __global__ void mulAndScaleSpectrumsKernel_CONJ(const PtrStep a, const PtrStep b, float scale, PtrStepSz c) { const int x = blockIdx.x * blockDim.x + threadIdx.x; @@ -728,6 +735,7 @@ namespace cv { namespace gpu { namespace device if (stream == 0) cudaSafeCall( cudaDeviceSynchronize() ); } +#endif ////////////////////////////////////////////////////////////////////////// // buildWarpMaps diff --git a/modules/gpu/src/cuda/safe_call.hpp b/modules/gpu/src/cuda/safe_call.hpp index 7fae710820..53d691f7cc 100644 --- a/modules/gpu/src/cuda/safe_call.hpp +++ b/modules/gpu/src/cuda/safe_call.hpp @@ -43,53 +43,94 @@ #ifndef __OPENCV_CUDA_SAFE_CALL_HPP__ #define __OPENCV_CUDA_SAFE_CALL_HPP__ +#include "cvconfig.h" + #include -#include -#include -#include "NCV.hpp" -#if defined(__GNUC__) - #define nppSafeCall(expr) ___nppSafeCall(expr, __FILE__, __LINE__, __func__) - #define ncvSafeCall(expr) ___ncvSafeCall(expr, __FILE__, __LINE__, __func__) - #define cufftSafeCall(expr) ___cufftSafeCall(expr, __FILE__, __LINE__, __func__) - #define cublasSafeCall(expr) ___cublasSafeCall(expr, __FILE__, __LINE__, __func__) -#else /* defined(__CUDACC__) || defined(__MSVC__) */ - #define nppSafeCall(expr) ___nppSafeCall(expr, __FILE__, __LINE__) - #define ncvSafeCall(expr) ___ncvSafeCall(expr, __FILE__, __LINE__) - #define cufftSafeCall(expr) ___cufftSafeCall(expr, __FILE__, __LINE__) - #define cublasSafeCall(expr) ___cublasSafeCall(expr, __FILE__, __LINE__) +#ifdef HAVE_CUFFT +# include #endif -namespace cv { namespace gpu -{ - void nppError(int err, const char *file, const int line, const char *func = ""); - void ncvError(int err, const char *file, const int line, const char *func = ""); +#ifdef HAVE_CUBLAS +# include +#endif + +#include "NCV.hpp" + +namespace cv { namespace gpu { + +void nppError(int err, const char *file, const int line, const char *func = ""); + +void ncvError(int err, const char *file, const int line, const char *func = ""); + +#ifdef HAVE_CUFFT void cufftError(int err, const char *file, const int line, const char *func = ""); +#endif + +#ifdef HAVE_CUBLAS void cublasError(int err, const char *file, const int line, const char *func = ""); +#endif + }} +// nppSafeCall + static inline void ___nppSafeCall(int err, const char *file, const int line, const char *func = "") { if (err < 0) cv::gpu::nppError(err, file, line, func); } +#if defined(__GNUC__) + #define nppSafeCall(expr) ___nppSafeCall(expr, __FILE__, __LINE__, __func__) +#else + #define nppSafeCall(expr) ___nppSafeCall(expr, __FILE__, __LINE__) +#endif + +// ncvSafeCall + static inline void ___ncvSafeCall(int err, const char *file, const int line, const char *func = "") { if (NCV_SUCCESS != err) cv::gpu::ncvError(err, file, line, func); } -static inline void ___cufftSafeCall(cufftResult_t err, const char *file, const int line, const char *func = "") -{ - if (CUFFT_SUCCESS != err) - cv::gpu::cufftError(err, file, line, func); -} +#if defined(__GNUC__) + #define ncvSafeCall(expr) ___ncvSafeCall(expr, __FILE__, __LINE__, __func__) +#else + #define ncvSafeCall(expr) ___ncvSafeCall(expr, __FILE__, __LINE__) +#endif -static inline void ___cublasSafeCall(cublasStatus_t err, const char *file, const int line, const char *func = "") -{ - if (CUBLAS_STATUS_SUCCESS != err) - cv::gpu::cublasError(err, file, line, func); -} +// cufftSafeCall + +#ifdef HAVE_CUFFT + static inline void ___cufftSafeCall(cufftResult_t err, const char *file, const int line, const char *func = "") + { + if (CUFFT_SUCCESS != err) + cv::gpu::cufftError(err, file, line, func); + } + + #if defined(__GNUC__) + #define cufftSafeCall(expr) ___cufftSafeCall(expr, __FILE__, __LINE__, __func__) + #else + #define cufftSafeCall(expr) ___cufftSafeCall(expr, __FILE__, __LINE__) + #endif +#endif + +// cublasSafeCall + +#ifdef HAVE_CUBLAS + static inline void ___cublasSafeCall(cublasStatus_t err, const char *file, const int line, const char *func = "") + { + if (CUBLAS_STATUS_SUCCESS != err) + cv::gpu::cublasError(err, file, line, func); + } + + #if defined(__GNUC__) + #define cublasSafeCall(expr) ___cublasSafeCall(expr, __FILE__, __LINE__, __func__) + #else + #define cublasSafeCall(expr) ___cublasSafeCall(expr, __FILE__, __LINE__) + #endif +#endif #endif /* __OPENCV_CUDA_SAFE_CALL_HPP__ */ diff --git a/modules/gpu/src/error.cpp b/modules/gpu/src/error.cpp index 7f5d5f38d5..ff0cadb75f 100644 --- a/modules/gpu/src/error.cpp +++ b/modules/gpu/src/error.cpp @@ -224,6 +224,7 @@ namespace ////////////////////////////////////////////////////////////////////////// // CUFFT errors +#ifdef HAVE_CUFFT const ErrorEntry cufft_errors[] = { error_entry( CUFFT_INVALID_PLAN ), @@ -238,10 +239,12 @@ namespace }; const int cufft_error_num = sizeof(cufft_errors) / sizeof(cufft_errors[0]); +#endif ////////////////////////////////////////////////////////////////////////// // CUBLAS errors +#ifdef HAVE_CUBLAS const ErrorEntry cublas_errors[] = { error_entry( CUBLAS_STATUS_SUCCESS ), @@ -255,6 +258,7 @@ namespace }; const int cublas_error_num = sizeof(cublas_errors) / sizeof(cublas_errors[0]); +#endif } namespace cv @@ -273,17 +277,21 @@ namespace cv cv::gpu::error(msg.c_str(), file, line, func); } +#ifdef HAVE_CUFFT void cufftError(int code, const char *file, const int line, const char *func) { string msg = getErrorString(code, cufft_errors, cufft_error_num); cv::gpu::error(msg.c_str(), file, line, func); } +#endif +#ifdef HAVE_CUBLAS void cublasError(int code, const char *file, const int line, const char *func) { string msg = getErrorString(code, cublas_errors, cublas_error_num); cv::gpu::error(msg.c_str(), file, line, func); } +#endif } } diff --git a/modules/gpu/src/imgproc.cpp b/modules/gpu/src/imgproc.cpp index 97c7c766c0..1904b6aad6 100644 --- a/modules/gpu/src/imgproc.cpp +++ b/modules/gpu/src/imgproc.cpp @@ -889,6 +889,21 @@ void cv::gpu::histEven(const GpuMat& src, GpuMat& hist, int histSize, int lowerL histEven(src, hist, buf, histSize, lowerLevel, upperLevel, stream); } +namespace hist +{ + void histEven8u(PtrStepSzb src, int* hist, int binCount, int lowerLevel, int upperLevel, cudaStream_t stream); +} + +namespace +{ + void histEven8u(const GpuMat& src, GpuMat& hist, int histSize, int lowerLevel, int upperLevel, cudaStream_t stream) + { + hist.create(1, histSize, CV_32S); + cudaSafeCall( cudaMemsetAsync(hist.data, 0, histSize * sizeof(int), stream) ); + hist::histEven8u(src, hist.ptr(), histSize, lowerLevel, upperLevel, stream); + } +} + void cv::gpu::histEven(const GpuMat& src, GpuMat& hist, GpuMat& buf, int histSize, int lowerLevel, int upperLevel, Stream& stream) { CV_Assert(src.type() == CV_8UC1 || src.type() == CV_16UC1 || src.type() == CV_16SC1 ); @@ -902,6 +917,12 @@ void cv::gpu::histEven(const GpuMat& src, GpuMat& hist, GpuMat& buf, int histSiz NppHistogramEvenC1::hist }; + if (src.depth() == CV_8U && deviceSupports(FEATURE_SET_COMPUTE_30)) + { + histEven8u(src, hist, histSize, lowerLevel, upperLevel, StreamAccessor::getStream(stream)); + return; + } + hist_callers[src.depth()](src, hist, buf, histSize, lowerLevel, upperLevel, StreamAccessor::getStream(stream)); } @@ -1136,6 +1157,8 @@ void cv::gpu::cornerMinEigenVal(const GpuMat& src, GpuMat& dst, GpuMat& Dx, GpuM ////////////////////////////////////////////////////////////////////////////// // mulSpectrums +#ifdef HAVE_CUFFT + namespace cv { namespace gpu { namespace device { namespace imgproc @@ -1146,9 +1169,20 @@ namespace cv { namespace gpu { namespace device } }}} +#endif + void cv::gpu::mulSpectrums(const GpuMat& a, const GpuMat& b, GpuMat& c, int flags, bool conjB, Stream& stream) { - (void)flags; +#ifndef HAVE_CUFFT + (void) a; + (void) b; + (void) c; + (void) flags; + (void) conjB; + (void) stream; + throw_nogpu(); +#else + (void) flags; using namespace ::cv::gpu::device::imgproc; typedef void (*Caller)(const PtrStep, const PtrStep, PtrStepSz, cudaStream_t stream); @@ -1162,11 +1196,14 @@ void cv::gpu::mulSpectrums(const GpuMat& a, const GpuMat& b, GpuMat& c, int flag Caller caller = callers[(int)conjB]; caller(a, b, c, StreamAccessor::getStream(stream)); +#endif } ////////////////////////////////////////////////////////////////////////////// // mulAndScaleSpectrums +#ifdef HAVE_CUFFT + namespace cv { namespace gpu { namespace device { namespace imgproc @@ -1177,8 +1214,20 @@ namespace cv { namespace gpu { namespace device } }}} +#endif + void cv::gpu::mulAndScaleSpectrums(const GpuMat& a, const GpuMat& b, GpuMat& c, int flags, float scale, bool conjB, Stream& stream) { +#ifndef HAVE_CUFFT + (void) a; + (void) b; + (void) c; + (void) flags; + (void) scale; + (void) conjB; + (void) stream; + throw_nogpu(); +#else (void)flags; using namespace ::cv::gpu::device::imgproc; @@ -1192,6 +1241,7 @@ void cv::gpu::mulAndScaleSpectrums(const GpuMat& a, const GpuMat& b, GpuMat& c, Caller caller = callers[(int)conjB]; caller(a, b, scale, c, StreamAccessor::getStream(stream)); +#endif } ////////////////////////////////////////////////////////////////////////////// diff --git a/modules/gpu/src/precomp.hpp b/modules/gpu/src/precomp.hpp index 06d5386405..d3a4467ea1 100644 --- a/modules/gpu/src/precomp.hpp +++ b/modules/gpu/src/precomp.hpp @@ -47,9 +47,7 @@ #pragma warning( disable: 4251 4710 4711 4514 4996 ) #endif -#ifdef HAVE_CVCONFIG_H #include "cvconfig.h" -#endif #include #include diff --git a/modules/gpu/test/test_imgproc.cpp b/modules/gpu/test/test_imgproc.cpp index e424763bf6..811d1294cf 100644 --- a/modules/gpu/test/test_imgproc.cpp +++ b/modules/gpu/test/test_imgproc.cpp @@ -86,13 +86,16 @@ INSTANTIATE_TEST_CASE_P(GPU_ImgProc, Integral, testing::Combine( /////////////////////////////////////////////////////////////////////////////////////////////////////// // HistEven -struct HistEven : testing::TestWithParam +PARAM_TEST_CASE(HistEven, cv::gpu::DeviceInfo, cv::Size) { cv::gpu::DeviceInfo devInfo; + cv::Size size; + virtual void SetUp() { - devInfo = GetParam(); + devInfo = GET_PARAM(0); + size = GET_PARAM(1); cv::gpu::setDevice(devInfo.deviceID()); } @@ -100,57 +103,34 @@ struct HistEven : testing::TestWithParam GPU_TEST_P(HistEven, Accuracy) { - cv::Mat img = readImage("stereobm/aloe-L.png"); - ASSERT_FALSE(img.empty()); - - cv::Mat hsv; - cv::cvtColor(img, hsv, CV_BGR2HSV); + cv::Mat src = randomMat(size, CV_8UC1); int hbins = 30; - float hranges[] = {0.0f, 180.0f}; - - std::vector srcs; - cv::gpu::split(loadMat(hsv), srcs); + float hranges[] = {50.0f, 200.0f}; cv::gpu::GpuMat hist; - cv::gpu::histEven(srcs[0], hist, hbins, (int)hranges[0], (int)hranges[1]); + cv::gpu::histEven(loadMat(src), hist, hbins, (int) hranges[0], (int) hranges[1]); + + cv::Mat hist_gold; - cv::MatND histnd; int histSize[] = {hbins}; const float* ranges[] = {hranges}; int channels[] = {0}; - cv::calcHist(&hsv, 1, channels, cv::Mat(), histnd, 1, histSize, ranges); + cv::calcHist(&src, 1, channels, cv::Mat(), hist_gold, 1, histSize, ranges); - cv::Mat hist_gold = histnd; hist_gold = hist_gold.t(); hist_gold.convertTo(hist_gold, CV_32S); EXPECT_MAT_NEAR(hist_gold, hist, 0.0); } -INSTANTIATE_TEST_CASE_P(GPU_ImgProc, HistEven, ALL_DEVICES); +INSTANTIATE_TEST_CASE_P(GPU_ImgProc, HistEven, testing::Combine( + ALL_DEVICES, + DIFFERENT_SIZES)); /////////////////////////////////////////////////////////////////////////////////////////////////////// // CalcHist -namespace -{ - void calcHistGold(const cv::Mat& src, cv::Mat& hist) - { - hist.create(1, 256, CV_32SC1); - hist.setTo(cv::Scalar::all(0)); - - int* hist_row = hist.ptr(); - for (int y = 0; y < src.rows; ++y) - { - const uchar* src_row = src.ptr(y); - - for (int x = 0; x < src.cols; ++x) - ++hist_row[src_row[x]]; - } - } -} - PARAM_TEST_CASE(CalcHist, cv::gpu::DeviceInfo, cv::Size) { cv::gpu::DeviceInfo devInfo; @@ -174,7 +154,16 @@ GPU_TEST_P(CalcHist, Accuracy) cv::gpu::calcHist(loadMat(src), hist); cv::Mat hist_gold; - calcHistGold(src, hist_gold); + + const int hbins = 256; + const float hranges[] = {0.0f, 256.0f}; + const int histSize[] = {hbins}; + const float* ranges[] = {hranges}; + const int channels[] = {0}; + + cv::calcHist(&src, 1, channels, cv::Mat(), hist_gold, 1, histSize, ranges); + hist_gold = hist_gold.reshape(1, 1); + hist_gold.convertTo(hist_gold, CV_32S); EXPECT_MAT_NEAR(hist_gold, hist, 0.0); } diff --git a/modules/gpu/test/test_precomp.cpp b/modules/gpu/test/test_precomp.cpp deleted file mode 100644 index 0fb6521809..0000000000 --- a/modules/gpu/test/test_precomp.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "test_precomp.hpp" diff --git a/modules/highgui/CMakeLists.txt b/modules/highgui/CMakeLists.txt index 2b0a232099..3d7667b65f 100644 --- a/modules/highgui/CMakeLists.txt +++ b/modules/highgui/CMakeLists.txt @@ -9,38 +9,33 @@ ocv_add_module(highgui opencv_imgproc OPTIONAL opencv_androidcamera) ocv_clear_vars(GRFMT_LIBS) -if(WITH_PNG OR WITH_TIFF OR WITH_OPENEXR) +if(HAVE_PNG OR HAVE_TIFF OR HAVE_OPENEXR) ocv_include_directories(${ZLIB_INCLUDE_DIR}) list(APPEND GRFMT_LIBS ${ZLIB_LIBRARIES}) endif() -if(WITH_JPEG) - add_definitions(-DHAVE_JPEG) +if(HAVE_JPEG) ocv_include_directories(${JPEG_INCLUDE_DIR}) list(APPEND GRFMT_LIBS ${JPEG_LIBRARIES}) endif() -if(WITH_PNG) - add_definitions(-DHAVE_PNG) +if(HAVE_PNG) add_definitions(${PNG_DEFINITIONS}) ocv_include_directories(${PNG_INCLUDE_DIR}) list(APPEND GRFMT_LIBS ${PNG_LIBRARIES}) endif() -if(WITH_TIFF) - add_definitions(-DHAVE_TIFF) +if(HAVE_TIFF) ocv_include_directories(${TIFF_INCLUDE_DIR}) list(APPEND GRFMT_LIBS ${TIFF_LIBRARIES}) endif() -if(WITH_JASPER) - add_definitions(-DHAVE_JASPER) +if(HAVE_JASPER) ocv_include_directories(${JASPER_INCLUDE_DIR}) list(APPEND GRFMT_LIBS ${JASPER_LIBRARIES}) endif() -if(WITH_OPENEXR) - add_definitions(-DHAVE_OPENEXR) +if(HAVE_OPENEXR) include_directories(SYSTEM ${OPENEXR_INCLUDE_PATHS}) list(APPEND GRFMT_LIBS ${OPENEXR_LIBRARIES}) endif() @@ -63,7 +58,6 @@ set(highgui_srcs src/cap_images.cpp src/cap_ffmpeg.cpp src/loadsave.cpp - src/precomp.cpp src/utils.cpp src/window.cpp ) @@ -108,16 +102,12 @@ elseif(HAVE_WIN32UI) list(APPEND highgui_srcs src/window_w32.cpp) elseif(HAVE_GTK) list(APPEND highgui_srcs src/window_gtk.cpp) -elseif(APPLE) - if(WITH_CARBON) - add_definitions(-DHAVE_CARBON=1) - list(APPEND highgui_srcs src/window_carbon.cpp) - list(APPEND HIGHGUI_LIBRARIES "-framework Carbon" "-framework QuickTime") - elseif(NOT IOS) - add_definitions(-DHAVE_COCOA=1) - list(APPEND highgui_srcs src/window_cocoa.mm) - list(APPEND HIGHGUI_LIBRARIES "-framework Cocoa") - endif() +elseif(HAVE_CARBON) + list(APPEND highgui_srcs src/window_carbon.cpp) + list(APPEND HIGHGUI_LIBRARIES "-framework Carbon" "-framework QuickTime") +elseif(HAVE_COCOA) + list(APPEND highgui_srcs src/window_cocoa.mm) + list(APPEND HIGHGUI_LIBRARIES "-framework Cocoa") endif() if(WIN32 AND NOT ARM) @@ -197,6 +187,7 @@ endif(HAVE_FFMPEG) if(HAVE_PVAPI) add_definitions(-DHAVE_PVAPI) + add_definitions(${PVAPI_DEFINITIONS}) ocv_include_directories(${PVAPI_INCLUDE_PATH}) set(highgui_srcs src/cap_pvapi.cpp ${highgui_srcs}) list(APPEND HIGHGUI_LIBRARIES ${PVAPI_LIBRARY}) @@ -210,26 +201,21 @@ if(HAVE_GIGE_API) list(APPEND highgui_srcs src/cap_giganetix.cpp) endif(HAVE_GIGE_API) -if(WITH_IMAGEIO) - add_definitions(-DHAVE_IMAGEIO=1) - if(IOS) - list(APPEND HIGHGUI_LIBRARIES "-framework ImageIO") - endif() -endif(WITH_IMAGEIO) +if(HAVE_IMAGEIO AND IOS) + list(APPEND HIGHGUI_LIBRARIES "-framework ImageIO") +endif() -if(WITH_AVFOUNDATION) - add_definitions(-DHAVE_AVFOUNDATION=1) +if(HAVE_AVFOUNDATION) list(APPEND highgui_srcs src/cap_avfoundation.mm) list(APPEND HIGHGUI_LIBRARIES "-framework AVFoundation" "-framework QuartzCore") +endif() + +if(HAVE_QUICKTIME) + list(APPEND highgui_srcs src/cap_qt.cpp) + list(APPEND HIGHGUI_LIBRARIES "-framework Carbon" "-framework QuickTime" "-framework CoreFoundation" "-framework QuartzCore") elseif(APPLE) - add_definitions(-DHAVE_QUICKTIME=1) - if(WITH_QUICKTIME) - list(APPEND highgui_srcs src/cap_qt.cpp) - list(APPEND HIGHGUI_LIBRARIES "-framework Carbon" "-framework QuickTime" "-framework CoreFoundation" "-framework QuartzCore") - else() - list(APPEND highgui_srcs src/cap_qtkit.mm) - list(APPEND HIGHGUI_LIBRARIES "-framework QTKit" "-framework QuartzCore" "-framework AppKit") - endif() + list(APPEND highgui_srcs src/cap_qtkit.mm) + list(APPEND HIGHGUI_LIBRARIES "-framework QTKit" "-framework QuartzCore" "-framework AppKit") endif() if(IOS) diff --git a/modules/highgui/doc/reading_and_writing_images_and_video.rst b/modules/highgui/doc/reading_and_writing_images_and_video.rst index d473bb4923..811f3da06c 100644 --- a/modules/highgui/doc/reading_and_writing_images_and_video.rst +++ b/modules/highgui/doc/reading_and_writing_images_and_video.rst @@ -224,6 +224,15 @@ The class provides C++ API for capturing video from cameras or for reading video .. note:: In C API the black-box structure ``CvCapture`` is used instead of ``VideoCapture``. +.. note:: + + * A basic sample on using the VideoCapture interface can be found at opencv_source_code/samples/cpp/starter_video.cpp + * Another basic video processing sample can be found at opencv_source_code/samples/cpp/video_dmtx.cpp + + * (Python) A basic sample on using the VideoCapture interface can be found at opencv_source_code/samples/python2/video.py + * (Python) Another basic video processing sample can be found at opencv_source_code/samples/python2/video_dmtx.py + * (Python) A multi threaded video processing sample can be found at opencv_source_code/samples/python2/video_threaded.py + VideoCapture::VideoCapture ------------------------------ diff --git a/modules/highgui/doc/user_interface.rst b/modules/highgui/doc/user_interface.rst index def8451a2c..f287b77bad 100644 --- a/modules/highgui/doc/user_interface.rst +++ b/modules/highgui/doc/user_interface.rst @@ -33,6 +33,10 @@ The function ``createTrackbar`` creates a trackbar (a slider or range control) w Clicking the label of each trackbar enables editing the trackbar values manually. +.. note:: + + * An example of using the trackbar functionality can be found at opencv_source_code/samples/cpp/connected_components.cpp + getTrackbarPos ------------------ Returns the trackbar position. @@ -79,6 +83,7 @@ The function ``imshow`` displays an image in the specified window. If the window * If the image is 32-bit floating-point, the pixel values are multiplied by 255. That is, the value range [0,1] is mapped to [0,255]. +If window was created with OpenGL support, ``imshow`` also support :ocv:class:`ogl::Buffer` , :ocv:class:`ogl::Texture2D` and :ocv:class:`gpu::GpuMat` as input. namedWindow --------------- @@ -94,7 +99,13 @@ Creates a window. :param name: Name of the window in the window caption that may be used as a window identifier. - :param flags: Flags of the window. Currently the only supported flag is ``CV_WINDOW_AUTOSIZE`` . If this is set, the window size is automatically adjusted to fit the displayed image (see :ocv:func:`imshow` ), and you cannot change the window size manually. + :param flags: Flags of the window. The supported flags are: + + * **WINDOW_NORMAL** If this is set, the user can resize the window (no constraint). + + * **WINDOW_AUTOSIZE** If this is set, the window size is automatically adjusted to fit the displayed image (see :ocv:func:`imshow` ), and you cannot change the window size manually. + + * **WINDOW_OPENGL** If this is set, the window will be created with OpenGL support. The function ``namedWindow`` creates a window that can be used as a placeholder for images and trackbars. Created windows are referred to by their names. @@ -256,3 +267,31 @@ The function ``waitKey`` waits for a key event infinitely (when .. note:: The function only works if there is at least one HighGUI window created and the window is active. If there are several HighGUI windows, any of them can be active. + +setOpenGlDrawCallback +--------------------- +Set OpenGL render handler for the specified window. + +.. ocv:function:: void setOpenGlDrawCallback(const string& winname, OpenGlDrawCallback onOpenGlDraw, void* userdata = 0) + + :param winname: Window name + + :param onOpenGlDraw: Draw callback. + + :param userdata: The optional parameter passed to the callback. + +setOpenGlContext +---------------- +Sets the specified window as current OpenGL context. + +.. ocv:function:: void setOpenGlContext(const string& winname) + + :param winname: Window name + +updateWindow +------------ +Force window to redraw its context and call draw callback ( :ocv:func:`setOpenGlDrawCallback` ). + +.. ocv:function:: void updateWindow(const string& winname) + + :param winname: Window name diff --git a/modules/highgui/perf/perf_precomp.cpp b/modules/highgui/perf/perf_precomp.cpp deleted file mode 100644 index 8552ac3d42..0000000000 --- a/modules/highgui/perf/perf_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "perf_precomp.hpp" diff --git a/modules/highgui/src/cap.cpp b/modules/highgui/src/cap.cpp index cc92da3d0c..b5cdc5e9f9 100644 --- a/modules/highgui/src/cap.cpp +++ b/modules/highgui/src/cap.cpp @@ -220,8 +220,8 @@ CV_IMPL CvCapture * cvCreateCameraCapture (int index) return capture; break; #endif -#ifdef HAVE_VFW case CV_CAP_VFW: +#ifdef HAVE_VFW capture = cvCreateCameraCapture_VFW (index); if (capture) return capture; @@ -489,14 +489,14 @@ VideoCapture::~VideoCapture() bool VideoCapture::open(const string& filename) { - if (!isOpened()) + if (isOpened()) release(); cap = cvCreateFileCapture(filename.c_str()); return isOpened(); } bool VideoCapture::open(int device) { - if (!isOpened()) + if (isOpened()) release(); cap = cvCreateCameraCapture(device); return isOpened(); } diff --git a/modules/highgui/src/cap_dshow.cpp b/modules/highgui/src/cap_dshow.cpp index b7cfbd94b3..606e520129 100644 --- a/modules/highgui/src/cap_dshow.cpp +++ b/modules/highgui/src/cap_dshow.cpp @@ -3164,18 +3164,18 @@ void CvCaptureCAM_DShow::close() // Initialize camera input bool CvCaptureCAM_DShow::open( int _index ) { - int try_index = _index; int devices = 0; close(); devices = VI.listDevices(true); if (devices == 0) return false; - try_index = try_index < 0 ? 0 : (try_index > devices-1 ? devices-1 : try_index); - VI.setupDevice(try_index); - if( !VI.isDeviceSetup(try_index) ) + if (_index < 0 || _index > devices-1) return false; - index = try_index; + VI.setupDevice(_index); + if( !VI.isDeviceSetup(_index) ) + return false; + index = _index; return true; } diff --git a/modules/highgui/src/cap_ffmpeg_impl.hpp b/modules/highgui/src/cap_ffmpeg_impl.hpp index d494948f96..84222ada26 100644 --- a/modules/highgui/src/cap_ffmpeg_impl.hpp +++ b/modules/highgui/src/cap_ffmpeg_impl.hpp @@ -1362,8 +1362,6 @@ bool CvVideoWriter_FFMPEG::writeFrame( const unsigned char* data, int step, int /// close video output stream and free associated memory void CvVideoWriter_FFMPEG::close() { - unsigned i; - // nothing to do if already released if ( !picture ) return; @@ -1419,13 +1417,6 @@ void CvVideoWriter_FFMPEG::close() av_free(outbuf); - /* free the streams */ - for(i = 0; i < oc->nb_streams; i++) - { - av_freep(&oc->streams[i]->codec); - av_freep(&oc->streams[i]); - } - if (!(fmt->flags & AVFMT_NOFILE)) { /* close the output file */ @@ -1443,7 +1434,7 @@ void CvVideoWriter_FFMPEG::close() } /* free the stream */ - av_free(oc); + avformat_free_context(oc); if( temp_image.data ) { diff --git a/modules/highgui/src/cap_msmf.cpp b/modules/highgui/src/cap_msmf.cpp index 09f65b7e87..76b9a215c5 100644 --- a/modules/highgui/src/cap_msmf.cpp +++ b/modules/highgui/src/cap_msmf.cpp @@ -2124,7 +2124,7 @@ long videoDevices::initDevices(IMFAttributes *pAttributes) return hr; } -size_t videoDevices::getCount() +unsigned int videoDevices::getCount() { return vds_Devices.size(); } diff --git a/modules/highgui/src/cap_qtkit.mm b/modules/highgui/src/cap_qtkit.mm index 207f01b525..c7afffa075 100644 --- a/modules/highgui/src/cap_qtkit.mm +++ b/modules/highgui/src/cap_qtkit.mm @@ -277,8 +277,11 @@ bool CvCaptureCAM::grabFrame(double timeOut) { double sleepTime = 0.005; double total = 0; - while (![capture updateImage] && (total += sleepTime)<=timeOut) - usleep((int)(sleepTime*1000)); + NSDate *loopUntil = [NSDate dateWithTimeIntervalSinceNow:sleepTime]; + while (![capture updateImage] && (total += sleepTime)<=timeOut && + [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode + beforeDate:loopUntil]) + loopUntil = [NSDate dateWithTimeIntervalSinceNow:sleepTime]; [localpool drain]; diff --git a/modules/highgui/src/cap_ximea.cpp b/modules/highgui/src/cap_ximea.cpp index 5acf2c09d1..98279e05b5 100644 --- a/modules/highgui/src/cap_ximea.cpp +++ b/modules/highgui/src/cap_ximea.cpp @@ -52,6 +52,8 @@ void CvCaptureCAM_XIMEA::init() { xiGetNumberDevices( &numDevices); hmv = NULL; + frame = NULL; + timeout = 0; memset(&image, 0, sizeof(XI_IMG)); } @@ -60,6 +62,8 @@ void CvCaptureCAM_XIMEA::init() // Initialize camera input bool CvCaptureCAM_XIMEA::open( int wIndex ) { +#define HandleXiResult(res) if (res!=XI_OK) goto error; + int mvret = XI_OK; if(numDevices == 0) @@ -73,26 +77,42 @@ bool CvCaptureCAM_XIMEA::open( int wIndex ) // always use auto exposure/gain mvret = xiSetParamInt( hmv, XI_PRM_AEAG, 1); - if(mvret != XI_OK) goto error; - - // always use auto white ballance - mvret = xiSetParamInt( hmv, XI_PRM_AUTO_WB, 1); - if(mvret != XI_OK) goto error; - - // default image format RGB24 - mvret = xiSetParamInt( hmv, XI_PRM_IMAGE_DATA_FORMAT, XI_RGB24); - if(mvret != XI_OK) goto error; + HandleXiResult(mvret); int width = 0; mvret = xiGetParamInt( hmv, XI_PRM_WIDTH, &width); - if(mvret != XI_OK) goto error; + HandleXiResult(mvret); int height = 0; mvret = xiGetParamInt( hmv, XI_PRM_HEIGHT, &height); - if(mvret != XI_OK) goto error; + HandleXiResult(mvret); + + int isColor = 0; + mvret = xiGetParamInt(hmv, XI_PRM_IMAGE_IS_COLOR, &isColor); + HandleXiResult(mvret); + + if(isColor) // for color cameras + { + // default image format RGB24 + mvret = xiSetParamInt( hmv, XI_PRM_IMAGE_DATA_FORMAT, XI_RGB24); + HandleXiResult(mvret); + + // always use auto white ballance for color cameras + mvret = xiSetParamInt( hmv, XI_PRM_AUTO_WB, 1); + HandleXiResult(mvret); + + // allocate frame buffer for RGB24 image + frame = cvCreateImage(cvSize( width, height), IPL_DEPTH_8U, 3); + } + else // for mono cameras + { + // default image format MONO8 + mvret = xiSetParamInt( hmv, XI_PRM_IMAGE_DATA_FORMAT, XI_MONO8); + HandleXiResult(mvret); - // allocate frame buffer for RGB24 image - frame = cvCreateImage(cvSize( width, height), IPL_DEPTH_8U, 3); + // allocate frame buffer for MONO8 image + frame = cvCreateImage(cvSize( width, height), IPL_DEPTH_8U, 1); + } //default capture timeout 10s timeout = 10000; @@ -118,9 +138,12 @@ void CvCaptureCAM_XIMEA::close() { if(frame) cvReleaseImage(&frame); - - xiStopAcquisition(hmv); - xiCloseDevice(hmv); + + if(hmv) + { + xiStopAcquisition(hmv); + xiCloseDevice(hmv); + } hmv = NULL; } diff --git a/modules/highgui/src/grfmt_jpeg2000.cpp b/modules/highgui/src/grfmt_jpeg2000.cpp index d9080e5d44..28818e30ca 100644 --- a/modules/highgui/src/grfmt_jpeg2000.cpp +++ b/modules/highgui/src/grfmt_jpeg2000.cpp @@ -53,12 +53,6 @@ #endif #endif -#undef PACKAGE -#undef PACKAGE_BUGREPORT -#undef PACKAGE_NAME -#undef PACKAGE_STRING -#undef PACKAGE_TARNAME -#undef PACKAGE_VERSION #undef VERSION #include diff --git a/modules/highgui/src/grfmt_png.cpp b/modules/highgui/src/grfmt_png.cpp index 9bb5d32be3..fb0fe6c391 100644 --- a/modules/highgui/src/grfmt_png.cpp +++ b/modules/highgui/src/grfmt_png.cpp @@ -51,7 +51,6 @@ and png2bmp sample from libpng distribution (Copyright (C) 1999-2001 MIYASAKA Masaru) \****************************************************************************************/ -#undef HAVE_UNISTD_H //to avoid redefinition #ifndef _LFS64_LARGEFILE # define _LFS64_LARGEFILE 0 #endif diff --git a/modules/highgui/src/precomp.cpp b/modules/highgui/src/precomp.cpp deleted file mode 100644 index d6f6e18f74..0000000000 --- a/modules/highgui/src/precomp.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/*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 "precomp.hpp" - diff --git a/modules/highgui/test/test_precomp.cpp b/modules/highgui/test/test_precomp.cpp deleted file mode 100644 index 5956e13e3e..0000000000 --- a/modules/highgui/test/test_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "test_precomp.hpp" diff --git a/modules/highgui/test/test_precomp.hpp b/modules/highgui/test/test_precomp.hpp index be06c0643a..5e030810fa 100644 --- a/modules/highgui/test/test_precomp.hpp +++ b/modules/highgui/test/test_precomp.hpp @@ -9,9 +9,7 @@ #ifndef __OPENCV_TEST_PRECOMP_HPP__ #define __OPENCV_TEST_PRECOMP_HPP__ -#ifdef HAVE_CVCONFIG_H # include "cvconfig.h" -#endif #include "opencv2/ts/ts.hpp" #include "opencv2/imgproc/imgproc.hpp" diff --git a/modules/imgproc/doc/feature_detection.rst b/modules/imgproc/doc/feature_detection.rst index df1a193076..8218ef24b1 100644 --- a/modules/imgproc/doc/feature_detection.rst +++ b/modules/imgproc/doc/feature_detection.rst @@ -32,7 +32,11 @@ Finds edges in an image using the [Canny86]_ algorithm. The function finds edges in the input image ``image`` and marks them in the output map ``edges`` using the Canny algorithm. The smallest value between ``threshold1`` and ``threshold2`` is used for edge linking. The largest value is used to find initial segments of strong edges. See http://en.wikipedia.org/wiki/Canny_edge_detector +.. note:: + * An example on using the canny edge detector can be found at opencv_source_code/samples/cpp/edge.cpp + + * (Python) An example on using the canny edge detector can be found at opencv_source_code/samples/cpp/edge.py cornerEigenValsAndVecs ---------------------- @@ -85,7 +89,9 @@ The output of the function can be used for robust edge or corner detection. :ocv:func:`cornerHarris`, :ocv:func:`preCornerDetect` +.. note:: + * (Python) An example on how to use eigenvectors and eigenvalues to estimate image texture flow direction can be found at opencv_source_code/samples/python2/texture_flow.py cornerHarris ------------ @@ -356,6 +362,9 @@ Example: :: :ocv:func:`fitEllipse`, :ocv:func:`minEnclosingCircle` +.. note:: + + * An example using the Hough circle detector can be found at opencv_source_code/samples/cpp/houghcircles.cpp HoughLines ---------- @@ -412,6 +421,10 @@ Finds lines in a binary image using the standard Hough transform. The function implements the standard or standard multi-scale Hough transform algorithm for line detection. See http://homepages.inf.ed.ac.uk/rbf/HIPR2/hough.htm for a good explanation of Hough transform. See also the example in :ocv:func:`HoughLinesP` description. +.. note:: + + * An example using the Hough line detector can be found at opencv_source_code/samples/cpp/houghlines.cpp + HoughLinesP ----------- Finds line segments in a binary image using the probabilistic Hough transform. diff --git a/modules/imgproc/doc/filtering.rst b/modules/imgproc/doc/filtering.rst index 0b1f9a34e4..73df71e6bd 100755 --- a/modules/imgproc/doc/filtering.rst +++ b/modules/imgproc/doc/filtering.rst @@ -22,6 +22,10 @@ OpenCV enables you to specify the extrapolation method. For details, see the fun * BORDER_CONSTANT: iiiiii|abcdefgh|iiiiiii with some specified 'i' */ +.. note:: + + * (Python) A complete example illustrating different morphological operations like erode/dilate, open/close, blackhat/tophat ... can be found at opencv_source_code/samples/python2/morphology.py + BaseColumnFilter ---------------- .. ocv:class:: BaseColumnFilter @@ -868,6 +872,9 @@ The function supports the in-place mode. Dilation can be applied several ( ``ite :ocv:func:`morphologyEx`, :ocv:func:`createMorphologyFilter` +.. note:: + + * An example using the morphological dilate operation can be found at opencv_source_code/samples/cpp/morphology2.cpp erode ----- @@ -908,7 +915,9 @@ The function supports the in-place mode. Erosion can be applied several ( ``iter :ocv:func:`morphologyEx`, :ocv:func:`createMorphologyFilter` +.. note:: + * An example using the morphological erode operation can be found at opencv_source_code/samples/cpp/morphology2.cpp filter2D -------- @@ -1245,6 +1254,9 @@ Any of the operations can be done in-place. In case of multi-channel images, eac :ocv:func:`erode`, :ocv:func:`createMorphologyFilter` +.. note:: + + * An example using the morphologyEx function for the morphological opening and closing operations can be found at opencv_source_code/samples/cpp/morphology2.cpp Laplacian --------- @@ -1290,7 +1302,9 @@ This is done when ``ksize > 1`` . When ``ksize == 1`` , the Laplacian is compute :ocv:func:`Sobel`, :ocv:func:`Scharr` +.. note:: + * An example using the Laplace transformation for edge detection can be found at opencv_source_code/samples/cpp/laplace.cpp pyrDown ------- @@ -1351,6 +1365,10 @@ Upsamples an image and then blurs it. The function performs the upsampling step of the Gaussian pyramid construction, though it can actually be used to construct the Laplacian pyramid. First, it upsamples the source image by injecting even zero rows and columns and then convolves the result with the same kernel as in :ocv:func:`pyrDown` multiplied by 4. +.. note:: + + * (Python) An example of Laplacian Pyramid construction and merging can be found at opencv_source_code/samples/python2/lappyr.py + pyrMeanShiftFiltering --------------------- @@ -1400,6 +1418,9 @@ After the iterations over, the color components of the initial pixel (that is, t When ``maxLevel > 0``, the gaussian pyramid of ``maxLevel+1`` levels is built, and the above procedure is run on the smallest layer first. After that, the results are propagated to the larger layer and the iterations are run again only on those pixels where the layer colors differ by more than ``sr`` from the lower-resolution layer of the pyramid. That makes boundaries of color regions sharper. Note that the results will be actually different from the ones obtained by running the meanshift procedure on the whole original image (i.e. when ``maxLevel==0``). +.. note:: + + * An example using mean-shift image segmentation can be found at opencv_source_code/samples/cpp/meanshift_segmentation.cpp sepFilter2D ----------- @@ -1425,7 +1446,7 @@ Applies a separable linear filter to an image. :param kernelY: Coefficients for filtering each column. - :param anchor: Anchor position within the kernel. The default value :math:`(-1, 1)` means that the anchor is at the kernel center. + :param anchor: Anchor position within the kernel. The default value :math:`(-1,-1)` means that the anchor is at the kernel center. :param delta: Value added to the filtered results before storing them. diff --git a/modules/imgproc/doc/geometric_transformations.rst b/modules/imgproc/doc/geometric_transformations.rst index c48da01d7e..c3abdb7c4c 100644 --- a/modules/imgproc/doc/geometric_transformations.rst +++ b/modules/imgproc/doc/geometric_transformations.rst @@ -307,6 +307,9 @@ where The function emulates the human "foveal" vision and can be used for fast scale and rotation-invariant template matching, for object tracking and so forth. The function can not operate in-place. +.. note:: + + * An example using the geometric logpolar operation in 4 applications can be found at opencv_source_code/samples/cpp/logpolar_bsm.cpp remap ----- diff --git a/modules/imgproc/doc/histograms.rst b/modules/imgproc/doc/histograms.rst index f576d5d755..bf6c98fd6b 100644 --- a/modules/imgproc/doc/histograms.rst +++ b/modules/imgproc/doc/histograms.rst @@ -99,7 +99,12 @@ input arrays at the same location. The sample below shows how to compute a 2D Hu waitKey(); } +.. note:: + * An example for creating histograms of an image can be found at opencv_source_code/samples/cpp/demhist.cpp + + * (Python) An example for creating color histograms can be found at opencv_source/samples/python2/color_histogram.py + * (Python) An example illustrating RGB and grayscale histogram plotting can be found at opencv_source/samples/python2/hist.py calcBackProject diff --git a/modules/imgproc/doc/miscellaneous_transformations.rst b/modules/imgproc/doc/miscellaneous_transformations.rst index 9fd8df517a..ae728c28cd 100644 --- a/modules/imgproc/doc/miscellaneous_transformations.rst +++ b/modules/imgproc/doc/miscellaneous_transformations.rst @@ -481,6 +481,12 @@ In this mode, the complexity is still linear. That is, the function provides a very fast way to compute the Voronoi diagram for a binary image. Currently, the second variant can use only the approximate distance transform algorithm, i.e. ``maskSize=CV_DIST_MASK_PRECISE`` is not supported yet. +.. note:: + + * An example on using the distance transform can be found at opencv_source_code/samples/cpp/distrans.cpp + + * (Python) An example on using the distance transform can be found at opencv_source/samples/python2/distrans.py + floodFill --------- Fills a connected component with the given color. @@ -580,11 +586,15 @@ where * Color/brightness of the seed point in case of a fixed range. -Use these functions to either mark a connected component with the specified color in-place, or build a mask and then extract the contour, or copy the region to another image, and so on. Various modes of the function are demonstrated in the ``floodfill.cpp`` sample. +Use these functions to either mark a connected component with the specified color in-place, or build a mask and then extract the contour, or copy the region to another image, and so on. .. seealso:: :ocv:func:`findContours` +.. note:: + * An example using the FloodFill technique can be found at opencv_source_code/samples/cpp/ffilldemo.cpp + + * (Python) An example using the FloodFill technique can be found at opencv_source_code/samples/python2/floodfill.cpp integral -------- @@ -748,6 +758,12 @@ Visual demonstration and usage example of the function can be found in the OpenC .. seealso:: :ocv:func:`findContours` +.. note:: + + * An example using the watershed algorithm can be found at opencv_source_code/samples/cpp/watershed.cpp + + * (Python) An example using the watershed algorithm can be found at opencv_source_code/samples/python2/watershed.py + grabCut ------- Runs the GrabCut algorithm. @@ -794,3 +810,9 @@ See the sample ``grabcut.cpp`` to learn how to use the function. .. [Meyer92] Meyer, F. *Color Image Segmentation*, ICIP92, 1992 .. [Telea04] Alexandru Telea, *An Image Inpainting Technique Based on the Fast Marching Method*. Journal of Graphics, GPU, and Game Tools 9 1, pp 23-34 (2004) + +.. note:: + + * An example using the GrabCut algorithm can be found at opencv_source_code/samples/cpp/grabcut.cpp + + * (Python) An example using the GrabCut algorithm can be found at opencv_source_code/samples/python2/grabcut.py \ No newline at end of file diff --git a/modules/imgproc/doc/object_detection.rst b/modules/imgproc/doc/object_detection.rst index c6231a05e0..ab4db330e9 100644 --- a/modules/imgproc/doc/object_detection.rst +++ b/modules/imgproc/doc/object_detection.rst @@ -74,3 +74,6 @@ image patch: After the function finishes the comparison, the best matches can be found as global minimums (when ``CV_TM_SQDIFF`` was used) or maximums (when ``CV_TM_CCORR`` or ``CV_TM_CCOEFF`` was used) using the :ocv:func:`minMaxLoc` function. In case of a color image, template summation in the numerator and each sum in the denominator is done over all of the channels and separate mean values are used for each channel. That is, the function can take a color template and a color image. The result will still be a single-channel image, which is easier to analyze. +.. note:: + + * (Python) An example on how to match mouse selected regions in an image can be found at opencv_source_code/samples/python2/mouse_and_match.py \ No newline at end of file diff --git a/modules/imgproc/doc/structural_analysis_and_shape_descriptors.rst b/modules/imgproc/doc/structural_analysis_and_shape_descriptors.rst index 37b23510d2..f25cc5a7ee 100644 --- a/modules/imgproc/doc/structural_analysis_and_shape_descriptors.rst +++ b/modules/imgproc/doc/structural_analysis_and_shape_descriptors.rst @@ -166,6 +166,14 @@ The function retrieves contours from the binary image using the algorithm .. note:: If you use the new Python interface then the ``CV_`` prefix has to be omitted in contour retrieval mode and contour approximation method parameters (for example, use ``cv2.RETR_LIST`` and ``cv2.CHAIN_APPROX_NONE`` parameters). If you use the old Python interface then these parameters have the ``CV_`` prefix (for example, use ``cv.CV_RETR_LIST`` and ``cv.CV_CHAIN_APPROX_NONE``). +.. note:: + + * An example using the findContour functionality can be found at opencv_source_code/samples/cpp/contours2.cpp + * An example using findContours to clean up a background segmentation result at opencv_source_code/samples/cpp/segment_objects.cpp + + * (Python) An example using the findContour functionality can be found at opencv_source/samples/python2/contours.py + * (Python) An example of detecting squares in an image can be found at opencv_source/samples/python2/squares.py + drawContours ---------------- Draws contours outlines or filled contours. @@ -246,7 +254,12 @@ The function draws contour outlines in the image if waitKey(0); } +.. note:: + + * An example using the drawContour functionality can be found at opencv_source_code/samples/cpp/contours2.cpp + * An example using drawContours to clean up a background segmentation result at opencv_source_code/samples/cpp/segment_objects.cpp + * (Python) An example using the drawContour functionality can be found at opencv_source/samples/python2/contours.py approxPolyDP ---------------- @@ -417,6 +430,10 @@ The functions find the convex hull of a 2D point set using the Sklansky's algori that has *O(N logN)* complexity in the current implementation. See the OpenCV sample ``convexhull.cpp`` that demonstrates the usage of different function variants. +.. note:: + + * An example using the convexHull functionality can be found at opencv_source_code/samples/cpp/convexhull.cpp + convexityDefects ---------------- @@ -473,6 +490,10 @@ Fits an ellipse around a set of 2D points. The function calculates the ellipse that fits (in a least-squares sense) a set of 2D points best of all. It returns the rotated rectangle in which the ellipse is inscribed. The algorithm [Fitzgibbon95]_ is used. +.. note:: + + * An example using the fitEllipse technique can be found at opencv_source_code/samples/cpp/fitellipse.cpp + fitLine ----------- Fits a line to a 2D or 3D point set. @@ -545,7 +566,9 @@ http://en.wikipedia.org/wiki/M-estimator :math:`w_i` are adjusted to be inversely proportional to :math:`\rho(r_i)` . +.. Sample code: + * (Python) An example of robust line fitting can be found at opencv_source_code/samples/python2/fitline.py isContourConvex ------------------- diff --git a/modules/imgproc/include/opencv2/imgproc/imgproc.hpp b/modules/imgproc/include/opencv2/imgproc/imgproc.hpp index 223ee32770..f51bbaab77 100644 --- a/modules/imgproc/include/opencv2/imgproc/imgproc.hpp +++ b/modules/imgproc/include/opencv2/imgproc/imgproc.hpp @@ -759,20 +759,20 @@ CV_EXPORTS double compareHist( const SparseMat& H1, const SparseMat& H2, int met //! normalizes the grayscale image brightness and contrast by normalizing its histogram CV_EXPORTS_W void equalizeHist( InputArray src, OutputArray dst ); -class CV_EXPORTS CLAHE : public Algorithm +class CV_EXPORTS_W CLAHE : public Algorithm { public: - virtual void apply(InputArray src, OutputArray dst) = 0; + CV_WRAP virtual void apply(InputArray src, OutputArray dst) = 0; - virtual void setClipLimit(double clipLimit) = 0; - virtual double getClipLimit() const = 0; + CV_WRAP virtual void setClipLimit(double clipLimit) = 0; + CV_WRAP virtual double getClipLimit() const = 0; - virtual void setTilesGridSize(Size tileGridSize) = 0; - virtual Size getTilesGridSize() const = 0; + CV_WRAP virtual void setTilesGridSize(Size tileGridSize) = 0; + CV_WRAP virtual Size getTilesGridSize() const = 0; - virtual void collectGarbage() = 0; + CV_WRAP virtual void collectGarbage() = 0; }; -CV_EXPORTS Ptr createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8)); +CV_EXPORTS_W Ptr createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8)); CV_EXPORTS float EMD( InputArray signature1, InputArray signature2, int distType, InputArray cost=noArray(), diff --git a/modules/imgproc/perf/perf_cvt_color.cpp b/modules/imgproc/perf/perf_cvt_color.cpp index 601beb8996..966a442f36 100644 --- a/modules/imgproc/perf/perf_cvt_color.cpp +++ b/modules/imgproc/perf/perf_cvt_color.cpp @@ -258,7 +258,7 @@ PERF_TEST_P(Size_CvtMode, cvtColor8u, declare.time(100); declare.in(src, WARMUP_RNG).out(dst); - int runs = sz.width <= 320 ? 70 : 5; + int runs = sz.width <= 320 ? 100 : 5; TEST_CYCLE_MULTIRUN(runs) cvtColor(src, dst, mode, ch.dcn); SANITY_CHECK(dst, 1); diff --git a/modules/imgproc/perf/perf_histogram.cpp b/modules/imgproc/perf/perf_histogram.cpp index 92db3be34a..1789470c20 100644 --- a/modules/imgproc/perf/perf_histogram.cpp +++ b/modules/imgproc/perf/perf_histogram.cpp @@ -28,14 +28,14 @@ PERF_TEST_P(Size_Source, calcHist1d, int dims = 1; int numberOfImages = 1; - const float r[] = {rangeLow, rangeHight}; - const float* ranges[] = {r}; + const float range[] = {rangeLow, rangeHight}; + const float* ranges[] = {range}; randu(source, rangeLow, rangeHight); declare.in(source); - TEST_CYCLE() + TEST_CYCLE_MULTIRUN(3) { calcHist(&source, numberOfImages, channels, Mat(), hist, dims, histSize, ranges); } diff --git a/modules/imgproc/perf/perf_precomp.cpp b/modules/imgproc/perf/perf_precomp.cpp deleted file mode 100644 index 8552ac3d42..0000000000 --- a/modules/imgproc/perf/perf_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "perf_precomp.hpp" diff --git a/modules/imgproc/perf/perf_resize.cpp b/modules/imgproc/perf/perf_resize.cpp index ea959a627a..7634644ea5 100644 --- a/modules/imgproc/perf/perf_resize.cpp +++ b/modules/imgproc/perf/perf_resize.cpp @@ -25,7 +25,7 @@ PERF_TEST_P(MatInfo_Size_Size, resizeUpLinear, cvtest::fillGradient(src); declare.in(src).out(dst); - TEST_CYCLE() resize(src, dst, to); + TEST_CYCLE_MULTIRUN(10) resize(src, dst, to); #ifdef ANDROID SANITY_CHECK(dst, 5); @@ -52,7 +52,7 @@ PERF_TEST_P(MatInfo_Size_Size, resizeDownLinear, cvtest::fillGradient(src); declare.in(src).out(dst); - TEST_CYCLE() resize(src, dst, to); + TEST_CYCLE_MULTIRUN(10) resize(src, dst, to); #ifdef ANDROID SANITY_CHECK(dst, 5); diff --git a/modules/imgproc/src/color.cpp b/modules/imgproc/src/color.cpp index 41ca2db9c0..fed7b73133 100644 --- a/modules/imgproc/src/color.cpp +++ b/modules/imgproc/src/color.cpp @@ -3457,7 +3457,7 @@ void cv::cvtColor( InputArray _src, OutputArray _dst, int code, int dcn ) case CV_BGR2YUV: case CV_RGB2YUV: { CV_Assert( scn == 3 || scn == 4 ); - bidx = code == CV_BGR2YCrCb || code == CV_RGB2YUV ? 0 : 2; + bidx = code == CV_BGR2YCrCb || code == CV_BGR2YUV ? 0 : 2; static const float yuv_f[] = { 0.114f, 0.587f, 0.299f, 0.492f, 0.877f }; static const int yuv_i[] = { B2Y, G2Y, R2Y, 8061, 14369 }; const float* coeffs_f = code == CV_BGR2YCrCb || code == CV_RGB2YCrCb ? 0 : yuv_f; @@ -3486,7 +3486,7 @@ void cv::cvtColor( InputArray _src, OutputArray _dst, int code, int dcn ) { if( dcn <= 0 ) dcn = 3; CV_Assert( scn == 3 && (dcn == 3 || dcn == 4) ); - bidx = code == CV_YCrCb2BGR || code == CV_YUV2RGB ? 0 : 2; + bidx = code == CV_YCrCb2BGR || code == CV_YUV2BGR ? 0 : 2; static const float yuv_f[] = { 2.032f, -0.395f, -0.581f, 1.140f }; static const int yuv_i[] = { 33292, -6472, -9519, 18678 }; const float* coeffs_f = code == CV_YCrCb2BGR || code == CV_YCrCb2RGB ? 0 : yuv_f; diff --git a/modules/imgproc/src/distransform.cpp b/modules/imgproc/src/distransform.cpp index d3e6f90242..a09b940627 100644 --- a/modules/imgproc/src/distransform.cpp +++ b/modules/imgproc/src/distransform.cpp @@ -779,6 +779,16 @@ cvDistTransform( const void* srcarr, void* dstarr, if( !labels ) { + #if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7) + if( maskSize == CV_DIST_MASK_5 ) + { + IppiSize roi = { src->cols, src->rows }; + if( ippiDistanceTransform_5x5_8u32f_C1R( + src->data.ptr, src->step, + dst->data.fl, dst->step, roi, _mask) >= 0 ) + return; + } + #endif CvDistTransFunc func = maskSize == CV_DIST_MASK_3 ? icvDistanceTransform_3x3_C1R : icvDistanceTransform_5x5_C1R; diff --git a/modules/imgproc/src/histogram.cpp b/modules/imgproc/src/histogram.cpp index bfcdee515f..18ff3436c1 100644 --- a/modules/imgproc/src/histogram.cpp +++ b/modules/imgproc/src/histogram.cpp @@ -270,6 +270,8 @@ public: } private: + calcHist1D_Invoker operator=(const calcHist1D_Invoker&); + T* p_[one]; uchar* mask_; int step_[one]; @@ -342,6 +344,8 @@ public: } private: + calcHist2D_Invoker operator=(const calcHist2D_Invoker&); + T* p_[two]; uchar* mask_; int step_[two]; @@ -432,6 +436,8 @@ public: } private: + calcHist3D_Invoker operator=(const calcHist3D_Invoker&); + T* p_[three]; uchar* mask_; int step_[three]; @@ -771,8 +777,7 @@ calcHist_( vector& _ptrs, const vector& _deltas, #ifdef HAVE_TBB calcHist1D_Invoker body(_ptrs, _deltas, hist, _uniranges, size[0], dims, imsize); parallel_for(BlockedRange(0, imsize.height), body); - return; -#endif +#else double a = uniranges[0], b = uniranges[1]; int sz = size[0], d0 = deltas[0], step0 = deltas[1]; const T* p0 = (const T*)ptrs[0]; @@ -795,14 +800,15 @@ calcHist_( vector& _ptrs, const vector& _deltas, ((int*)H)[idx]++; } } +#endif //HAVE_TBB + return; } else if( dims == 2 ) { #ifdef HAVE_TBB calcHist2D_Invoker body(_ptrs, _deltas, hist, _uniranges, size, dims, imsize, hstep); parallel_for(BlockedRange(0, imsize.height), body); - return; -#endif +#else double a0 = uniranges[0], b0 = uniranges[1], a1 = uniranges[2], b1 = uniranges[3]; int sz0 = size[0], sz1 = size[1]; int d0 = deltas[0], step0 = deltas[1], @@ -831,6 +837,8 @@ calcHist_( vector& _ptrs, const vector& _deltas, ((int*)(H + hstep0*idx0))[idx1]++; } } +#endif //HAVE_TBB + return; } else if( dims == 3 ) { diff --git a/modules/imgproc/src/morph.cpp b/modules/imgproc/src/morph.cpp index 53d2347ec4..fb901b7268 100644 --- a/modules/imgproc/src/morph.cpp +++ b/modules/imgproc/src/morph.cpp @@ -1136,11 +1136,151 @@ private: Scalar borderValue; }; +#if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7) +static bool IPPMorphReplicate(int op, const Mat &src, Mat &dst, const Mat &kernel, const Point &anchor) +{ + int type = src.type(); + const Mat* _src = &src; + Mat temp; + if( src.data == dst.data ) + { + src.copyTo(temp); + _src = &temp; + } + //DEPRECATED. Allocates and initializes morphology state structure for erosion or dilation operation. + typedef IppStatus (CV_STDCALL* ippiMorphologyInitAllocFunc)(int, const void*, IppiSize, IppiPoint, IppiMorphState **); + ippiMorphologyInitAllocFunc ippInitAllocFunc = + type == CV_8UC1 ? (ippiMorphologyInitAllocFunc)ippiMorphologyInitAlloc_8u_C1R : + type == CV_8UC3 ? (ippiMorphologyInitAllocFunc)ippiMorphologyInitAlloc_8u_C3R : + type == CV_8UC4 ? (ippiMorphologyInitAllocFunc)ippiMorphologyInitAlloc_8u_C4R : + type == CV_32FC1 ? (ippiMorphologyInitAllocFunc)ippiMorphologyInitAlloc_32f_C1R : + type == CV_32FC3 ? (ippiMorphologyInitAllocFunc)ippiMorphologyInitAlloc_32f_C3R : + type == CV_32FC4 ? (ippiMorphologyInitAllocFunc)ippiMorphologyInitAlloc_32f_C4R : + 0; + typedef IppStatus (CV_STDCALL* ippiMorphologyBorderReplicateFunc)(const void*, int, void *, int, IppiSize, IppiBorderType, IppiMorphState *); + ippiMorphologyBorderReplicateFunc ippFunc = 0; + switch( op ) + { + case MORPH_DILATE: + { + ippFunc = + type == CV_8UC1 ? (ippiMorphologyBorderReplicateFunc)ippiDilateBorderReplicate_8u_C1R : + type == CV_8UC3 ? (ippiMorphologyBorderReplicateFunc)ippiDilateBorderReplicate_8u_C3R : + type == CV_8UC4 ? (ippiMorphologyBorderReplicateFunc)ippiDilateBorderReplicate_8u_C4R : + type == CV_32FC1 ? (ippiMorphologyBorderReplicateFunc)ippiDilateBorderReplicate_32f_C1R : + type == CV_32FC3 ? (ippiMorphologyBorderReplicateFunc)ippiDilateBorderReplicate_32f_C3R : + type == CV_32FC4 ? (ippiMorphologyBorderReplicateFunc)ippiDilateBorderReplicate_32f_C4R : + 0; + break; + } + case MORPH_ERODE: + { + ippFunc = + type == CV_8UC1 ? (ippiMorphologyBorderReplicateFunc)ippiErodeBorderReplicate_8u_C1R : + type == CV_8UC3 ? (ippiMorphologyBorderReplicateFunc)ippiErodeBorderReplicate_8u_C3R : + type == CV_8UC4 ? (ippiMorphologyBorderReplicateFunc)ippiErodeBorderReplicate_8u_C4R : + type == CV_32FC1 ? (ippiMorphologyBorderReplicateFunc)ippiErodeBorderReplicate_32f_C1R : + type == CV_32FC3 ? (ippiMorphologyBorderReplicateFunc)ippiErodeBorderReplicate_32f_C3R : + type == CV_32FC4 ? (ippiMorphologyBorderReplicateFunc)ippiErodeBorderReplicate_32f_C4R : + 0; + break; + } + } + if( ippFunc && ippInitAllocFunc) + { + IppiMorphState* pState; + IppiSize roiSize = {src.cols, src.rows}; + IppiSize kernelSize = {kernel.cols, kernel.rows}; + IppiPoint point = {anchor.x, anchor.y}; + if( ippInitAllocFunc( roiSize.width, kernel.data, kernelSize, point, &pState ) < 0 ) + return false; + bool is_ok = ippFunc( _src->data, _src->step[0], dst.data, dst.step[0], roiSize, ippBorderRepl, pState ) >= 0; + ippiMorphologyFree(pState); + return is_ok; + } + return false; +} + +static bool IPPMorphOp(int op, InputArray _src, OutputArray _dst, + InputArray _kernel, + const Point &anchor, int iterations, + int borderType, const Scalar &borderValue) +{ + Mat src = _src.getMat(), kernel = _kernel.getMat(); + if( !( src.depth() == CV_8U || src.depth() == CV_32F ) || ( iterations > 1 ) || + !( borderType == cv::BORDER_REPLICATE || (borderType == cv::BORDER_CONSTANT && borderValue == morphologyDefaultBorderValue()) ) + || !( op == MORPH_DILATE || op == MORPH_ERODE) ) + return false; + if( borderType == cv::BORDER_CONSTANT ) + { + int x, y; + for( y = 0; y < kernel.rows; y++ ) + { + if( kernel.at(y, anchor.x) != 0 ) + continue; + for( x = 0; x < kernel.cols; x++ ) + { + if( kernel.at(y,x) != 0 ) + return false; + } + } + for( x = 0; y < kernel.cols; x++ ) + { + if( kernel.at(anchor.y, x) != 0 ) + continue; + for( y = 0; y < kernel.rows; y++ ) + { + if( kernel.at(y,x) != 0 ) + return false; + } + } + + } + Size ksize = kernel.data ? kernel.size() : Size(3,3); + Point normanchor = normalizeAnchor(anchor, ksize); + + CV_Assert( normanchor.inside(Rect(0, 0, ksize.width, ksize.height)) ); + + _dst.create( src.size(), src.type() ); + Mat dst = _dst.getMat(); + + if( iterations == 0 || kernel.rows*kernel.cols == 1 ) + { + src.copyTo(dst); + return true; + } + + if( !kernel.data ) + { + kernel = getStructuringElement(MORPH_RECT, Size(1+iterations*2,1+iterations*2)); + normanchor = Point(iterations, iterations); + iterations = 1; + } + else if( iterations > 1 && countNonZero(kernel) == kernel.rows*kernel.cols ) + { + normanchor = Point(normanchor.x*iterations, normanchor.y*iterations); + kernel = getStructuringElement(MORPH_RECT, + Size(ksize.width + (iterations-1)*(ksize.width-1), + ksize.height + (iterations-1)*(ksize.height-1)), + normanchor); + iterations = 1; + } + + return IPPMorphReplicate( op, src, dst, kernel, normanchor ); +} +#endif + static void morphOp( int op, InputArray _src, OutputArray _dst, InputArray _kernel, Point anchor, int iterations, int borderType, const Scalar& borderValue ) { + +#if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7) + if( IPPMorphOp(op, _src, _dst, _kernel, anchor, iterations, borderType, borderValue) ) + return; +#endif + Mat src = _src.getMat(), kernel = _kernel.getMat(); Size ksize = kernel.data ? kernel.size() : Size(3,3); anchor = normalizeAnchor(anchor, ksize); diff --git a/modules/imgproc/src/precomp.cpp b/modules/imgproc/src/precomp.cpp deleted file mode 100644 index 3e0ec42de9..0000000000 --- a/modules/imgproc/src/precomp.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/*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 "precomp.hpp" - -/* End of file. */ diff --git a/modules/imgproc/src/precomp.hpp b/modules/imgproc/src/precomp.hpp index 842a15ceaf..20101b77b5 100644 --- a/modules/imgproc/src/precomp.hpp +++ b/modules/imgproc/src/precomp.hpp @@ -43,9 +43,7 @@ #ifndef __OPENCV_PRECOMP_H__ #define __OPENCV_PRECOMP_H__ -#ifdef HAVE_CVCONFIG_H #include "cvconfig.h" -#endif #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/imgproc/imgproc_c.h" diff --git a/modules/imgproc/src/samplers.cpp b/modules/imgproc/src/samplers.cpp index e6d2d1214e..eb2f61755c 100644 --- a/modules/imgproc/src/samplers.cpp +++ b/modules/imgproc/src/samplers.cpp @@ -519,6 +519,12 @@ typedef CvStatus (CV_STDCALL *CvGetRectSubPixFunc)( const void* src, int src_ste int dst_step, CvSize win_size, CvPoint2D32f center ); +typedef CvStatus (CV_STDCALL *CvIPPGetRectSubPixFunc)( const void* src, int src_step, + CvSize src_size, void* dst, + int dst_step, CvSize win_size, + CvPoint2D32f center, + CvPoint* minpt, CvPoint* maxpt ); + CV_IMPL void cvGetRectSubPix( const void* srcarr, void* dstarr, CvPoint2D32f center ) { @@ -556,6 +562,18 @@ cvGetRectSubPix( const void* srcarr, void* dstarr, CvPoint2D32f center ) //if( dst_size.width > src_size.width || dst_size.height > src_size.height ) // CV_ERROR( CV_StsBadSize, "destination ROI must be smaller than source ROI" ); +#if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7) + CvPoint minpt, maxpt; + int srctype = CV_MAT_TYPE(src->type), dsttype = CV_MAT_TYPE(dst->type); + CvIPPGetRectSubPixFunc ippfunc = + srctype == CV_8UC1 && dsttype == CV_8UC1 ? (CvIPPGetRectSubPixFunc)ippiCopySubpixIntersect_8u_C1R : + srctype == CV_8UC1 && dsttype == CV_32FC1 ? (CvIPPGetRectSubPixFunc)ippiCopySubpixIntersect_8u32f_C1R : + srctype == CV_32FC1 && dsttype == CV_32FC1 ? (CvIPPGetRectSubPixFunc)ippiCopySubpixIntersect_32f_C1R : 0; + + if( ippfunc && ippfunc(src->data.ptr, src->step, src_size, dst->data.ptr, + dst->step, dst_size, center, &minpt, &maxpt) >= 0 ) + return; +#endif if( CV_ARE_DEPTHS_EQ( src, dst )) { diff --git a/modules/imgproc/src/shapedescr.cpp b/modules/imgproc/src/shapedescr.cpp index b1bc1babe2..c6c49a14ef 100644 --- a/modules/imgproc/src/shapedescr.cpp +++ b/modules/imgproc/src/shapedescr.cpp @@ -804,7 +804,7 @@ cvFitEllipse2( const CvArr* array ) CvPoint2D32f c = {0,0}; double gfp[5], rp[5], t; CvMat A, b, x; - const double min_eps = 1e-6; + const double min_eps = 1e-8; int i, is_float; CvSeqReader reader; diff --git a/modules/imgproc/src/smooth.cpp b/modules/imgproc/src/smooth.cpp index c84abe5c6d..00be086189 100644 --- a/modules/imgproc/src/smooth.cpp +++ b/modules/imgproc/src/smooth.cpp @@ -856,6 +856,22 @@ void cv::GaussianBlur( InputArray _src, OutputArray _dst, Size ksize, return; #endif +#if defined HAVE_IPP && (IPP_VERSION_MAJOR >= 7) + if(src.type() == CV_32FC1 && sigma1 == sigma2 && ksize.width == ksize.height && sigma1 != 0.0 ) + { + IppiSize roi = {src.cols, src.rows}; + int bufSize = 0; + ippiFilterGaussGetBufferSize_32f_C1R(roi, ksize.width, &bufSize); + AutoBuffer buf(bufSize+128); + if( ippiFilterGaussBorder_32f_C1R((const Ipp32f *)src.data, (int)src.step, + (Ipp32f *)dst.data, (int)dst.step, + roi, ksize.width, (Ipp32f)sigma1, + (IppiBorderType)borderType, 0.0, + alignPtr(&buf[0],32)) >= 0 ) + return; + } +#endif + Ptr f = createGaussianFilter( src.type(), ksize, sigma1, sigma2, borderType ); f->apply( src, dst ); } @@ -1888,6 +1904,29 @@ bilateralFilter_8u( const Mat& src, Mat& dst, int d, radius = MAX(radius, 1); d = radius*2 + 1; +#if 0 && defined HAVE_IPP && (IPP_VERSION_MAJOR >= 7) + if(cn == 1) + { + IppiSize kernel = {d, d}; + IppiSize roi={src.cols, src.rows}; + int bufsize=0; + ippiFilterBilateralGetBufSize_8u_C1R( ippiFilterBilateralGauss, roi, kernel, &bufsize); + AutoBuffer buf(bufsize+128); + IppiFilterBilateralSpec *pSpec = (IppiFilterBilateralSpec *)alignPtr(&buf[0], 32); + ippiFilterBilateralInit_8u_C1R( ippiFilterBilateralGauss, kernel, sigma_color*sigma_color, sigma_space*sigma_space, 1, pSpec ); + Mat tsrc; + const Mat* psrc = &src; + if( src.data == dst.data ) + { + src.copyTo(tsrc); + psrc = &tsrc; + } + if( ippiFilterBilateral_8u_C1R(psrc->data, (int)psrc->step[0], + dst.data, (int)dst.step[0], + roi, kernel, pSpec) >= 0 ) + return; + } +#endif Mat temp; copyMakeBorder( src, temp, radius, radius, radius, radius, borderType ); diff --git a/modules/imgproc/src/sumpixels.cpp b/modules/imgproc/src/sumpixels.cpp index b44197047a..4ee941762a 100644 --- a/modules/imgproc/src/sumpixels.cpp +++ b/modules/imgproc/src/sumpixels.cpp @@ -41,6 +41,9 @@ //M*/ #include "precomp.hpp" +#if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7) +static IppStatus sts = ippInit(); +#endif namespace cv { @@ -234,6 +237,53 @@ void cv::integral( InputArray _src, OutputArray _sum, OutputArray _sqsum, Output if( sdepth <= 0 ) sdepth = depth == CV_8U ? CV_32S : CV_64F; sdepth = CV_MAT_DEPTH(sdepth); + +#if defined (HAVE_IPP) && (IPP_VERSION_MAJOR >= 7) + if( ( depth == CV_8U ) && ( !_tilted.needed() ) ) + { + if( sdepth == CV_32F ) + { + if( cn == 1 ) + { + IppiSize srcRoiSize = ippiSize( src.cols, src.rows ); + _sum.create( isize, CV_MAKETYPE( sdepth, cn ) ); + sum = _sum.getMat(); + if( _sqsum.needed() ) + { + _sqsum.create( isize, CV_MAKETYPE( CV_64F, cn ) ); + sqsum = _sqsum.getMat(); + ippiSqrIntegral_8u32f64f_C1R( (const Ipp8u*)src.data, src.step, (Ipp32f*)sum.data, sum.step, (Ipp64f*)sqsum.data, sqsum.step, srcRoiSize, 0, 0 ); + } + else + { + ippiIntegral_8u32f_C1R( (const Ipp8u*)src.data, src.step, (Ipp32f*)sum.data, sum.step, srcRoiSize, 0 ); + } + return; + } + } + if( sdepth == CV_32S ) + { + if( cn == 1 ) + { + IppiSize srcRoiSize = ippiSize( src.cols, src.rows ); + _sum.create( isize, CV_MAKETYPE( sdepth, cn ) ); + sum = _sum.getMat(); + if( _sqsum.needed() ) + { + _sqsum.create( isize, CV_MAKETYPE( CV_64F, cn ) ); + sqsum = _sqsum.getMat(); + ippiSqrIntegral_8u32s64f_C1R( (const Ipp8u*)src.data, src.step, (Ipp32s*)sum.data, sum.step, (Ipp64f*)sqsum.data, sqsum.step, srcRoiSize, 0, 0 ); + } + else + { + ippiIntegral_8u32s_C1R( (const Ipp8u*)src.data, src.step, (Ipp32s*)sum.data, sum.step, srcRoiSize, 0 ); + } + return; + } + } + } +#endif + _sum.create( isize, CV_MAKETYPE(sdepth, cn) ); sum = _sum.getMat(); diff --git a/modules/imgproc/src/templmatch.cpp b/modules/imgproc/src/templmatch.cpp index ec7a92a223..18d7da9d91 100644 --- a/modules/imgproc/src/templmatch.cpp +++ b/modules/imgproc/src/templmatch.cpp @@ -248,6 +248,8 @@ void cv::matchTemplate( InputArray _img, InputArray _templ, OutputArray _result, CV_Assert( (img.depth() == CV_8U || img.depth() == CV_32F) && img.type() == templ.type() ); + CV_Assert( img.rows >= templ.rows && img.cols >= templ.cols); + Size corrSize(img.cols - templ.cols + 1, img.rows - templ.rows + 1); _result.create(corrSize, CV_32F); Mat result = _result.getMat(); diff --git a/modules/imgproc/test/test_precomp.cpp b/modules/imgproc/test/test_precomp.cpp deleted file mode 100644 index 5956e13e3e..0000000000 --- a/modules/imgproc/test/test_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "test_precomp.hpp" diff --git a/modules/java/android_test/src/org/opencv/test/core/CoreTest.java b/modules/java/android_test/src/org/opencv/test/core/CoreTest.java index a6023c7cc6..45e435330c 100644 --- a/modules/java/android_test/src/org/opencv/test/core/CoreTest.java +++ b/modules/java/android_test/src/org/opencv/test/core/CoreTest.java @@ -491,20 +491,6 @@ public class CoreTest extends OpenCVTestCase { Point truth[] = { new Point(5, 6), - new Point(5, 6), - new Point(5, 6), - new Point(5, 6), - new Point(5, 6), - new Point(5, 6), - new Point(5, 6), - new Point(5, 6), - new Point(4, 6), - new Point(4, 6), - new Point(4, 6), - new Point(4, 6), - new Point(4, 6), - new Point(4, 6), - new Point(4, 6), new Point(4, 6) }; assertArrayPointsEquals(truth, pts.toArray(), EPS); diff --git a/modules/java/generator/src/cpp/Mat.cpp b/modules/java/generator/src/cpp/Mat.cpp index 726dcaf5fb..b651b4d705 100644 --- a/modules/java/generator/src/cpp/Mat.cpp +++ b/modules/java/generator/src/cpp/Mat.cpp @@ -1,12 +1,37 @@ #define LOG_TAG "org.opencv.core.Mat" +#include + #include "common.h" #include "opencv2/core/core.hpp" using namespace cv; -extern "C" { +/// throw java exception +static void throwJavaException(JNIEnv *env, const std::exception *e, const char *method) { + std::string what = "unknown exception"; + jclass je = 0; + + if(e) { + std::string exception_type = "std::exception"; + + if(dynamic_cast(e)) { + exception_type = "cv::Exception"; + je = env->FindClass("org/opencv/core/CvException"); + } + + what = exception_type + ": " + e->what(); + } + + if(!je) je = env->FindClass("java/lang/Exception"); + env->ThrowNew(je, what.c_str()); + + LOGE("%s caught %s", method, what.c_str()); + (void)method; // avoid "unused" warning +} +extern "C" { + // // MatXXX::MatXXX() @@ -35,24 +60,17 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1Mat__III JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1Mat__III (JNIEnv* env, jclass, jint rows, jint cols, jint type) { + static const char method_name[] = "Mat::n_1Mat__III()"; try { - LOGD("Mat::n_1Mat__III()"); - - Mat* _retval_ = new Mat( rows, cols, type ); - - return (jlong) _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1Mat__III() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + LOGD("%s", method_name); + return (jlong) new Mat( rows, cols, type ); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1Mat__III() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1Mat__III()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -67,24 +85,18 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1Mat__DDI JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1Mat__DDI (JNIEnv* env, jclass, jdouble size_width, jdouble size_height, jint type) { + static const char method_name[] = "Mat::n_1Mat__DDI()"; try { - LOGD("Mat::n_1Mat__DDI()"); + LOGD("%s", method_name); Size size((int)size_width, (int)size_height); - Mat* _retval_ = new Mat( size, type ); - - return (jlong) _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1Mat__DDI() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + return (jlong) new Mat( size, type ); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1Mat__DDI() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1Mat__DDI()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -100,24 +112,18 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1Mat__IIIDDDD JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1Mat__IIIDDDD (JNIEnv* env, jclass, jint rows, jint cols, jint type, jdouble s_val0, jdouble s_val1, jdouble s_val2, jdouble s_val3) { + static const char method_name[] = "Mat::n_1Mat__IIIDDDD()"; try { - LOGD("Mat::n_1Mat__IIIDDDD()"); + LOGD("%s", method_name); Scalar s(s_val0, s_val1, s_val2, s_val3); - Mat* _retval_ = new Mat( rows, cols, type, s ); - - return (jlong) _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1Mat__IIIDDDD() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + return (jlong) new Mat( rows, cols, type, s ); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1Mat__IIIDDDD() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1Mat__IIIDDDD()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -132,25 +138,19 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1Mat__DDIDDDD JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1Mat__DDIDDDD (JNIEnv* env, jclass, jdouble size_width, jdouble size_height, jint type, jdouble s_val0, jdouble s_val1, jdouble s_val2, jdouble s_val3) { + static const char method_name[] = "Mat::n_1Mat__DDIDDDD()"; try { - LOGD("Mat::n_1Mat__DDIDDDD()"); + LOGD("%s", method_name); Size size((int)size_width, (int)size_height); Scalar s(s_val0, s_val1, s_val2, s_val3); - Mat* _retval_ = new Mat( size, type, s ); - - return (jlong) _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1Mat__DDIDDDD() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + return (jlong) new Mat( size, type, s ); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1Mat__DDIDDDD() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1Mat__DDIDDDD()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -165,25 +165,19 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1Mat__JIIII JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1Mat__JIIII (JNIEnv* env, jclass, jlong m_nativeObj, jint rowRange_start, jint rowRange_end, jint colRange_start, jint colRange_end) { + static const char method_name[] = "Mat::n_1Mat__JIIII()"; try { - LOGD("Mat::n_1Mat__JIIII()"); + LOGD("%s", method_name); Range rowRange(rowRange_start, rowRange_end); Range colRange(colRange_start, colRange_end); - Mat* _retval_ = new Mat( (*(Mat*)m_nativeObj), rowRange, colRange ); - - return (jlong) _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1Mat__JIIII() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + return (jlong) new Mat( (*(Mat*)m_nativeObj), rowRange, colRange ); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1Mat__JIIII() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1Mat__JIIII()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -194,24 +188,18 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1Mat__JII JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1Mat__JII (JNIEnv* env, jclass, jlong m_nativeObj, jint rowRange_start, jint rowRange_end) { + static const char method_name[] = "Mat::n_1Mat__JII()"; try { - LOGD("Mat::n_1Mat__JII()"); + LOGD("%s", method_name); Range rowRange(rowRange_start, rowRange_end); - Mat* _retval_ = new Mat( (*(Mat*)m_nativeObj), rowRange ); - - return (jlong) _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1Mat__JII() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + return (jlong) new Mat( (*(Mat*)m_nativeObj), rowRange ); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1Mat__JII() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1Mat__JII()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -225,24 +213,19 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1adjustROI JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1adjustROI (JNIEnv* env, jclass, jlong self, jint dtop, jint dbottom, jint dleft, jint dright) { + static const char method_name[] = "Mat::n_1adjustROI()"; try { - LOGD("Mat::n_1adjustROI()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat _retval_ = me->adjustROI( dtop, dbottom, dleft, dright ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1adjustROI() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1adjustROI() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1adjustROI()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -257,23 +240,15 @@ JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1assignTo__JJI JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1assignTo__JJI (JNIEnv* env, jclass, jlong self, jlong m_nativeObj, jint type) { + static const char method_name[] = "Mat::n_1assignTo__JJI()"; try { - LOGD("Mat::n_1assignTo__JJI()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL me->assignTo( (*(Mat*)m_nativeObj), type ); - - return; - } catch(cv::Exception e) { - LOGD("Mat::n_1assignTo__JJI() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1assignTo__JJI() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1assignTo__JJI()}"); - return; + throwJavaException(env, 0, method_name); } } @@ -284,23 +259,15 @@ JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1assignTo__JJ JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1assignTo__JJ (JNIEnv* env, jclass, jlong self, jlong m_nativeObj) { + static const char method_name[] = "Mat::n_1assignTo__JJ()"; try { - LOGD("Mat::n_1assignTo__JJ()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL me->assignTo( (*(Mat*)m_nativeObj) ); - - return; - } catch(cv::Exception e) { - LOGD("Mat::n_1assignTo__JJ() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1assignTo__JJ() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1assignTo__JJ()}"); - return; + throwJavaException(env, 0, method_name); } } @@ -316,24 +283,18 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1channels JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1channels (JNIEnv* env, jclass, jlong self) { + static const char method_name[] = "Mat::n_1channels()"; try { - LOGD("Mat::n_1channels()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL - int _retval_ = me->channels( ); - - return _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1channels() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + return me->channels( ); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1channels() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1channels()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -348,24 +309,18 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1checkVector__JIIZ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1checkVector__JIIZ (JNIEnv* env, jclass, jlong self, jint elemChannels, jint depth, jboolean requireContinuous) { + static const char method_name[] = "Mat::n_1checkVector__JIIZ()"; try { - LOGD("Mat::n_1checkVector__JIIZ()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL - int _retval_ = me->checkVector( elemChannels, depth, requireContinuous ); - - return _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1checkVector__JIIZ() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + return me->checkVector( elemChannels, depth, requireContinuous ); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1checkVector__JIIZ() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1checkVector__JIIZ()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -376,24 +331,18 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1checkVector__JII JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1checkVector__JII (JNIEnv* env, jclass, jlong self, jint elemChannels, jint depth) { + static const char method_name[] = "Mat::n_1checkVector__JII()"; try { - LOGD("Mat::n_1checkVector__JII()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL - int _retval_ = me->checkVector( elemChannels, depth ); - - return _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1checkVector__JII() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + return me->checkVector( elemChannels, depth ); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1checkVector__JII() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1checkVector__JII()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -404,24 +353,18 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1checkVector__JI JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1checkVector__JI (JNIEnv* env, jclass, jlong self, jint elemChannels) { + static const char method_name[] = "Mat::n_1checkVector__JI()"; try { - LOGD("Mat::n_1checkVector__JI()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL - int _retval_ = me->checkVector( elemChannels ); - - return _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1checkVector__JI() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + return me->checkVector( elemChannels ); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1checkVector__JI() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1checkVector__JI()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -437,24 +380,19 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1clone JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1clone (JNIEnv* env, jclass, jlong self) { + static const char method_name[] = "Mat::n_1clone()"; try { - LOGD("Mat::n_1clone()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat _retval_ = me->clone( ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1clone() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1clone() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1clone()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -469,24 +407,19 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1col JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1col (JNIEnv* env, jclass, jlong self, jint x) { + static const char method_name[] = "Mat::n_1col()"; try { - LOGD("Mat::n_1col()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat _retval_ = me->col( x ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1col() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1col() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1col()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -501,24 +434,45 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1colRange JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1colRange (JNIEnv* env, jclass, jlong self, jint startcol, jint endcol) { + static const char method_name[] = "Mat::n_1colRange()"; try { - LOGD("Mat::n_1colRange()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat _retval_ = me->colRange( startcol, endcol ); - return (jlong) new Mat(_retval_); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); + } catch (...) { + throwJavaException(env, 0, method_name); + } + + return 0; +} + + + +// +// int Mat::dims() +// + +JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1dims + (JNIEnv* env, jclass, jlong self); + +JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1dims + (JNIEnv* env, jclass, jlong self) +{ + static const char method_name[] = "Mat::n_1dims()"; + try { + LOGD("%s", method_name); + Mat* me = (Mat*) self; //TODO: check for NULL + return me->dims; } catch(cv::Exception e) { - LOGD("Mat::n_1colRange() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1colRange() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1colRange()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -533,24 +487,18 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1cols JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1cols (JNIEnv* env, jclass, jlong self) { + static const char method_name[] = "Mat::n_1cols()"; try { - LOGD("Mat::n_1cols()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL - int _retval_ = me->cols; - - return _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1cols() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + return me->cols; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1cols() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1cols()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -565,24 +513,16 @@ JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1convertTo__JJIDD JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1convertTo__JJIDD (JNIEnv* env, jclass, jlong self, jlong m_nativeObj, jint rtype, jdouble alpha, jdouble beta) { + static const char method_name[] = "Mat::n_1convertTo__JJIDD()"; try { - LOGD("Mat::n_1convertTo__JJIDD()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat& m = *((Mat*)m_nativeObj); me->convertTo( m, rtype, alpha, beta ); - - return; - } catch(cv::Exception e) { - LOGD("Mat::n_1convertTo__JJIDD() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1convertTo__JJIDD() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1convertTo__JJIDD()}"); - return; + throwJavaException(env, 0, method_name); } } @@ -593,24 +533,16 @@ JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1convertTo__JJID JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1convertTo__JJID (JNIEnv* env, jclass, jlong self, jlong m_nativeObj, jint rtype, jdouble alpha) { + static const char method_name[] = "Mat::n_1convertTo__JJID()"; try { - LOGD("Mat::n_1convertTo__JJID()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat& m = *((Mat*)m_nativeObj); me->convertTo( m, rtype, alpha ); - - return; - } catch(cv::Exception e) { - LOGD("Mat::n_1convertTo__JJID() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1convertTo__JJID() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1convertTo__JJID()}"); - return; + throwJavaException(env, 0, method_name); } } @@ -621,24 +553,16 @@ JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1convertTo__JJI JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1convertTo__JJI (JNIEnv* env, jclass, jlong self, jlong m_nativeObj, jint rtype) { + static const char method_name[] = "Mat::n_1convertTo__JJI()"; try { - LOGD("Mat::n_1convertTo__JJI()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat& m = *((Mat*)m_nativeObj); me->convertTo( m, rtype ); - - return; - } catch(cv::Exception e) { - LOGD("Mat::n_1convertTo__JJI() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1convertTo__JJI() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1convertTo__JJI()}"); - return; + throwJavaException(env, 0, method_name); } } @@ -654,24 +578,16 @@ JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1copyTo__JJ JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1copyTo__JJ (JNIEnv* env, jclass, jlong self, jlong m_nativeObj) { + static const char method_name[] = "Mat::n_1copyTo__JJ()"; try { - LOGD("Mat::n_1copyTo__JJ()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat& m = *((Mat*)m_nativeObj); me->copyTo( m ); - - return; - } catch(cv::Exception e) { - LOGD("Mat::n_1copyTo__JJ() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1copyTo__JJ() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1copyTo__JJ()}"); - return; + throwJavaException(env, 0, method_name); } } @@ -687,25 +603,17 @@ JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1copyTo__JJJ JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1copyTo__JJJ (JNIEnv* env, jclass, jlong self, jlong m_nativeObj, jlong mask_nativeObj) { + static const char method_name[] = "Mat::n_1copyTo__JJJ()"; try { - LOGD("Mat::n_1copyTo__JJJ()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat& m = *((Mat*)m_nativeObj); Mat& mask = *((Mat*)mask_nativeObj); me->copyTo( m, mask ); - - return; - } catch(cv::Exception e) { - LOGD("Mat::n_1copyTo__JJJ() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1copyTo__JJJ() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1copyTo__JJJ()}"); - return; + throwJavaException(env, 0, method_name); } } @@ -721,23 +629,15 @@ JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1create__JIII JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1create__JIII (JNIEnv* env, jclass, jlong self, jint rows, jint cols, jint type) { + static const char method_name[] = "Mat::n_1create__JIII()"; try { - LOGD("Mat::n_1create__JIII()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL me->create( rows, cols, type ); - - return; - } catch(cv::Exception e) { - LOGD("Mat::n_1create__JIII() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1create__JIII() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1create__JIII()}"); - return; + throwJavaException(env, 0, method_name); } } @@ -753,24 +653,16 @@ JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1create__JDDI JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1create__JDDI (JNIEnv* env, jclass, jlong self, jdouble size_width, jdouble size_height, jint type) { + static const char method_name[] = "Mat::n_1create__JDDI()"; try { - LOGD("Mat::n_1create__JDDI()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Size size((int)size_width, (int)size_height); me->create( size, type ); - - return; - } catch(cv::Exception e) { - LOGD("Mat::n_1create__JDDI() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1create__JDDI() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1create__JDDI()}"); - return; + throwJavaException(env, 0, method_name); } } @@ -786,25 +678,20 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1cross JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1cross (JNIEnv* env, jclass, jlong self, jlong m_nativeObj) { + static const char method_name[] = "Mat::n_1cross()"; try { - LOGD("Mat::n_1cross()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat& m = *((Mat*)m_nativeObj); Mat _retval_ = me->cross( m ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1cross() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1cross() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1cross()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -836,24 +723,18 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1depth JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1depth (JNIEnv* env, jclass, jlong self) { + static const char method_name[] = "Mat::n_1depth()"; try { - LOGD("Mat::n_1depth()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL - int _retval_ = me->depth( ); - - return _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1depth() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + return me->depth( ); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1depth() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1depth()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -868,24 +749,19 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1diag__JI JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1diag__JI (JNIEnv* env, jclass, jlong self, jint d) { + static const char method_name[] = "Mat::n_1diag__JI()"; try { - LOGD("Mat::n_1diag__JI()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat _retval_ = me->diag( d ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1diag__JI() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1diag__JI() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1diag__JI()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -901,24 +777,18 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1diag__J JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1diag__J (JNIEnv* env, jclass, jlong d_nativeObj) { + static const char method_name[] = "Mat::n_1diag__J()"; try { - LOGD("Mat::n_1diag__J()"); - + LOGD("%s", method_name); Mat _retval_ = Mat::diag( (*(Mat*)d_nativeObj) ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1diag__J() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1diag__J() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1diag__J()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -933,25 +803,19 @@ JNIEXPORT jdouble JNICALL Java_org_opencv_core_Mat_n_1dot JNIEXPORT jdouble JNICALL Java_org_opencv_core_Mat_n_1dot (JNIEnv* env, jclass, jlong self, jlong m_nativeObj) { + static const char method_name[] = "Mat::n_1dot()"; try { - LOGD("Mat::n_1dot()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat& m = *((Mat*)m_nativeObj); - double _retval_ = me->dot( m ); - - return _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1dot() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + return me->dot( m ); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1dot() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1dot()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -966,24 +830,18 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1elemSize JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1elemSize (JNIEnv* env, jclass, jlong self) { + static const char method_name[] = "Mat::n_1elemSize()"; try { - LOGD("Mat::n_1elemSize()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL - size_t _retval_ = me->elemSize( ); - - return _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1elemSize() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + return me->elemSize( ); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1elemSize() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1elemSize()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -998,24 +856,18 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1elemSize1 JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1elemSize1 (JNIEnv* env, jclass, jlong self) { + static const char method_name[] = "Mat::n_1elemSize1()"; try { - LOGD("Mat::n_1elemSize1()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL - size_t _retval_ = me->elemSize1( ); - - return _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1elemSize1() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + return me->elemSize1( ); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1elemSize1() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1elemSize1()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1030,24 +882,18 @@ JNIEXPORT jboolean JNICALL Java_org_opencv_core_Mat_n_1empty JNIEXPORT jboolean JNICALL Java_org_opencv_core_Mat_n_1empty (JNIEnv* env, jclass, jlong self) { + static const char method_name[] = "Mat::n_1empty()"; try { - LOGD("Mat::n_1empty()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL - bool _retval_ = me->empty( ); - - return _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1empty() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + return me->empty( ); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1empty() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1empty()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1062,24 +908,18 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1eye__III JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1eye__III (JNIEnv* env, jclass, jint rows, jint cols, jint type) { + static const char method_name[] = "Mat::n_1eye__III()"; try { - LOGD("Mat::n_1eye__III()"); - + LOGD("%s", method_name); Mat _retval_ = Mat::eye( rows, cols, type ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1eye__III() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1eye__III() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1eye__III()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1094,24 +934,19 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1eye__DDI JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1eye__DDI (JNIEnv* env, jclass, jdouble size_width, jdouble size_height, jint type) { + static const char method_name[] = "Mat::n_1eye__DDI()"; try { - LOGD("Mat::n_1eye__DDI()"); + LOGD("%s", method_name); Size size((int)size_width, (int)size_height); Mat _retval_ = Mat::eye( size, type ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1eye__DDI() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1eye__DDI() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1eye__DDI()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1126,24 +961,19 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1inv__JI JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1inv__JI (JNIEnv* env, jclass, jlong self, jint method) { + static const char method_name[] = "Mat::n_1inv__JI()"; try { - LOGD("Mat::n_1inv__JI()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat _retval_ = me->inv( method ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1inv__JI() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1inv__JI() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1inv__JI()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1153,24 +983,19 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1inv__J JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1inv__J (JNIEnv* env, jclass, jlong self) { + static const char method_name[] = "Mat::n_1inv__J()"; try { - LOGD("Mat::n_1inv__J()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat _retval_ = me->inv( ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1inv__J() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1inv__J() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1inv__J()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1185,24 +1010,18 @@ JNIEXPORT jboolean JNICALL Java_org_opencv_core_Mat_n_1isContinuous JNIEXPORT jboolean JNICALL Java_org_opencv_core_Mat_n_1isContinuous (JNIEnv* env, jclass, jlong self) { + static const char method_name[] = "Mat::n_1isContinuous()"; try { - LOGD("Mat::n_1isContinuous()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL - bool _retval_ = me->isContinuous( ); - - return _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1isContinuous() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + return me->isContinuous( ); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1isContinuous() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1isContinuous()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1217,24 +1036,18 @@ JNIEXPORT jboolean JNICALL Java_org_opencv_core_Mat_n_1isSubmatrix JNIEXPORT jboolean JNICALL Java_org_opencv_core_Mat_n_1isSubmatrix (JNIEnv* env, jclass, jlong self) { + static const char method_name[] = "Mat::n_1isSubmatrix()"; try { - LOGD("Mat::n_1isSubmatrix()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL - bool _retval_ = me->isSubmatrix( ); - - return _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1isSubmatrix() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + return me->isSubmatrix( ); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1isSubmatrix() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1isSubmatrix()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1249,25 +1062,18 @@ JNIEXPORT void JNICALL Java_org_opencv_core_Mat_locateROI_10 JNIEXPORT void JNICALL Java_org_opencv_core_Mat_locateROI_10 (JNIEnv* env, jclass, jlong self, jdoubleArray wholeSize_out, jdoubleArray ofs_out) { + static const char method_name[] = "core::locateROI_10()"; try { - LOGD("core::locateROI_10()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Size wholeSize; Point ofs; me->locateROI( wholeSize, ofs ); jdouble tmp_wholeSize[2] = {wholeSize.width, wholeSize.height}; env->SetDoubleArrayRegion(wholeSize_out, 0, 2, tmp_wholeSize); jdouble tmp_ofs[2] = {ofs.x, ofs.y}; env->SetDoubleArrayRegion(ofs_out, 0, 2, tmp_ofs); - return; - } catch(cv::Exception e) { - LOGD("Mat::locateROI_10() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::locateROI_10() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::locateROI_10()}"); - return; + throwJavaException(env, 0, method_name); } } @@ -1283,25 +1089,20 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1mul__JJD JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1mul__JJD (JNIEnv* env, jclass, jlong self, jlong m_nativeObj, jdouble scale) { + static const char method_name[] = "Mat::n_1mul__JJD()"; try { - LOGD("Mat::n_1mul__JJD()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat& m = *((Mat*)m_nativeObj); Mat _retval_ = me->mul( m, scale ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1mul__JJD() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1mul__JJD() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1mul__JJD()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1312,25 +1113,20 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1mul__JJ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1mul__JJ (JNIEnv* env, jclass, jlong self, jlong m_nativeObj) { + static const char method_name[] = "Mat::n_1mul__JJ()"; try { - LOGD("Mat::n_1mul__JJ()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat& m = *((Mat*)m_nativeObj); Mat _retval_ = me->mul( m ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1mul__JJ() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1mul__JJ() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1mul__JJ()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1345,24 +1141,18 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1ones__III JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1ones__III (JNIEnv* env, jclass, jint rows, jint cols, jint type) { + static const char method_name[] = "Mat::n_1ones__III()"; try { - LOGD("Mat::n_1ones__III()"); - + LOGD("%s", method_name); Mat _retval_ = Mat::ones( rows, cols, type ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1ones__III() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1ones__III() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1ones__III()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1377,24 +1167,19 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1ones__DDI JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1ones__DDI (JNIEnv* env, jclass, jdouble size_width, jdouble size_height, jint type) { + static const char method_name[] = "Mat::n_1ones__DDI()"; try { - LOGD("Mat::n_1ones__DDI()"); + LOGD("%s", method_name); Size size((int)size_width, (int)size_height); Mat _retval_ = Mat::ones( size, type ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1ones__DDI() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1ones__DDI() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1ones__DDI()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1409,23 +1194,15 @@ JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1push_1back JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1push_1back (JNIEnv* env, jclass, jlong self, jlong m_nativeObj) { + static const char method_name[] = "Mat::n_1push_1back()"; try { - LOGD("Mat::n_1push_1back()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL me->push_back( (*(Mat*)m_nativeObj) ); - - return; - } catch(cv::Exception e) { - LOGD("Mat::n_1push_1back() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1push_1back() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1push_1back()}"); - return; + throwJavaException(env, 0, method_name); } } @@ -1441,23 +1218,15 @@ JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1release JNIEXPORT void JNICALL Java_org_opencv_core_Mat_n_1release (JNIEnv* env, jclass, jlong self) { + static const char method_name[] = "Mat::n_1release()"; try { - LOGD("Mat::n_1release()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL me->release( ); - - return; - } catch(cv::Exception e) { - LOGD("Mat::n_1release() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1release() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1release()}"); - return; + throwJavaException(env, 0, method_name); } } @@ -1473,24 +1242,19 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1reshape__JII JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1reshape__JII (JNIEnv* env, jclass, jlong self, jint cn, jint rows) { + static const char method_name[] = "Mat::n_1reshape__JII()"; try { - LOGD("Mat::n_1reshape__JII()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat _retval_ = me->reshape( cn, rows ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1reshape__JII() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1reshape__JII() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1reshape__JII()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1501,24 +1265,19 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1reshape__JI JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1reshape__JI (JNIEnv* env, jclass, jlong self, jint cn) { + static const char method_name[] = "Mat::n_1reshape__JI()"; try { - LOGD("Mat::n_1reshape__JI()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat _retval_ = me->reshape( cn ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1reshape__JI() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1reshape__JI() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1reshape__JI()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1533,24 +1292,19 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1row JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1row (JNIEnv* env, jclass, jlong self, jint y) { + static const char method_name[] = "Mat::n_1row()"; try { - LOGD("Mat::n_1row()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat _retval_ = me->row( y ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1row() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1row() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1row()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1565,24 +1319,19 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1rowRange JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1rowRange (JNIEnv* env, jclass, jlong self, jint startrow, jint endrow) { + static const char method_name[] = "Mat::n_1rowRange()"; try { - LOGD("Mat::n_1rowRange()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat _retval_ = me->rowRange( startrow, endrow ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1rowRange() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1rowRange() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1rowRange()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1597,24 +1346,18 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1rows JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1rows (JNIEnv* env, jclass, jlong self) { + static const char method_name[] = "Mat::n_1rows()"; try { - LOGD("Mat::n_1rows()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL - int _retval_ = me->rows; - - return _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1rows() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + return me->rows; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1rows() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1rows()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1629,25 +1372,20 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1setTo__JDDDD JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1setTo__JDDDD (JNIEnv* env, jclass, jlong self, jdouble s_val0, jdouble s_val1, jdouble s_val2, jdouble s_val3) { + static const char method_name[] = "Mat::n_1setTo__JDDDD()"; try { - LOGD("Mat::n_1setTo__JDDDD()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Scalar s(s_val0, s_val1, s_val2, s_val3); Mat _retval_ = me->operator =( s ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1setTo__JDDDD() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1setTo__JDDDD() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1setTo__JDDDD()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1662,26 +1400,21 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1setTo__JDDDDJ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1setTo__JDDDDJ (JNIEnv* env, jclass, jlong self, jdouble s_val0, jdouble s_val1, jdouble s_val2, jdouble s_val3, jlong mask_nativeObj) { + static const char method_name[] = "Mat::n_1setTo__JDDDDJ()"; try { - LOGD("Mat::n_1setTo__JDDDDJ()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Scalar s(s_val0, s_val1, s_val2, s_val3); Mat& mask = *((Mat*)mask_nativeObj); Mat _retval_ = me->setTo( s, mask ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1setTo__JDDDDJ() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1setTo__JDDDDJ() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1setTo__JDDDDJ()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1696,26 +1429,21 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1setTo__JJJ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1setTo__JJJ (JNIEnv* env, jclass, jlong self, jlong value_nativeObj, jlong mask_nativeObj) { + static const char method_name[] = "Mat::n_1setTo__JJJ()"; try { - LOGD("Mat::n_1setTo__JJJ()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat& value = *((Mat*)value_nativeObj); Mat& mask = *((Mat*)mask_nativeObj); Mat _retval_ = me->setTo( value, mask ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1setTo__JJJ() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1setTo__JJJ() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1setTo__JJJ()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1726,25 +1454,20 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1setTo__JJ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1setTo__JJ (JNIEnv* env, jclass, jlong self, jlong value_nativeObj) { + static const char method_name[] = "Mat::n_1setTo__JJ()"; try { - LOGD("Mat::n_1setTo__JJ()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat& value = *((Mat*)value_nativeObj); Mat _retval_ = me->setTo( value ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1setTo__JJ() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1setTo__JJ() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1setTo__JJ()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1759,24 +1482,22 @@ JNIEXPORT jdoubleArray JNICALL Java_org_opencv_core_Mat_n_1size JNIEXPORT jdoubleArray JNICALL Java_org_opencv_core_Mat_n_1size (JNIEnv* env, jclass, jlong self) { + static const char method_name[] = "Mat::n_1size()"; try { - LOGD("Mat::n_1size()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Size _retval_ = me->size( ); - jdoubleArray _da_retval_ = env->NewDoubleArray(2); jdouble _tmp_retval_[2] = {_retval_.width, _retval_.height}; env->SetDoubleArrayRegion(_da_retval_, 0, 2, _tmp_retval_); + jdoubleArray _da_retval_ = env->NewDoubleArray(2); + jdouble _tmp_retval_[2] = {_retval_.width, _retval_.height}; + env->SetDoubleArrayRegion(_da_retval_, 0, 2, _tmp_retval_); return _da_retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1size() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1size() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1size()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1791,24 +1512,18 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1step1__JI JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1step1__JI (JNIEnv* env, jclass, jlong self, jint i) { + static const char method_name[] = "Mat::n_1step1__JI()"; try { - LOGD("Mat::n_1step1__JI()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL - size_t _retval_ = me->step1( i ); - - return _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1step1__JI() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + return me->step1( i ); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1step1__JI() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1step1__JI()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1819,24 +1534,18 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1step1__J JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1step1__J (JNIEnv* env, jclass, jlong self) { + static const char method_name[] = "Mat::n_1step1__J()"; try { - LOGD("Mat::n_1step1__J()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL - size_t _retval_ = me->step1( ); - - return _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1step1__J() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + return me->step1( ); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1step1__J() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1step1__J()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } // @@ -1849,26 +1558,21 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1submat_1rr JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1submat_1rr (JNIEnv* env, jclass, jlong self, jint rowRange_start, jint rowRange_end, jint colRange_start, jint colRange_end) { + static const char method_name[] = "Mat::n_1submat_1rr()"; try { - LOGD("Mat::n_1submat_1rr()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Range rowRange(rowRange_start, rowRange_end); Range colRange(colRange_start, colRange_end); Mat _retval_ = me->operator()( rowRange, colRange ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1submat_1rr() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1submat_1rr() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1submat_1rr()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1883,25 +1587,20 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1submat JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1submat (JNIEnv* env, jclass, jlong self, jint roi_x, jint roi_y, jint roi_width, jint roi_height) { + static const char method_name[] = "Mat::n_1submat()"; try { - LOGD("Mat::n_1submat()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Rect roi(roi_x, roi_y, roi_width, roi_height); Mat _retval_ = me->operator()( roi ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1submat() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1submat() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1submat()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1916,24 +1615,19 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1t JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1t (JNIEnv* env, jclass, jlong self) { + static const char method_name[] = "Mat::n_1t()"; try { - LOGD("Mat::n_1t()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL Mat _retval_ = me->t( ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1t() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1t() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1t()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1948,24 +1642,18 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1total JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1total (JNIEnv* env, jclass, jlong self) { + static const char method_name[] = "Mat::n_1total()"; try { - LOGD("Mat::n_1total()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL - size_t _retval_ = me->total( ); - - return _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1total() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + return me->total( ); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1total() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1total()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -1980,24 +1668,18 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1type JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_n_1type (JNIEnv* env, jclass, jlong self) { + static const char method_name[] = "Mat::n_1type()"; try { - LOGD("Mat::n_1type()"); + LOGD("%s", method_name); Mat* me = (Mat*) self; //TODO: check for NULL - int _retval_ = me->type( ); - - return _retval_; - } catch(cv::Exception e) { - LOGD("Mat::n_1type() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + return me->type( ); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1type() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1type()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -2012,24 +1694,18 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1zeros__III JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1zeros__III (JNIEnv* env, jclass, jint rows, jint cols, jint type) { + static const char method_name[] = "Mat::n_1zeros__III()"; try { - LOGD("Mat::n_1zeros__III()"); - + LOGD("%s", method_name); Mat _retval_ = Mat::zeros( rows, cols, type ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1zeros__III() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1zeros__III() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1zeros__III()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -2044,24 +1720,19 @@ JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1zeros__DDI JNIEXPORT jlong JNICALL Java_org_opencv_core_Mat_n_1zeros__DDI (JNIEnv* env, jclass, jdouble size_width, jdouble size_height, jint type) { + static const char method_name[] = "Mat::n_1zeros__DDI()"; try { - LOGD("Mat::n_1zeros__DDI()"); + LOGD("%s", method_name); Size size((int)size_width, (int)size_height); Mat _retval_ = Mat::zeros( size, type ); - return (jlong) new Mat(_retval_); - } catch(cv::Exception e) { - LOGD("Mat::n_1zeros__DDI() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::n_1zeros__DDI() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::n_1zeros__DDI()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -2089,8 +1760,9 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nPutD JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nPutD (JNIEnv* env, jclass, jlong self, jint row, jint col, jint count, jdoubleArray vals) { + static const char method_name[] = "Mat::nPutD()"; try { - LOGD("Mat::nPutD()"); + LOGD("%s", method_name); cv::Mat* me = (cv::Mat*) self; if(!me || !me->data) return 0; // no native object behind if(me->rows<=row || me->cols<=col) return 0; // indexes out of range @@ -2130,18 +1802,13 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nPutD env->ReleasePrimitiveArrayCritical(vals, values, 0); return res; - } catch(cv::Exception e) { - LOGD("Mat::nPutD() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::nPutD() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::nPutD()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -2186,8 +1853,9 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nPutB JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nPutB (JNIEnv* env, jclass, jlong self, jint row, jint col, jint count, jbyteArray vals) { + static const char method_name[] = "Mat::nPutB()"; try { - LOGD("Mat::nPutB()"); + LOGD("%s", method_name); cv::Mat* me = (cv::Mat*) self; if(! self) return 0; // no native object behind if(me->depth() != CV_8U && me->depth() != CV_8S) return 0; // incompatible type @@ -2197,18 +1865,13 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nPutB int res = mat_put(me, row, col, count, values); env->ReleasePrimitiveArrayCritical(vals, values, 0); return res; - } catch(cv::Exception e) { - LOGD("Mat::nPutB() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::nPutB() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::nPutB()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nPutS @@ -2217,8 +1880,9 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nPutS JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nPutS (JNIEnv* env, jclass, jlong self, jint row, jint col, jint count, jshortArray vals) { + static const char method_name[] = "Mat::nPutS()"; try { - LOGD("Mat::nPutS()"); + LOGD("%s", method_name); cv::Mat* me = (cv::Mat*) self; if(! self) return 0; // no native object behind if(me->depth() != CV_16U && me->depth() != CV_16S) return 0; // incompatible type @@ -2228,18 +1892,13 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nPutS int res = mat_put(me, row, col, count, values); env->ReleasePrimitiveArrayCritical(vals, values, 0); return res; - } catch(cv::Exception e) { - LOGD("Mat::nPutS() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::nPutS() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::nPutS()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nPutI @@ -2248,8 +1907,9 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nPutI JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nPutI (JNIEnv* env, jclass, jlong self, jint row, jint col, jint count, jintArray vals) { + static const char method_name[] = "Mat::nPutI()"; try { - LOGD("Mat::nPutI()"); + LOGD("%s", method_name); cv::Mat* me = (cv::Mat*) self; if(! self) return 0; // no native object behind if(me->depth() != CV_32S) return 0; // incompatible type @@ -2259,18 +1919,13 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nPutI int res = mat_put(me, row, col, count, values); env->ReleasePrimitiveArrayCritical(vals, values, 0); return res; - } catch(cv::Exception e) { - LOGD("Mat::nPutI() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::nPutI() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::nPutI()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nPutF @@ -2279,8 +1934,9 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nPutF JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nPutF (JNIEnv* env, jclass, jlong self, jint row, jint col, jint count, jfloatArray vals) { + static const char method_name[] = "Mat::nPutF()"; try { - LOGD("Mat::nPutF()"); + LOGD("%s", method_name); cv::Mat* me = (cv::Mat*) self; if(! self) return 0; // no native object behind if(me->depth() != CV_32F) return 0; // incompatible type @@ -2290,18 +1946,13 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nPutF int res = mat_put(me, row, col, count, values); env->ReleasePrimitiveArrayCritical(vals, values, 0); return res; - } catch(cv::Exception e) { - LOGD("Mat::nPutF() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::nPutF() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::nPutF()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } @@ -2345,8 +1996,9 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nGetB JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nGetB (JNIEnv* env, jclass, jlong self, jint row, jint col, jint count, jbyteArray vals) { + static const char method_name[] = "Mat::nGetB()"; try { - LOGD("Mat::nGetB()"); + LOGD("%s", method_name); cv::Mat* me = (cv::Mat*) self; if(! self) return 0; // no native object behind if(me->depth() != CV_8U && me->depth() != CV_8S) return 0; // incompatible type @@ -2356,18 +2008,13 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nGetB int res = mat_get(me, row, col, count, values); env->ReleasePrimitiveArrayCritical(vals, values, 0); return res; - } catch(cv::Exception e) { - LOGD("Mat::nGetB() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::nGetB() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::nGetB()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nGetS @@ -2376,8 +2023,9 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nGetS JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nGetS (JNIEnv* env, jclass, jlong self, jint row, jint col, jint count, jshortArray vals) { + static const char method_name[] = "Mat::nGetS()"; try { - LOGD("Mat::nGetS()"); + LOGD("%s", method_name); cv::Mat* me = (cv::Mat*) self; if(! self) return 0; // no native object behind if(me->depth() != CV_16U && me->depth() != CV_16S) return 0; // incompatible type @@ -2387,18 +2035,13 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nGetS int res = mat_get(me, row, col, count, values); env->ReleasePrimitiveArrayCritical(vals, values, 0); return res; - } catch(cv::Exception e) { - LOGD("Mat::nGetS() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::nGetS() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::nGetS()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nGetI @@ -2407,8 +2050,9 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nGetI JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nGetI (JNIEnv* env, jclass, jlong self, jint row, jint col, jint count, jintArray vals) { + static const char method_name[] = "Mat::nGetI()"; try { - LOGD("Mat::nGetI()"); + LOGD("%s", method_name); cv::Mat* me = (cv::Mat*) self; if(! self) return 0; // no native object behind if(me->depth() != CV_32S) return 0; // incompatible type @@ -2418,18 +2062,13 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nGetI int res = mat_get(me, row, col, count, values); env->ReleasePrimitiveArrayCritical(vals, values, 0); return res; - } catch(cv::Exception e) { - LOGD("Mat::nGetI() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::nGetI() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::nGetI()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nGetF @@ -2438,8 +2077,9 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nGetF JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nGetF (JNIEnv* env, jclass, jlong self, jint row, jint col, jint count, jfloatArray vals) { + static const char method_name[] = "Mat::nGetF()"; try { - LOGD("Mat::nGetF()"); + LOGD("%s", method_name); cv::Mat* me = (cv::Mat*) self; if(! self) return 0; // no native object behind if(me->depth() != CV_32F) return 0; // incompatible type @@ -2449,18 +2089,13 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nGetF int res = mat_get(me, row, col, count, values); env->ReleasePrimitiveArrayCritical(vals, values, 0); return res; - } catch(cv::Exception e) { - LOGD("Mat::nGetF() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::nGetF() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::nGetF()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nGetD @@ -2469,8 +2104,9 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nGetD JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nGetD (JNIEnv* env, jclass, jlong self, jint row, jint col, jint count, jdoubleArray vals) { + static const char method_name[] = "Mat::nGetD()"; try { - LOGD("Mat::nGetD()"); + LOGD("%s", method_name); cv::Mat* me = (cv::Mat*) self; if(! self) return 0; // no native object behind if(me->depth() != CV_64F) return 0; // incompatible type @@ -2480,18 +2116,13 @@ JNIEXPORT jint JNICALL Java_org_opencv_core_Mat_nGetD int res = mat_get(me, row, col, count, values); env->ReleasePrimitiveArrayCritical(vals, values, 0); return res; - } catch(cv::Exception e) { - LOGD("Mat::nGetD() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::nGetD() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::nGetD()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } JNIEXPORT jdoubleArray JNICALL Java_org_opencv_core_Mat_nGet @@ -2500,8 +2131,9 @@ JNIEXPORT jdoubleArray JNICALL Java_org_opencv_core_Mat_nGet JNIEXPORT jdoubleArray JNICALL Java_org_opencv_core_Mat_nGet (JNIEnv* env, jclass, jlong self, jint row, jint col) { + static const char method_name[] = "Mat::nGet()"; try { - LOGD("Mat::nGet()"); + LOGD("%s", method_name); cv::Mat* me = (cv::Mat*) self; if(! self) return 0; // no native object behind if(me->rows<=row || me->cols<=col) return 0; // indexes out of range @@ -2522,18 +2154,13 @@ JNIEXPORT jdoubleArray JNICALL Java_org_opencv_core_Mat_nGet env->SetDoubleArrayRegion(res, 0, me->channels(), buff); } return res; - } catch(cv::Exception e) { - LOGD("Mat::nGet() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return 0; + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); } catch (...) { - LOGD("Mat::nGet() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::nGet()}"); - return 0; + throwJavaException(env, 0, method_name); } + + return 0; } JNIEXPORT jstring JNICALL Java_org_opencv_core_Mat_nDump @@ -2542,25 +2169,21 @@ JNIEXPORT jstring JNICALL Java_org_opencv_core_Mat_nDump JNIEXPORT jstring JNICALL Java_org_opencv_core_Mat_nDump (JNIEnv *env, jclass, jlong self) { - cv::Mat* me = (cv::Mat*) self; //TODO: check for NULL - std::stringstream s; - try { - LOGD("Mat::nDump()"); - - s << *me; - return env->NewStringUTF(s.str().c_str()); - } catch(cv::Exception e) { - LOGE("Mat::nDump() catched cv::Exception: %s", e.what()); - jclass je = env->FindClass("org/opencv/core/CvException"); - if(!je) je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, e.what()); - return env->NewStringUTF("ERROR"); - } catch (...) { - LOGE("Mat::nDump() catched unknown exception (...)"); - jclass je = env->FindClass("java/lang/Exception"); - env->ThrowNew(je, "Unknown exception in JNI code {Mat::nDump()}"); - return env->NewStringUTF("ERROR"); - } + static const char method_name[] = "Mat::nDump()"; + try { + LOGD("%s", method_name); + cv::Mat* me = (cv::Mat*) self; //TODO: check for NULL + std::stringstream s; + s << *me; + std::string str = s.str(); + return env->NewStringUTF(str.c_str()); + } catch(const std::exception &e) { + throwJavaException(env, &e, method_name); + } catch (...) { + throwJavaException(env, 0, method_name); + } + + return 0; } diff --git a/modules/java/generator/src/java/core+Mat.java b/modules/java/generator/src/java/core+Mat.java index 8dd72fb681..6db255417c 100644 --- a/modules/java/generator/src/java/core+Mat.java +++ b/modules/java/generator/src/java/core+Mat.java @@ -245,6 +245,19 @@ public class Mat { return retVal; } + // + // C++: int Mat::dims() + // + + // javadoc: Mat::dims() + public int dims() + { + + int retVal = n_dims(nativeObj); + + return retVal; + } + // // C++: int Mat::cols() // @@ -1130,6 +1143,9 @@ public class Mat { // C++: Mat Mat::colRange(int startcol, int endcol) private static native long n_colRange(long nativeObj, int startcol, int endcol); + // C++: int Mat::dims() + private static native int n_dims(long nativeObj); + // C++: int Mat::cols() private static native int n_cols(long nativeObj); diff --git a/modules/java/generator/src/java/core+MatOfByte.java b/modules/java/generator/src/java/core+MatOfByte.java index b3fe5691ee..7756eb94f9 100644 --- a/modules/java/generator/src/java/core+MatOfByte.java +++ b/modules/java/generator/src/java/core+MatOfByte.java @@ -15,7 +15,7 @@ public class MatOfByte extends Mat { protected MatOfByte(long addr) { super(addr); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } @@ -26,7 +26,7 @@ public class MatOfByte extends Mat { public MatOfByte(Mat m) { super(m, Range.all()); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } diff --git a/modules/java/generator/src/java/core+MatOfDMatch.java b/modules/java/generator/src/java/core+MatOfDMatch.java index 4a161017d4..b703c5c86a 100644 --- a/modules/java/generator/src/java/core+MatOfDMatch.java +++ b/modules/java/generator/src/java/core+MatOfDMatch.java @@ -17,7 +17,7 @@ public class MatOfDMatch extends Mat { protected MatOfDMatch(long addr) { super(addr); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat: " + toString()); + throw new IllegalArgumentException("Incompatible Mat: " + toString()); //FIXME: do we need release() here? } @@ -28,7 +28,7 @@ public class MatOfDMatch extends Mat { public MatOfDMatch(Mat m) { super(m, Range.all()); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat: " + toString()); + throw new IllegalArgumentException("Incompatible Mat: " + toString()); //FIXME: do we need release() here? } diff --git a/modules/java/generator/src/java/core+MatOfDouble.java b/modules/java/generator/src/java/core+MatOfDouble.java index 4eb7cbc280..1a8e23ca30 100644 --- a/modules/java/generator/src/java/core+MatOfDouble.java +++ b/modules/java/generator/src/java/core+MatOfDouble.java @@ -15,7 +15,7 @@ public class MatOfDouble extends Mat { protected MatOfDouble(long addr) { super(addr); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } @@ -26,7 +26,7 @@ public class MatOfDouble extends Mat { public MatOfDouble(Mat m) { super(m, Range.all()); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } diff --git a/modules/java/generator/src/java/core+MatOfFloat.java b/modules/java/generator/src/java/core+MatOfFloat.java index 96bbeab9fb..dfd6b84048 100644 --- a/modules/java/generator/src/java/core+MatOfFloat.java +++ b/modules/java/generator/src/java/core+MatOfFloat.java @@ -15,7 +15,7 @@ public class MatOfFloat extends Mat { protected MatOfFloat(long addr) { super(addr); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } @@ -26,7 +26,7 @@ public class MatOfFloat extends Mat { public MatOfFloat(Mat m) { super(m, Range.all()); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } diff --git a/modules/java/generator/src/java/core+MatOfFloat4.java b/modules/java/generator/src/java/core+MatOfFloat4.java index aaa97b7990..96f9e5cde4 100644 --- a/modules/java/generator/src/java/core+MatOfFloat4.java +++ b/modules/java/generator/src/java/core+MatOfFloat4.java @@ -15,7 +15,7 @@ public class MatOfFloat4 extends Mat { protected MatOfFloat4(long addr) { super(addr); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } @@ -26,7 +26,7 @@ public class MatOfFloat4 extends Mat { public MatOfFloat4(Mat m) { super(m, Range.all()); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } diff --git a/modules/java/generator/src/java/core+MatOfFloat6.java b/modules/java/generator/src/java/core+MatOfFloat6.java index 68e6249b6d..140bb57a9b 100644 --- a/modules/java/generator/src/java/core+MatOfFloat6.java +++ b/modules/java/generator/src/java/core+MatOfFloat6.java @@ -15,7 +15,7 @@ public class MatOfFloat6 extends Mat { protected MatOfFloat6(long addr) { super(addr); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } @@ -26,7 +26,7 @@ public class MatOfFloat6 extends Mat { public MatOfFloat6(Mat m) { super(m, Range.all()); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } diff --git a/modules/java/generator/src/java/core+MatOfInt.java b/modules/java/generator/src/java/core+MatOfInt.java index 33e5124e4f..7d076878fc 100644 --- a/modules/java/generator/src/java/core+MatOfInt.java +++ b/modules/java/generator/src/java/core+MatOfInt.java @@ -16,7 +16,7 @@ public class MatOfInt extends Mat { protected MatOfInt(long addr) { super(addr); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } @@ -27,7 +27,7 @@ public class MatOfInt extends Mat { public MatOfInt(Mat m) { super(m, Range.all()); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } diff --git a/modules/java/generator/src/java/core+MatOfInt4.java b/modules/java/generator/src/java/core+MatOfInt4.java index c924233a6c..4ca4d9e318 100644 --- a/modules/java/generator/src/java/core+MatOfInt4.java +++ b/modules/java/generator/src/java/core+MatOfInt4.java @@ -16,7 +16,7 @@ public class MatOfInt4 extends Mat { protected MatOfInt4(long addr) { super(addr); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } @@ -27,7 +27,7 @@ public class MatOfInt4 extends Mat { public MatOfInt4(Mat m) { super(m, Range.all()); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } diff --git a/modules/java/generator/src/java/core+MatOfKeyPoint.java b/modules/java/generator/src/java/core+MatOfKeyPoint.java index b402fe1245..d0a18793d8 100644 --- a/modules/java/generator/src/java/core+MatOfKeyPoint.java +++ b/modules/java/generator/src/java/core+MatOfKeyPoint.java @@ -17,7 +17,7 @@ public class MatOfKeyPoint extends Mat { protected MatOfKeyPoint(long addr) { super(addr); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } @@ -28,7 +28,7 @@ public class MatOfKeyPoint extends Mat { public MatOfKeyPoint(Mat m) { super(m, Range.all()); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } diff --git a/modules/java/generator/src/java/core+MatOfPoint.java b/modules/java/generator/src/java/core+MatOfPoint.java index 6d23ed1162..f4d573bb73 100644 --- a/modules/java/generator/src/java/core+MatOfPoint.java +++ b/modules/java/generator/src/java/core+MatOfPoint.java @@ -15,7 +15,7 @@ public class MatOfPoint extends Mat { protected MatOfPoint(long addr) { super(addr); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } @@ -26,7 +26,7 @@ public class MatOfPoint extends Mat { public MatOfPoint(Mat m) { super(m, Range.all()); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } diff --git a/modules/java/generator/src/java/core+MatOfPoint2f.java b/modules/java/generator/src/java/core+MatOfPoint2f.java index 0c6960730b..4b8c926fff 100644 --- a/modules/java/generator/src/java/core+MatOfPoint2f.java +++ b/modules/java/generator/src/java/core+MatOfPoint2f.java @@ -15,7 +15,7 @@ public class MatOfPoint2f extends Mat { protected MatOfPoint2f(long addr) { super(addr); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } @@ -26,7 +26,7 @@ public class MatOfPoint2f extends Mat { public MatOfPoint2f(Mat m) { super(m, Range.all()); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } diff --git a/modules/java/generator/src/java/core+MatOfPoint3.java b/modules/java/generator/src/java/core+MatOfPoint3.java index 0c8374f250..3b50561e91 100644 --- a/modules/java/generator/src/java/core+MatOfPoint3.java +++ b/modules/java/generator/src/java/core+MatOfPoint3.java @@ -15,7 +15,7 @@ public class MatOfPoint3 extends Mat { protected MatOfPoint3(long addr) { super(addr); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } @@ -26,7 +26,7 @@ public class MatOfPoint3 extends Mat { public MatOfPoint3(Mat m) { super(m, Range.all()); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } diff --git a/modules/java/generator/src/java/core+MatOfPoint3f.java b/modules/java/generator/src/java/core+MatOfPoint3f.java index b0d50d4500..fc5fee436d 100644 --- a/modules/java/generator/src/java/core+MatOfPoint3f.java +++ b/modules/java/generator/src/java/core+MatOfPoint3f.java @@ -15,7 +15,7 @@ public class MatOfPoint3f extends Mat { protected MatOfPoint3f(long addr) { super(addr); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } @@ -26,7 +26,7 @@ public class MatOfPoint3f extends Mat { public MatOfPoint3f(Mat m) { super(m, Range.all()); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } diff --git a/modules/java/generator/src/java/core+MatOfRect.java b/modules/java/generator/src/java/core+MatOfRect.java index 3844d9dfbf..ec0fb01e4a 100644 --- a/modules/java/generator/src/java/core+MatOfRect.java +++ b/modules/java/generator/src/java/core+MatOfRect.java @@ -16,7 +16,7 @@ public class MatOfRect extends Mat { protected MatOfRect(long addr) { super(addr); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } @@ -27,7 +27,7 @@ public class MatOfRect extends Mat { public MatOfRect(Mat m) { super(m, Range.all()); if( !empty() && checkVector(_channels, _depth) < 0 ) - throw new IllegalArgumentException("Incomatible Mat"); + throw new IllegalArgumentException("Incompatible Mat"); //FIXME: do we need release() here? } diff --git a/modules/legacy/doc/expectation_maximization.rst b/modules/legacy/doc/expectation_maximization.rst index d97d152e7b..e3791cbe55 100644 --- a/modules/legacy/doc/expectation_maximization.rst +++ b/modules/legacy/doc/expectation_maximization.rst @@ -5,6 +5,12 @@ This section describes obsolete ``C`` interface of EM algorithm. Details of the .. highlight:: cpp +.. note:: + + * An example on using the Expectation Maximalization algorithm can be found at opencv_source_code/samples/cpp/em.cpp + + * (Python) An example using Expectation Maximalization for Gaussian Mixing can be found at opencv_source_code/samples/python2/gaussian_mix.py + CvEMParams ---------- diff --git a/modules/legacy/doc/feature_detection_and_description.rst b/modules/legacy/doc/feature_detection_and_description.rst index 222d7a03a6..3dc1ae5792 100644 --- a/modules/legacy/doc/feature_detection_and_description.rst +++ b/modules/legacy/doc/feature_detection_and_description.rst @@ -75,7 +75,9 @@ Class containing a base structure for ``RTreeClassifier``. :: void estimateQuantPercForPosteriors(float perc[2]); }; +.. note:: + * : PYTHON : An example using Randomized Tree training for letter recognition can be found at opencv_source_code/samples/python2/letter_recog.py RandomizedTree::train ------------------------- @@ -99,7 +101,9 @@ Trains a randomized tree using an input set of keypoints. :param num_quant_bits: Number of bits used for quantization. +.. note:: + * : An example on training a Random Tree Classifier for letter recognition can be found at opencv_source_code\samples\cpp\letter_recog.cpp RandomizedTree::read ------------------------ diff --git a/modules/legacy/src/precomp.cpp b/modules/legacy/src/precomp.cpp deleted file mode 100644 index a9477b85ba..0000000000 --- a/modules/legacy/src/precomp.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/*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 "precomp.hpp" diff --git a/modules/legacy/src/precomp.hpp b/modules/legacy/src/precomp.hpp index 48b9e4a230..383b694ba2 100644 --- a/modules/legacy/src/precomp.hpp +++ b/modules/legacy/src/precomp.hpp @@ -41,9 +41,7 @@ #ifndef __OPENCV_PRECOMP_H__ #define __OPENCV_PRECOMP_H__ -#ifdef HAVE_CVCONFIG_H #include "cvconfig.h" -#endif #include "opencv2/legacy/legacy.hpp" diff --git a/modules/legacy/test/test_precomp.cpp b/modules/legacy/test/test_precomp.cpp deleted file mode 100644 index 5956e13e3e..0000000000 --- a/modules/legacy/test/test_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "test_precomp.hpp" diff --git a/modules/ml/doc/k_nearest_neighbors.rst b/modules/ml/doc/k_nearest_neighbors.rst index 739f52dad8..6692417189 100644 --- a/modules/ml/doc/k_nearest_neighbors.rst +++ b/modules/ml/doc/k_nearest_neighbors.rst @@ -9,7 +9,13 @@ CvKNearest ---------- .. ocv:class:: CvKNearest : public CvStatModel -The class implements K-Nearest Neighbors model as described in the beginning of this section. +The class implements K-Nearest Neighbors model as described in the beginning of this section. + +.. note:: + + * (Python) An example of digit recognition using KNearest can be found at opencv_source/samples/python2/digits.py + * (Python) An example of grid search digit recognition using KNearest can be found at opencv_source/samples/python2/digits_adjust.py + * (Python) An example of video digit recognition using KNearest can be found at opencv_source/samples/python2/digits_video.py CvKNearest::CvKNearest ---------------------- diff --git a/modules/ml/doc/support_vector_machines.rst b/modules/ml/doc/support_vector_machines.rst index b0d23ae863..8c24e5f937 100644 --- a/modules/ml/doc/support_vector_machines.rst +++ b/modules/ml/doc/support_vector_machines.rst @@ -150,6 +150,12 @@ CvSVM Support Vector Machines. +.. note:: + + * (Python) An example of digit recognition using SVM can be found at opencv_source/samples/python2/digits.py + * (Python) An example of grid search digit recognition using SVM can be found at opencv_source/samples/python2/digits_adjust.py + * (Python) An example of video digit recognition using SVM can be found at opencv_source/samples/python2/digits_video.py + CvSVM::CvSVM ------------ Default and training constructors. diff --git a/modules/ml/src/precomp.cpp b/modules/ml/src/precomp.cpp deleted file mode 100644 index e540cc5e8a..0000000000 --- a/modules/ml/src/precomp.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "precomp.hpp" - -/* End of file. */ diff --git a/modules/ml/src/precomp.hpp b/modules/ml/src/precomp.hpp index 63002a8e85..b4ae21a55e 100644 --- a/modules/ml/src/precomp.hpp +++ b/modules/ml/src/precomp.hpp @@ -41,9 +41,7 @@ #ifndef __OPENCV_PRECOMP_H__ #define __OPENCV_PRECOMP_H__ -#ifdef HAVE_CVCONFIG_H #include "cvconfig.h" -#endif #include "opencv2/ml/ml.hpp" #include "opencv2/core/core_c.h" diff --git a/modules/ml/test/test_precomp.cpp b/modules/ml/test/test_precomp.cpp deleted file mode 100644 index 5956e13e3e..0000000000 --- a/modules/ml/test/test_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "test_precomp.hpp" diff --git a/modules/nonfree/doc/feature_detection.rst b/modules/nonfree/doc/feature_detection.rst index c7ccb74932..5c2b2a0786 100644 --- a/modules/nonfree/doc/feature_detection.rst +++ b/modules/nonfree/doc/feature_detection.rst @@ -75,6 +75,10 @@ SURF .. [Bay06] Bay, H. and Tuytelaars, T. and Van Gool, L. "SURF: Speeded Up Robust Features", 9th European Conference on Computer Vision, 2006 +.. note:: + + * An example using the SURF feature detector can be found at opencv_source_code/samples/cpp/generic_descriptor_match.cpp + * Another example using the SURF feature detector, extractor and matcher can be found at opencv_source_code/samples/cpp/matcher_simple.cpp SURF::SURF ---------- @@ -230,6 +234,9 @@ The class ``SURF_GPU`` uses some buffers and provides access to it. All buffers .. seealso:: :ocv:class:`SURF` +.. note:: + + * An example for using the SURF keypoint matcher on GPU can be found at opencv_source_code/samples/gpu/surf_keypoint_matcher.cpp ocl::SURF_OCL ------------- @@ -327,4 +334,8 @@ The ``descriptors`` matrix is :math:`\texttt{nFeatures} \times \texttt{descripto The class ``SURF_OCL`` uses some buffers and provides access to it. All buffers can be safely released between function calls. -.. seealso:: :ocv:class:`SURF` \ No newline at end of file +.. seealso:: :ocv:class:`SURF` + +.. note:: + + * OCL : An example of the SURF detector can be found at opencv_source_code/samples/ocl/surf_matcher.cpp \ No newline at end of file diff --git a/modules/nonfree/perf/perf_precomp.cpp b/modules/nonfree/perf/perf_precomp.cpp deleted file mode 100644 index 8552ac3d42..0000000000 --- a/modules/nonfree/perf/perf_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "perf_precomp.hpp" diff --git a/modules/nonfree/src/precomp.cpp b/modules/nonfree/src/precomp.cpp deleted file mode 100644 index 730edbb63d..0000000000 --- a/modules/nonfree/src/precomp.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "precomp.hpp" - -/* End of file. */ diff --git a/modules/nonfree/src/precomp.hpp b/modules/nonfree/src/precomp.hpp index 6c46114c76..2abe6038ac 100644 --- a/modules/nonfree/src/precomp.hpp +++ b/modules/nonfree/src/precomp.hpp @@ -43,9 +43,7 @@ #ifndef __OPENCV_PRECOMP_H__ #define __OPENCV_PRECOMP_H__ -#ifdef HAVE_CVCONFIG_H #include "cvconfig.h" -#endif #include "opencv2/opencv_modules.hpp" diff --git a/modules/nonfree/test/test_precomp.cpp b/modules/nonfree/test/test_precomp.cpp deleted file mode 100644 index 5956e13e3e..0000000000 --- a/modules/nonfree/test/test_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "test_precomp.hpp" diff --git a/modules/objdetect/doc/cascade_classification.rst b/modules/objdetect/doc/cascade_classification.rst index eb07a6c8f7..231a19344d 100644 --- a/modules/objdetect/doc/cascade_classification.rst +++ b/modules/objdetect/doc/cascade_classification.rst @@ -215,6 +215,10 @@ Detects objects of different sizes in the input image. The detected objects are The function is parallelized with the TBB library. +.. note:: + + * (Python) A face detection example using cascade classifiers can be found at opencv_source_code/samples/python2/facedetect.py + CascadeClassifier::setImage ------------------------------- diff --git a/modules/objdetect/include/opencv2/objdetect/objdetect.hpp b/modules/objdetect/include/opencv2/objdetect/objdetect.hpp index 8d7efb0ba4..d5d6f0b24d 100644 --- a/modules/objdetect/include/opencv2/objdetect/objdetect.hpp +++ b/modules/objdetect/include/opencv2/objdetect/objdetect.hpp @@ -192,12 +192,12 @@ typedef struct CvLSVMFilterObject{ // data type: STRUCT CvLatentSvmDetector // structure contains internal representation of trained Latent SVM detector -// num_filters - total number of filters (root plus part) in model -// num_components - number of components in model -// num_part_filters - array containing number of part filters for each component -// filters - root and part filters for all model components -// b - biases for all model components -// score_threshold - confidence level threshold +// num_filters - total number of filters (root plus part) in model +// num_components - number of components in model +// num_part_filters - array containing number of part filters for each component +// filters - root and part filters for all model components +// b - biases for all model components +// score_threshold - confidence level threshold typedef struct CvLatentSvmDetector { int num_filters; @@ -211,8 +211,8 @@ CvLatentSvmDetector; // data type: STRUCT CvObjectDetection // structure contains the bounding box and confidence level for detected object -// rect - bounding box for a detected object -// score - confidence level +// rect - bounding box for a detected object +// score - confidence level typedef struct CvObjectDetection { CvRect rect; @@ -228,7 +228,7 @@ typedef struct CvObjectDetection // API // CvLatentSvmDetector* cvLoadLatentSvmDetector(const char* filename); // INPUT -// filename - path to the file containing the parameters of +// filename - path to the file containing the parameters of - trained Latent SVM detector // OUTPUT // trained Latent SVM detector in internal representation @@ -241,7 +241,7 @@ CVAPI(CvLatentSvmDetector*) cvLoadLatentSvmDetector(const char* filename); // API // void cvReleaseLatentSvmDetector(CvLatentSvmDetector** detector); // INPUT -// detector - CvLatentSvmDetector structure to be released +// detector - CvLatentSvmDetector structure to be released // OUTPUT */ CVAPI(void) cvReleaseLatentSvmDetector(CvLatentSvmDetector** detector); @@ -252,16 +252,16 @@ CVAPI(void) cvReleaseLatentSvmDetector(CvLatentSvmDetector** detector); // // API // CvSeq* cvLatentSvmDetectObjects(const IplImage* image, -// CvLatentSvmDetector* detector, -// CvMemStorage* storage, -// float overlap_threshold = 0.5f, +// CvLatentSvmDetector* detector, +// CvMemStorage* storage, +// float overlap_threshold = 0.5f, // int numThreads = -1); // INPUT -// image - image to detect objects in -// detector - Latent SVM detector in internal representation -// storage - memory storage to store the resultant sequence -// of the object candidate rectangles -// overlap_threshold - threshold for the non-maximum suppression algorithm +// image - image to detect objects in +// detector - Latent SVM detector in internal representation +// storage - memory storage to store the resultant sequence +// of the object candidate rectangles +// overlap_threshold - threshold for the non-maximum suppression algorithm = 0.5f [here will be the reference to original paper] // OUTPUT // sequence of detected objects (bounding boxes and confidence levels stored in CvObjectDetection structures) @@ -327,6 +327,23 @@ private: vector classNames; }; +// class for grouping object candidates, detected by Cascade Classifier, HOG etc. +// instance of the class is to be passed to cv::partition (see cxoperations.hpp) +class CV_EXPORTS SimilarRects +{ +public: + SimilarRects(double _eps) : eps(_eps) {} + inline bool operator()(const Rect& r1, const Rect& r2) const + { + double delta = eps*(std::min(r1.width, r2.width) + std::min(r1.height, r2.height))*0.5; + return std::abs(r1.x - r2.x) <= delta && + std::abs(r1.y - r2.y) <= delta && + std::abs(r1.x + r1.width - r2.x - r2.width) <= delta && + std::abs(r1.y + r1.height - r2.y - r2.height) <= delta; + } + double eps; +}; + CV_EXPORTS void groupRectangles(CV_OUT CV_IN_OUT vector& rectList, int groupThreshold, double eps=0.2); CV_EXPORTS_W void groupRectangles(CV_OUT CV_IN_OUT vector& rectList, CV_OUT vector& weights, int groupThreshold, double eps=0.2); CV_EXPORTS void groupRectangles( vector& rectList, int groupThreshold, double eps, vector* weights, vector* levelWeights ); @@ -611,6 +628,7 @@ public: // read/parse Dalal's alt model file void readALTModel(std::string modelfile); + void groupRectangles(vector& rectList, vector& weights, int groupThreshold, double eps) const; }; diff --git a/modules/objdetect/perf/perf_precomp.cpp b/modules/objdetect/perf/perf_precomp.cpp deleted file mode 100644 index 8552ac3d42..0000000000 --- a/modules/objdetect/perf/perf_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "perf_precomp.hpp" diff --git a/modules/objdetect/src/cascadedetect.cpp b/modules/objdetect/src/cascadedetect.cpp index 9e78dce243..6c41655f14 100644 --- a/modules/objdetect/src/cascadedetect.cpp +++ b/modules/objdetect/src/cascadedetect.cpp @@ -114,24 +114,6 @@ struct Logger namespace cv { -// class for grouping object candidates, detected by Cascade Classifier, HOG etc. -// instance of the class is to be passed to cv::partition (see cxoperations.hpp) -class CV_EXPORTS SimilarRects -{ -public: - SimilarRects(double _eps) : eps(_eps) {} - inline bool operator()(const Rect& r1, const Rect& r2) const - { - double delta = eps*(std::min(r1.width, r2.width) + std::min(r1.height, r2.height))*0.5; - return std::abs(r1.x - r2.x) <= delta && - std::abs(r1.y - r2.y) <= delta && - std::abs(r1.x + r1.width - r2.x - r2.width) <= delta && - std::abs(r1.y + r1.height - r2.y - r2.height) <= delta; - } - double eps; -}; - - void groupRectangles(vector& rectList, int groupThreshold, double eps, vector* weights, vector* levelWeights) { if( groupThreshold <= 0 || rectList.empty() ) diff --git a/modules/objdetect/src/hog.cpp b/modules/objdetect/src/hog.cpp index 1eab434f66..7287d57ecc 100644 --- a/modules/objdetect/src/hog.cpp +++ b/modules/objdetect/src/hog.cpp @@ -1060,7 +1060,7 @@ void HOGDescriptor::detectMultiScale( } else { - groupRectangles(foundLocations, (int)finalThreshold, 0.2); + groupRectangles(foundLocations, foundWeights, (int)finalThreshold, 0.2); } } @@ -2634,4 +2634,82 @@ void HOGDescriptor::readALTModel(std::string modelfile) fclose(modelfl); } +void HOGDescriptor::groupRectangles(vector& rectList, vector& weights, int groupThreshold, double eps) const +{ + if( groupThreshold <= 0 || rectList.empty() ) + { + return; + } + + CV_Assert(rectList.size() == weights.size()); + + vector labels; + int nclasses = partition(rectList, labels, SimilarRects(eps)); + + vector > rrects(nclasses); + vector numInClass(nclasses, 0); + vector foundWeights(nclasses, DBL_MIN); + vector totalFactorsPerClass(nclasses, 1); + int i, j, nlabels = (int)labels.size(); + + for( i = 0; i < nlabels; i++ ) + { + int cls = labels[i]; + rrects[cls].x += rectList[i].x; + rrects[cls].y += rectList[i].y; + rrects[cls].width += rectList[i].width; + rrects[cls].height += rectList[i].height; + foundWeights[cls] = max(foundWeights[cls], weights[i]); + numInClass[cls]++; + } + + for( i = 0; i < nclasses; i++ ) + { + // find the average of all ROI in the cluster + cv::Rect_ r = rrects[i]; + double s = 1.0/numInClass[i]; + rrects[i] = cv::Rect_(cv::saturate_cast(r.x*s), + cv::saturate_cast(r.y*s), + cv::saturate_cast(r.width*s), + cv::saturate_cast(r.height*s)); + } + + rectList.clear(); + weights.clear(); + + for( i = 0; i < nclasses; i++ ) + { + cv::Rect r1 = rrects[i]; + int n1 = numInClass[i]; + double w1 = foundWeights[i]; + if( n1 <= groupThreshold ) + continue; + // filter out small rectangles inside large rectangles + for( j = 0; j < nclasses; j++ ) + { + int n2 = numInClass[j]; + + if( j == i || n2 <= groupThreshold ) + continue; + + cv::Rect r2 = rrects[j]; + + int dx = cv::saturate_cast( r2.width * eps ); + int dy = cv::saturate_cast( r2.height * eps ); + + if( r1.x >= r2.x - dx && + r1.y >= r2.y - dy && + r1.x + r1.width <= r2.x + r2.width + dx && + r1.y + r1.height <= r2.y + r2.height + dy && + (n2 > std::max(3, n1) || n1 < 3) ) + break; + } + + if( j == nclasses ) + { + rectList.push_back(r1); + weights.push_back(w1); + } + } +} } diff --git a/modules/objdetect/src/precomp.cpp b/modules/objdetect/src/precomp.cpp deleted file mode 100644 index 3e0ec42de9..0000000000 --- a/modules/objdetect/src/precomp.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/*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 "precomp.hpp" - -/* End of file. */ diff --git a/modules/objdetect/src/precomp.hpp b/modules/objdetect/src/precomp.hpp index 560ed45a20..37f3673a4a 100644 --- a/modules/objdetect/src/precomp.hpp +++ b/modules/objdetect/src/precomp.hpp @@ -43,9 +43,7 @@ #ifndef __OPENCV_PRECOMP_H__ #define __OPENCV_PRECOMP_H__ -#ifdef HAVE_CVCONFIG_H #include "cvconfig.h" -#endif #include "opencv2/objdetect/objdetect.hpp" #include "opencv2/imgproc/imgproc.hpp" diff --git a/modules/objdetect/test/test_latentsvmdetector.cpp b/modules/objdetect/test/test_latentsvmdetector.cpp index b595d7ac51..1efa55f50f 100644 --- a/modules/objdetect/test/test_latentsvmdetector.cpp +++ b/modules/objdetect/test/test_latentsvmdetector.cpp @@ -44,9 +44,7 @@ #include -#ifdef HAVE_CVCONFIG_H #include "cvconfig.h" -#endif #ifdef HAVE_TBB #include "tbb/task_scheduler_init.h" diff --git a/modules/objdetect/test/test_precomp.cpp b/modules/objdetect/test/test_precomp.cpp deleted file mode 100644 index 5956e13e3e..0000000000 --- a/modules/objdetect/test/test_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "test_precomp.hpp" diff --git a/modules/ocl/doc/feature_detection_and_description.rst b/modules/ocl/doc/feature_detection_and_description.rst index d4fd6e65fa..f654124732 100644 --- a/modules/ocl/doc/feature_detection_and_description.rst +++ b/modules/ocl/doc/feature_detection_and_description.rst @@ -363,7 +363,9 @@ The class implements Histogram of Oriented Gradients ([Dalal2005]_) object detec Interfaces of all methods are kept similar to the ``CPU HOG`` descriptor and detector analogues as much as possible. +.. note:: + (Ocl) An example using the HOG descriptor can be found at opencv_source_code/samples/ocl/hog.cpp ocl::HOGDescriptor::HOGDescriptor ------------------------------------- diff --git a/modules/ocl/doc/image_processing.rst b/modules/ocl/doc/image_processing.rst index 94712e091d..de3669ca34 100644 --- a/modules/ocl/doc/image_processing.rst +++ b/modules/ocl/doc/image_processing.rst @@ -257,7 +257,10 @@ The class can calculate an optical flow for a sparse feature set or dense optica .. seealso:: :ocv:func:`calcOpticalFlowPyrLK` +.. note:: + (Ocl) An example the Lucas Kanade optical flow pyramid method can be found at opencv_source_code/samples/ocl/pyrlk_optical_flow.cpp + (Ocl) An example for square detection can be found at opencv_source_code/samples/ocl/squares.cpp ocl::PyrLKOpticalFlow::sparse ----------------------------- diff --git a/modules/ocl/doc/object_detection.rst b/modules/ocl/doc/object_detection.rst index 17eb62d0e5..36f3e46cf8 100644 --- a/modules/ocl/doc/object_detection.rst +++ b/modules/ocl/doc/object_detection.rst @@ -20,6 +20,10 @@ Cascade classifier class used for object detection. Supports HAAR cascade classi CvSize maxSize = cvSize(0, 0)); }; +.. note:: + + (Ocl) A face detection example using cascade classifiers can be found at opencv_source_code/samples/ocl/facedetect.cpp + ocl::OclCascadeClassifier::oclHaarDetectObjects ------------------------------------------------------ Returns the detected objects by a list of rectangles diff --git a/modules/ocl/doc/operations_on_matrices.rst b/modules/ocl/doc/operations_on_matrices.rst index 145659b991..1500ea52ad 100644 --- a/modules/ocl/doc/operations_on_matrices.rst +++ b/modules/ocl/doc/operations_on_matrices.rst @@ -481,4 +481,40 @@ Performs generalized matrix multiplication. * **GEMM_1_T** transpose ``src1`` * **GEMM_2_T** transpose ``src2`` -.. seealso:: :ocv:func:`gemm` \ No newline at end of file +.. seealso:: :ocv:func:`gemm` + +ocl::sortByKey +------------------ +Returns void + +.. ocv:function:: void ocl::sortByKey(oclMat& keys, oclMat& values, int method, bool isGreaterThan = false) + + :param keys: The keys to be used as sorting indices. + + :param values: The array of values. + + :param isGreaterThan: Determine sorting order. + + :param method: supported sorting methods: + * **SORT_BITONIC** bitonic sort, only support power-of-2 buffer size + * **SORT_SELECTION** selection sort, currently cannot sort duplicate keys + * **SORT_MERGE** merge sort + * **SORT_RADIX** radix sort, only support signed int/float keys(``CV_32S``/``CV_32F``) + +Returns the sorted result of all the elements in values based on equivalent keys. + +The element unit in the values to be sorted is determined from the data type, +i.e., a ``CV_32FC2`` input ``{a1a2, b1b2}`` will be considered as two elements, regardless its matrix dimension. + +Both keys and values will be sorted inplace. + +Keys needs to be a **single** channel `oclMat`. + +Example:: + input - + keys = {2, 3, 1} (CV_8UC1) + values = {10,5, 4,3, 6,2} (CV_8UC2) + sortByKey(keys, values, SORT_SELECTION, false); + output - + keys = {1, 2, 3} (CV_8UC1) + values = {6,2, 10,5, 4,3} (CV_8UC2) diff --git a/modules/ocl/include/opencv2/ocl/ocl.hpp b/modules/ocl/include/opencv2/ocl/ocl.hpp index fa11177c47..3c83129881 100644 --- a/modules/ocl/include/opencv2/ocl/ocl.hpp +++ b/modules/ocl/include/opencv2/ocl/ocl.hpp @@ -834,6 +834,18 @@ namespace cv CV_EXPORTS void cornerMinEigenVal_dxdy(const oclMat &src, oclMat &dst, oclMat &Dx, oclMat &Dy, int blockSize, int ksize, int bordertype = cv::BORDER_DEFAULT); + /////////////////////////////////// ML /////////////////////////////////////////// + + //! Compute closest centers for each lines in source and lable it after center's index + // supports CV_32FC1/CV_32FC2/CV_32FC4 data type + CV_EXPORTS void distanceToCenters(oclMat &dists, oclMat &labels, const oclMat &src, const oclMat ¢ers); + + //!Does k-means procedure on GPU + // supports CV_32FC1/CV_32FC2/CV_32FC4 data type + CV_EXPORTS double kmeans(const oclMat &src, int K, oclMat &bestLabels, + TermCriteria criteria, int attemps, int flags, oclMat ¢ers); + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////CascadeClassifier////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -1661,6 +1673,31 @@ namespace cv oclMat diff_buf; oclMat norm_buf; }; + // current supported sorting methods + enum + { + SORT_BITONIC, // only support power-of-2 buffer size + SORT_SELECTION, // cannot sort duplicate keys + SORT_MERGE, + SORT_RADIX // only support signed int/float keys(CV_32S/CV_32F) + }; + //! Returns the sorted result of all the elements in input based on equivalent keys. + // + // The element unit in the values to be sorted is determined from the data type, + // i.e., a CV_32FC2 input {a1a2, b1b2} will be considered as two elements, regardless its + // matrix dimension. + // both keys and values will be sorted inplace + // Key needs to be single channel oclMat. + // + // Example: + // input - + // keys = {2, 3, 1} (CV_8UC1) + // values = {10,5, 4,3, 6,2} (CV_8UC2) + // sortByKey(keys, values, SORT_SELECTION, false); + // output - + // keys = {1, 2, 3} (CV_8UC1) + // values = {6,2, 10,5, 4,3} (CV_8UC2) + void CV_EXPORTS sortByKey(oclMat& keys, oclMat& values, int method, bool isGreaterThan = false); } } #if defined _MSC_VER && _MSC_VER >= 1200 diff --git a/modules/ocl/perf/main.cpp b/modules/ocl/perf/main.cpp index bd2a4ec4b6..0875903413 100644 --- a/modules/ocl/perf/main.cpp +++ b/modules/ocl/perf/main.cpp @@ -40,7 +40,7 @@ // //M*/ -#include "precomp.hpp" +#include "perf_precomp.hpp" int main(int argc, const char *argv[]) { diff --git a/modules/ocl/perf/perf_arithm.cpp b/modules/ocl/perf/perf_arithm.cpp index 3ef0634e70..29ff0d802a 100644 --- a/modules/ocl/perf/perf_arithm.cpp +++ b/modules/ocl/perf/perf_arithm.cpp @@ -44,7 +44,7 @@ // //M*/ -#include "precomp.hpp" +#include "perf_precomp.hpp" ///////////// Lut //////////////////////// PERFTEST(lut) { diff --git a/modules/ocl/perf/perf_blend.cpp b/modules/ocl/perf/perf_blend.cpp index 8ebb6482ba..22139779d4 100644 --- a/modules/ocl/perf/perf_blend.cpp +++ b/modules/ocl/perf/perf_blend.cpp @@ -44,7 +44,7 @@ // //M*/ -#include "precomp.hpp" +#include "perf_precomp.hpp" ///////////// blend //////////////////////// template void blendLinearGold(const cv::Mat &img1, const cv::Mat &img2, const cv::Mat &weights1, const cv::Mat &weights2, cv::Mat &result_gold) diff --git a/modules/ocl/perf/perf_brute_force_matcher.cpp b/modules/ocl/perf/perf_brute_force_matcher.cpp index 406b46a324..c481766035 100644 --- a/modules/ocl/perf/perf_brute_force_matcher.cpp +++ b/modules/ocl/perf/perf_brute_force_matcher.cpp @@ -43,7 +43,7 @@ // the use of this software, even if advised of the possibility of such damage. // //M*/ -#include "precomp.hpp" +#include "perf_precomp.hpp" //////////////////// BruteForceMatch ///////////////// PERFTEST(BruteForceMatcher) diff --git a/modules/ocl/perf/perf_calib3d.cpp b/modules/ocl/perf/perf_calib3d.cpp index f998ddf0f3..e0622aa56b 100644 --- a/modules/ocl/perf/perf_calib3d.cpp +++ b/modules/ocl/perf/perf_calib3d.cpp @@ -44,7 +44,7 @@ // //M*/ -#include "precomp.hpp" +#include "perf_precomp.hpp" ///////////// StereoMatchBM //////////////////////// PERFTEST(StereoMatchBM) { diff --git a/modules/ocl/perf/perf_canny.cpp b/modules/ocl/perf/perf_canny.cpp index cb23d7ad28..7ea0ce652a 100644 --- a/modules/ocl/perf/perf_canny.cpp +++ b/modules/ocl/perf/perf_canny.cpp @@ -43,7 +43,7 @@ // the use of this software, even if advised of the possibility of such damage. // //M*/ -#include "precomp.hpp" +#include "perf_precomp.hpp" ///////////// Canny //////////////////////// PERFTEST(Canny) diff --git a/modules/ocl/perf/perf_color.cpp b/modules/ocl/perf/perf_color.cpp index daf1cfdc9c..4bd5fa5d44 100644 --- a/modules/ocl/perf/perf_color.cpp +++ b/modules/ocl/perf/perf_color.cpp @@ -43,7 +43,7 @@ // the use of this software, even if advised of the possibility of such damage. // //M*/ -#include "precomp.hpp" +#include "perf_precomp.hpp" ///////////// cvtColor//////////////////////// PERFTEST(cvtColor) diff --git a/modules/ocl/perf/perf_fft.cpp b/modules/ocl/perf/perf_fft.cpp index 6e0be3f19d..7073eb691d 100644 --- a/modules/ocl/perf/perf_fft.cpp +++ b/modules/ocl/perf/perf_fft.cpp @@ -43,7 +43,7 @@ // the use of this software, even if advised of the possibility of such damage. // //M*/ -#include "precomp.hpp" +#include "perf_precomp.hpp" ///////////// dft //////////////////////// PERFTEST(dft) diff --git a/modules/ocl/perf/perf_filters.cpp b/modules/ocl/perf/perf_filters.cpp index e988ce09d6..be288b444b 100644 --- a/modules/ocl/perf/perf_filters.cpp +++ b/modules/ocl/perf/perf_filters.cpp @@ -43,7 +43,7 @@ // the use of this software, even if advised of the possibility of such damage. // //M*/ -#include "precomp.hpp" +#include "perf_precomp.hpp" ///////////// Blur//////////////////////// PERFTEST(Blur) diff --git a/modules/ocl/perf/perf_gemm.cpp b/modules/ocl/perf/perf_gemm.cpp index f197c5f5a0..abaeda363c 100644 --- a/modules/ocl/perf/perf_gemm.cpp +++ b/modules/ocl/perf/perf_gemm.cpp @@ -43,7 +43,7 @@ // the use of this software, even if advised of the possibility of such damage. // //M*/ -#include "precomp.hpp" +#include "perf_precomp.hpp" ///////////// gemm //////////////////////// PERFTEST(gemm) diff --git a/modules/ocl/perf/perf_gftt.cpp b/modules/ocl/perf/perf_gftt.cpp new file mode 100644 index 0000000000..9e809e4435 --- /dev/null +++ b/modules/ocl/perf/perf_gftt.cpp @@ -0,0 +1,101 @@ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved. +// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// @Authors +// Peng Xiao, pengxiao@outlook.com +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other oclMaterials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors as is and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + + +#include "perf_precomp.hpp" + +///////////// GoodFeaturesToTrack //////////////////////// +PERFTEST(GoodFeaturesToTrack) +{ + using namespace cv; + + int maxCorners = 2000; + double qualityLevel = 0.01; + + std::string images[] = { "rubberwhale1.png", "aloeL.jpg" }; + + std::vector pts_gold, pts_ocl; + + for(size_t imgIdx = 0; imgIdx < (sizeof(images)/sizeof(std::string)); ++imgIdx) + { + Mat frame = imread(abspath(images[imgIdx]), IMREAD_GRAYSCALE); + CV_Assert(!frame.empty()); + + for(float minDistance = 0; minDistance < 4; minDistance += 3.0) + { + SUBTEST << "image = " << images[imgIdx] << "; "; + SUBTEST << "minDistance = " << minDistance << "; "; + + cv::goodFeaturesToTrack(frame, pts_gold, maxCorners, qualityLevel, minDistance); + + CPU_ON; + cv::goodFeaturesToTrack(frame, pts_gold, maxCorners, qualityLevel, minDistance); + CPU_OFF; + + cv::ocl::GoodFeaturesToTrackDetector_OCL detector(maxCorners, qualityLevel, minDistance); + + ocl::oclMat frame_ocl(frame), pts_oclmat; + + WARMUP_ON; + detector(frame_ocl, pts_oclmat); + WARMUP_OFF; + + detector.downloadPoints(pts_oclmat, pts_ocl); + + double diff = abs(static_cast(pts_gold.size() - pts_ocl.size())); + TestSystem::instance().setAccurate(diff == 0.0, diff); + + GPU_ON; + detector(frame_ocl, pts_oclmat); + GPU_OFF; + + GPU_FULL_ON; + frame_ocl.upload(frame); + detector(frame_ocl, pts_oclmat); + detector.downloadPoints(pts_oclmat, pts_ocl); + GPU_FULL_OFF; + } + } +} diff --git a/modules/ocl/perf/perf_haar.cpp b/modules/ocl/perf/perf_haar.cpp index 72f01dc935..26bed5ebd9 100644 --- a/modules/ocl/perf/perf_haar.cpp +++ b/modules/ocl/perf/perf_haar.cpp @@ -43,7 +43,7 @@ // the use of this software, even if advised of the possibility of such damage. // //M*/ -#include "precomp.hpp" +#include "perf_precomp.hpp" ///////////// Haar //////////////////////// namespace cv diff --git a/modules/ocl/perf/perf_hog.cpp b/modules/ocl/perf/perf_hog.cpp index 7daa61396c..0f05581295 100644 --- a/modules/ocl/perf/perf_hog.cpp +++ b/modules/ocl/perf/perf_hog.cpp @@ -43,7 +43,7 @@ // the use of this software, even if advised of the possibility of such damage. // //M*/ -#include "precomp.hpp" +#include "perf_precomp.hpp" ///////////// HOG//////////////////////// diff --git a/modules/ocl/perf/perf_imgproc.cpp b/modules/ocl/perf/perf_imgproc.cpp index ade5019147..582853d05b 100644 --- a/modules/ocl/perf/perf_imgproc.cpp +++ b/modules/ocl/perf/perf_imgproc.cpp @@ -43,7 +43,7 @@ // the use of this software, even if advised of the possibility of such damage. // //M*/ -#include "precomp.hpp" +#include "perf_precomp.hpp" ///////////// equalizeHist //////////////////////// PERFTEST(equalizeHist) diff --git a/modules/ocl/perf/perf_match_template.cpp b/modules/ocl/perf/perf_match_template.cpp index 5da15aaf64..8aafc98968 100644 --- a/modules/ocl/perf/perf_match_template.cpp +++ b/modules/ocl/perf/perf_match_template.cpp @@ -43,7 +43,7 @@ // the use of this software, even if advised of the possibility of such damage. // //M*/ -#include "precomp.hpp" +#include "perf_precomp.hpp" /////////// matchTemplate //////////////////////// //void InitMatchTemplate() diff --git a/modules/ocl/perf/perf_matrix_operation.cpp b/modules/ocl/perf/perf_matrix_operation.cpp index b724cdbe64..bb407c9afe 100644 --- a/modules/ocl/perf/perf_matrix_operation.cpp +++ b/modules/ocl/perf/perf_matrix_operation.cpp @@ -43,7 +43,7 @@ // the use of this software, even if advised of the possibility of such damage. // //M*/ -#include "precomp.hpp" +#include "perf_precomp.hpp" ///////////// ConvertTo//////////////////////// PERFTEST(ConvertTo) diff --git a/modules/ocl/perf/perf_moments.cpp b/modules/ocl/perf/perf_moments.cpp index 7fa3948dec..a1515b879b 100644 --- a/modules/ocl/perf/perf_moments.cpp +++ b/modules/ocl/perf/perf_moments.cpp @@ -43,7 +43,7 @@ // the use of this software, even if advised of the possibility of such damage. // //M*/ -#include "precomp.hpp" +#include "perf_precomp.hpp" ///////////// Moments //////////////////////// PERFTEST(Moments) { diff --git a/modules/ocl/perf/perf_norm.cpp b/modules/ocl/perf/perf_norm.cpp index 1d986c8e49..fec8d73791 100644 --- a/modules/ocl/perf/perf_norm.cpp +++ b/modules/ocl/perf/perf_norm.cpp @@ -43,7 +43,7 @@ // the use of this software, even if advised of the possibility of such damage. // //M*/ -#include "precomp.hpp" +#include "perf_precomp.hpp" ///////////// norm//////////////////////// PERFTEST(norm) diff --git a/modules/ocl/perf/perf_opticalflow.cpp b/modules/ocl/perf/perf_opticalflow.cpp index 936d7a77fc..a6724c8123 100644 --- a/modules/ocl/perf/perf_opticalflow.cpp +++ b/modules/ocl/perf/perf_opticalflow.cpp @@ -43,13 +43,13 @@ // the use of this software, even if advised of the possibility of such damage. // //M*/ -#include "precomp.hpp" +#include "perf_precomp.hpp" ///////////// PyrLKOpticalFlow //////////////////////// PERFTEST(PyrLKOpticalFlow) { - std::string images1[] = {"rubberwhale1.png", "basketball1.png"}; - std::string images2[] = {"rubberwhale2.png", "basketball2.png"}; + std::string images1[] = {"rubberwhale1.png", "aloeL.jpg"}; + std::string images2[] = {"rubberwhale2.png", "aloeR.jpg"}; for (size_t i = 0; i < sizeof(images1) / sizeof(std::string); i++) { diff --git a/modules/ocl/perf/precomp.cpp b/modules/ocl/perf/perf_precomp.cpp similarity index 99% rename from modules/ocl/perf/precomp.cpp rename to modules/ocl/perf/perf_precomp.cpp index dd3b5e4ea1..2a49eb20e8 100644 --- a/modules/ocl/perf/precomp.cpp +++ b/modules/ocl/perf/perf_precomp.cpp @@ -40,7 +40,7 @@ // //M*/ -#include "precomp.hpp" +#include "perf_precomp.hpp" #if GTEST_OS_WINDOWS #ifndef NOMINMAX #define NOMINMAX diff --git a/modules/ocl/perf/precomp.hpp b/modules/ocl/perf/perf_precomp.hpp similarity index 98% rename from modules/ocl/perf/precomp.hpp rename to modules/ocl/perf/perf_precomp.hpp index 97e3d7e5c6..2df1b2c8f3 100644 --- a/modules/ocl/perf/precomp.hpp +++ b/modules/ocl/perf/perf_precomp.hpp @@ -40,6 +40,9 @@ // //M*/ +#ifndef __OPENCV_PERF_PRECOMP_HPP__ +#define __OPENCV_PERF_PRECOMP_HPP__ + #include #include #include @@ -99,7 +102,7 @@ int EeceptDoubleEQ(T1 expected, T1 actual) testing::internal::Double lhs(expected); testing::internal::Double rhs(actual); - if (lhs.AlmostEquals(rhs)) + if (lhs.AlmostEquals(rhs)) { return 1; } @@ -352,7 +355,7 @@ public: if(accurate_diff_ <= eps) is_accurate_ = 1; else - is_accurate_ = 0; + is_accurate_ = 0; } std::stringstream &getCurSubtestDescription() @@ -369,7 +372,7 @@ private: speedup_full_faster_count_(0), speedup_full_slower_count_(0), speedup_full_equal_count_(0), is_list_mode_(false), num_iters_(10), cpu_num_iters_(2), gpu_warmup_iters_(1), cur_iter_idx_(0), cur_warmup_idx_(0), - record_(0), recordname_("performance"), itname_changed_(true), + record_(0), recordname_("performance"), itname_changed_(true), is_accurate_(-1), accurate_diff_(0.) { cpu_times_.reserve(num_iters_); @@ -506,3 +509,5 @@ struct name##_test: Runnable { \ #define WARMUP_OFF \ ocl::finish();\ } TestSystem::instance().warmupComplete() + +#endif diff --git a/modules/ocl/perf/perf_pyramid.cpp b/modules/ocl/perf/perf_pyramid.cpp index 3b96251e5d..b98f531b5e 100644 --- a/modules/ocl/perf/perf_pyramid.cpp +++ b/modules/ocl/perf/perf_pyramid.cpp @@ -43,7 +43,7 @@ // the use of this software, even if advised of the possibility of such damage. // //M*/ -#include "precomp.hpp" +#include "perf_precomp.hpp" ///////////// pyrDown ////////////////////// PERFTEST(pyrDown) diff --git a/modules/ocl/perf/perf_split_merge.cpp b/modules/ocl/perf/perf_split_merge.cpp index 0fafd14aba..cbe817faff 100644 --- a/modules/ocl/perf/perf_split_merge.cpp +++ b/modules/ocl/perf/perf_split_merge.cpp @@ -43,7 +43,7 @@ // the use of this software, even if advised of the possibility of such damage. // //M*/ -#include "precomp.hpp" +#include "perf_precomp.hpp" ///////////// Merge//////////////////////// PERFTEST(Merge) diff --git a/modules/ocl/src/color.cpp b/modules/ocl/src/color.cpp index e14bd27569..493dbc33c4 100644 --- a/modules/ocl/src/color.cpp +++ b/modules/ocl/src/color.cpp @@ -213,7 +213,7 @@ void cvtColor_caller(const oclMat &src, oclMat &dst, int code, int dcn) case CV_RGB2YUV: { CV_Assert(scn == 3 || scn == 4); - bidx = code == CV_BGR2YUV ? 0 : 2; + bidx = code == CV_RGB2YUV ? 0 : 2; dst.create(sz, CV_MAKETYPE(depth, 3)); RGB2YUV_caller(src, dst, bidx); break; @@ -222,7 +222,7 @@ void cvtColor_caller(const oclMat &src, oclMat &dst, int code, int dcn) case CV_YUV2RGB: { CV_Assert(scn == 3 || scn == 4); - bidx = code == CV_YUV2BGR ? 0 : 2; + bidx = code == CV_YUV2RGB ? 0 : 2; dst.create(sz, CV_MAKETYPE(depth, 3)); YUV2RGB_caller(src, dst, bidx); break; diff --git a/modules/ocl/src/gfft.cpp b/modules/ocl/src/gftt.cpp similarity index 97% rename from modules/ocl/src/gfft.cpp rename to modules/ocl/src/gftt.cpp index 7fd5e3a174..06844177a9 100644 --- a/modules/ocl/src/gfft.cpp +++ b/modules/ocl/src/gftt.cpp @@ -55,7 +55,7 @@ namespace cv namespace ocl { ///////////////////////////OpenCL kernel strings/////////////////////////// - extern const char *imgproc_gfft; + extern const char *imgproc_gftt; } } @@ -133,7 +133,7 @@ struct Sorter for(int passOfStage = 0; passOfStage < stage + 1; ++passOfStage) { args[4] = std::make_pair(sizeof(cl_int), (void *)&passOfStage); - openCLExecuteKernel(cxt, &imgproc_gfft, kernelname, globalThreads, localThreads, args, -1, -1); + openCLExecuteKernel(cxt, &imgproc_gftt, kernelname, globalThreads, localThreads, args, -1, -1); } } } @@ -160,12 +160,12 @@ struct Sorter args.push_back( std::make_pair( sizeof(cl_int), (void*)&count) ); args.push_back( std::make_pair( lds_size, (void*)NULL) ); - openCLExecuteKernel(cxt, &imgproc_gfft, kernelname, globalThreads, localThreads, args, -1, -1); + openCLExecuteKernel(cxt, &imgproc_gftt, kernelname, globalThreads, localThreads, args, -1, -1); //final kernelname = "sortCorners_selectionSortFinal"; args.pop_back(); - openCLExecuteKernel(cxt, &imgproc_gfft, kernelname, globalThreads, localThreads, args, -1, -1); + openCLExecuteKernel(cxt, &imgproc_gftt, kernelname, globalThreads, localThreads, args, -1, -1); } }; @@ -201,7 +201,7 @@ int findCorners_caller( size_t localThreads[3] = {16, 16, 1}; const char * opt = mask.empty() ? "" : "-D WITH_MASK"; - openCLExecuteKernel(cxt, &imgproc_gfft, kernelname, globalThreads, localThreads, args, -1, -1, opt); + openCLExecuteKernel(cxt, &imgproc_gftt, kernelname, globalThreads, localThreads, args, -1, -1, opt); return std::min(Mat(g_counter).at(0), max_count); } }//unnamed namespace diff --git a/modules/ocl/src/hog.cpp b/modules/ocl/src/hog.cpp index 412afee8b8..c7ac4098f5 100644 --- a/modules/ocl/src/hog.cpp +++ b/modules/ocl/src/hog.cpp @@ -56,98 +56,6 @@ using namespace std; static oclMat gauss_w_lut; static bool hog_device_cpu; -/* pre-compute gaussian and interp_weight lookup tables if sigma is 4.0f */ -static const float gaussian_interp_lut[] = -{ - /* gaussian lut */ - 0.01831564f, 0.02926831f, 0.04393693f, 0.06196101f, 0.08208500f, 0.10215643f, - 0.11943297f, 0.13117145f, 0.13533528f, 0.13117145f, 0.11943297f, 0.10215643f, - 0.08208500f, 0.06196101f, 0.04393693f, 0.02926831f, 0.02926831f, 0.04677062f, - 0.07021102f, 0.09901341f, 0.13117145f, 0.16324551f, 0.19085334f, 0.20961139f, - 0.21626517f, 0.20961139f, 0.19085334f, 0.16324551f, 0.13117145f, 0.09901341f, - 0.07021102f, 0.04677062f, 0.04393693f, 0.07021102f, 0.10539922f, 0.14863673f, - 0.19691168f, 0.24506053f, 0.28650481f, 0.31466395f, 0.32465246f, 0.31466395f, - 0.28650481f, 0.24506053f, 0.19691168f, 0.14863673f, 0.10539922f, 0.07021102f, - 0.06196101f, 0.09901341f, 0.14863673f, 0.20961139f, 0.27768996f, 0.34559074f, - 0.40403652f, 0.44374731f, 0.45783335f, 0.44374731f, 0.40403652f, 0.34559074f, - 0.27768996f, 0.20961139f, 0.14863673f, 0.09901341f, 0.08208500f, 0.13117145f, - 0.19691168f, 0.27768996f, 0.36787945f, 0.45783335f, 0.53526145f, 0.58786964f, - 0.60653067f, 0.58786964f, 0.53526145f, 0.45783335f, 0.36787945f, 0.27768996f, - 0.19691168f, 0.13117145f, 0.10215643f, 0.16324551f, 0.24506053f, 0.34559074f, - 0.45783335f, 0.56978285f, 0.66614360f, 0.73161560f, 0.75483960f, 0.73161560f, - 0.66614360f, 0.56978285f, 0.45783335f, 0.34559074f, 0.24506053f, 0.16324551f, - 0.11943297f, 0.19085334f, 0.28650481f, 0.40403652f, 0.53526145f, 0.66614360f, - 0.77880079f, 0.85534531f, 0.88249689f, 0.85534531f, 0.77880079f, 0.66614360f, - 0.53526145f, 0.40403652f, 0.28650481f, 0.19085334f, 0.13117145f, 0.20961139f, - 0.31466395f, 0.44374731f, 0.58786964f, 0.73161560f, 0.85534531f, 0.93941307f, - 0.96923321f, 0.93941307f, 0.85534531f, 0.73161560f, 0.58786964f, 0.44374731f, - 0.31466395f, 0.20961139f, 0.13533528f, 0.21626517f, 0.32465246f, 0.45783335f, - 0.60653067f, 0.75483960f, 0.88249689f, 0.96923321f, 1.00000000f, 0.96923321f, - 0.88249689f, 0.75483960f, 0.60653067f, 0.45783335f, 0.32465246f, 0.21626517f, - 0.13117145f, 0.20961139f, 0.31466395f, 0.44374731f, 0.58786964f, 0.73161560f, - 0.85534531f, 0.93941307f, 0.96923321f, 0.93941307f, 0.85534531f, 0.73161560f, - 0.58786964f, 0.44374731f, 0.31466395f, 0.20961139f, 0.11943297f, 0.19085334f, - 0.28650481f, 0.40403652f, 0.53526145f, 0.66614360f, 0.77880079f, 0.85534531f, - 0.88249689f, 0.85534531f, 0.77880079f, 0.66614360f, 0.53526145f, 0.40403652f, - 0.28650481f, 0.19085334f, 0.10215643f, 0.16324551f, 0.24506053f, 0.34559074f, - 0.45783335f, 0.56978285f, 0.66614360f, 0.73161560f, 0.75483960f, 0.73161560f, - 0.66614360f, 0.56978285f, 0.45783335f, 0.34559074f, 0.24506053f, 0.16324551f, - 0.08208500f, 0.13117145f, 0.19691168f, 0.27768996f, 0.36787945f, 0.45783335f, - 0.53526145f, 0.58786964f, 0.60653067f, 0.58786964f, 0.53526145f, 0.45783335f, - 0.36787945f, 0.27768996f, 0.19691168f, 0.13117145f, 0.06196101f, 0.09901341f, - 0.14863673f, 0.20961139f, 0.27768996f, 0.34559074f, 0.40403652f, 0.44374731f, - 0.45783335f, 0.44374731f, 0.40403652f, 0.34559074f, 0.27768996f, 0.20961139f, - 0.14863673f, 0.09901341f, 0.04393693f, 0.07021102f, 0.10539922f, 0.14863673f, - 0.19691168f, 0.24506053f, 0.28650481f, 0.31466395f, 0.32465246f, 0.31466395f, - 0.28650481f, 0.24506053f, 0.19691168f, 0.14863673f, 0.10539922f, 0.07021102f, - 0.02926831f, 0.04677062f, 0.07021102f, 0.09901341f, 0.13117145f, 0.16324551f, - 0.19085334f, 0.20961139f, 0.21626517f, 0.20961139f, 0.19085334f, 0.16324551f, - 0.13117145f, 0.09901341f, 0.07021102f, 0.04677062f, - /* interp_weight lut */ - 0.00390625f, 0.01171875f, 0.01953125f, 0.02734375f, 0.03515625f, 0.04296875f, - 0.05078125f, 0.05859375f, 0.05859375f, 0.05078125f, 0.04296875f, 0.03515625f, - 0.02734375f, 0.01953125f, 0.01171875f, 0.00390625f, 0.01171875f, 0.03515625f, - 0.05859375f, 0.08203125f, 0.10546875f, 0.12890625f, 0.15234375f, 0.17578125f, - 0.17578125f, 0.15234375f, 0.12890625f, 0.10546875f, 0.08203125f, 0.05859375f, - 0.03515625f, 0.01171875f, 0.01953125f, 0.05859375f, 0.09765625f, 0.13671875f, - 0.17578125f, 0.21484375f, 0.25390625f, 0.29296875f, 0.29296875f, 0.25390625f, - 0.21484375f, 0.17578125f, 0.13671875f, 0.09765625f, 0.05859375f, 0.01953125f, - 0.02734375f, 0.08203125f, 0.13671875f, 0.19140625f, 0.24609375f, 0.30078125f, - 0.35546875f, 0.41015625f, 0.41015625f, 0.35546875f, 0.30078125f, 0.24609375f, - 0.19140625f, 0.13671875f, 0.08203125f, 0.02734375f, 0.03515625f, 0.10546875f, - 0.17578125f, 0.24609375f, 0.31640625f, 0.38671875f, 0.45703125f, 0.52734375f, - 0.52734375f, 0.45703125f, 0.38671875f, 0.31640625f, 0.24609375f, 0.17578125f, - 0.10546875f, 0.03515625f, 0.04296875f, 0.12890625f, 0.21484375f, 0.30078125f, - 0.38671875f, 0.47265625f, 0.55859375f, 0.64453125f, 0.64453125f, 0.55859375f, - 0.47265625f, 0.38671875f, 0.30078125f, 0.21484375f, 0.12890625f, 0.04296875f, - 0.05078125f, 0.15234375f, 0.25390625f, 0.35546875f, 0.45703125f, 0.55859375f, - 0.66015625f, 0.76171875f, 0.76171875f, 0.66015625f, 0.55859375f, 0.45703125f, - 0.35546875f, 0.25390625f, 0.15234375f, 0.05078125f, 0.05859375f, 0.17578125f, - 0.29296875f, 0.41015625f, 0.52734375f, 0.64453125f, 0.76171875f, 0.87890625f, - 0.87890625f, 0.76171875f, 0.64453125f, 0.52734375f, 0.41015625f, 0.29296875f, - 0.17578125f, 0.05859375f, 0.05859375f, 0.17578125f, 0.29296875f, 0.41015625f, - 0.52734375f, 0.64453125f, 0.76171875f, 0.87890625f, 0.87890625f, 0.76171875f, - 0.64453125f, 0.52734375f, 0.41015625f, 0.29296875f, 0.17578125f, 0.05859375f, - 0.05078125f, 0.15234375f, 0.25390625f, 0.35546875f, 0.45703125f, 0.55859375f, - 0.66015625f, 0.76171875f, 0.76171875f, 0.66015625f, 0.55859375f, 0.45703125f, - 0.35546875f, 0.25390625f, 0.15234375f, 0.05078125f, 0.04296875f, 0.12890625f, - 0.21484375f, 0.30078125f, 0.38671875f, 0.47265625f, 0.55859375f, 0.64453125f, - 0.64453125f, 0.55859375f, 0.47265625f, 0.38671875f, 0.30078125f, 0.21484375f, - 0.12890625f, 0.04296875f, 0.03515625f, 0.10546875f, 0.17578125f, 0.24609375f, - 0.31640625f, 0.38671875f, 0.45703125f, 0.52734375f, 0.52734375f, 0.45703125f, - 0.38671875f, 0.31640625f, 0.24609375f, 0.17578125f, 0.10546875f, 0.03515625f, - 0.02734375f, 0.08203125f, 0.13671875f, 0.19140625f, 0.24609375f, 0.30078125f, - 0.35546875f, 0.41015625f, 0.41015625f, 0.35546875f, 0.30078125f, 0.24609375f, - 0.19140625f, 0.13671875f, 0.08203125f, 0.02734375f, 0.01953125f, 0.05859375f, - 0.09765625f, 0.13671875f, 0.17578125f, 0.21484375f, 0.25390625f, 0.29296875f, - 0.29296875f, 0.25390625f, 0.21484375f, 0.17578125f, 0.13671875f, 0.09765625f, - 0.05859375f, 0.01953125f, 0.01171875f, 0.03515625f, 0.05859375f, 0.08203125f, - 0.10546875f, 0.12890625f, 0.15234375f, 0.17578125f, 0.17578125f, 0.15234375f, - 0.12890625f, 0.10546875f, 0.08203125f, 0.05859375f, 0.03515625f, 0.01171875f, - 0.00390625f, 0.01171875f, 0.01953125f, 0.02734375f, 0.03515625f, 0.04296875f, - 0.05078125f, 0.05859375f, 0.05859375f, 0.05078125f, 0.04296875f, 0.03515625f, - 0.02734375f, 0.01953125f, 0.01171875f, 0.00390625f -}; namespace cv { @@ -180,7 +88,7 @@ namespace cv int nblocks_win_x, int nblocks_win_y); void compute_hists(int nbins, int block_stride_x, int blovck_stride_y, - int height, int width, float sigma, const cv::ocl::oclMat &grad, + int height, int width, const cv::ocl::oclMat &grad, const cv::ocl::oclMat &qangle, const cv::ocl::oclMat &gauss_w_lut, cv::ocl::oclMat &block_hists); @@ -254,7 +162,7 @@ cv::ocl::HOGDescriptor::HOGDescriptor(Size win_size_, Size block_size_, Size blo effect_size = Size(0, 0); - if (queryDeviceInfo()) + if (queryDeviceInfo()) hog_device_cpu = true; else hog_device_cpu = false; @@ -328,10 +236,18 @@ void cv::ocl::HOGDescriptor::init_buffer(const oclMat &img, Size win_stride) Size wins_per_img = numPartsWithin(img.size(), win_size, win_stride); labels.create(1, wins_per_img.area(), CV_8U); - vector v_lut = vector(gaussian_interp_lut, gaussian_interp_lut + - sizeof(gaussian_interp_lut) / sizeof(gaussian_interp_lut[0])); - Mat m_lut(v_lut); - gauss_w_lut.upload(m_lut.reshape(1,1)); + float sigma = getWinSigma(); + float scale = 1.f / (2.f * sigma * sigma); + Mat gaussian_lut(1, 512, CV_32FC1); + int idx = 0; + for(int i=-8; i<8; i++) + for(int j=-8; j<8; j++) + gaussian_lut.at(idx++) = std::exp(-(j * j + i * i) * scale); + for(int i=-8; i<8; i++) + for(int j=-8; j<8; j++) + gaussian_lut.at(idx++) = (8.f - fabs(j + 0.5f)) * (8.f - fabs(i + 0.5f)) / 64.f; + + gauss_w_lut.upload(gaussian_lut); } void cv::ocl::HOGDescriptor::computeGradient(const oclMat &img, oclMat &grad, oclMat &qangle) @@ -358,7 +274,7 @@ void cv::ocl::HOGDescriptor::computeBlockHistograms(const oclMat &img) computeGradient(img, this->grad, this->qangle); hog::compute_hists(nbins, block_stride.width, block_stride.height, effect_size.height, - effect_size.width, (float)getWinSigma(), grad, qangle, gauss_w_lut, block_hists); + effect_size.width, grad, qangle, gauss_w_lut, block_hists); hog::normalize_hists(nbins, block_stride.width, block_stride.height, effect_size.height, effect_size.width, block_hists, (float)threshold_L2hys); @@ -1708,7 +1624,7 @@ void cv::ocl::device::hog::set_up_constants(int nbins, void cv::ocl::device::hog::compute_hists(int nbins, int block_stride_x, int block_stride_y, - int height, int width, float sigma, + int height, int width, const cv::ocl::oclMat &grad, const cv::ocl::oclMat &qangle, const cv::ocl::oclMat &gauss_w_lut, @@ -1716,8 +1632,7 @@ void cv::ocl::device::hog::compute_hists(int nbins, { Context *clCxt = Context::getContext(); vector< pair > args; - string kernelName = (sigma == 4.0f) ? "compute_hists_lut_kernel" : - "compute_hists_kernel"; + string kernelName = "compute_hists_lut_kernel"; int img_block_width = (width - CELLS_PER_BLOCK_X * CELL_WIDTH + block_stride_x) / block_stride_x; @@ -1728,9 +1643,6 @@ void cv::ocl::device::hog::compute_hists(int nbins, int grad_quadstep = grad.step >> 2; int qangle_step = qangle.step; - // Precompute gaussian spatial window parameter - float scale = 1.f / (2.f * sigma * sigma); - int blocks_in_group = 4; size_t localThreads[3] = { blocks_in_group * 24, 2, 1 }; size_t globalThreads[3] = { @@ -1751,15 +1663,23 @@ void cv::ocl::device::hog::compute_hists(int nbins, args.push_back( make_pair( sizeof(cl_int), (void *)&qangle_step)); args.push_back( make_pair( sizeof(cl_mem), (void *)&grad.data)); args.push_back( make_pair( sizeof(cl_mem), (void *)&qangle.data)); - if (kernelName.compare("compute_hists_lut_kernel") == 0) - args.push_back( make_pair( sizeof(cl_mem), (void *)&gauss_w_lut.data)); - else - args.push_back( make_pair( sizeof(cl_float), (void *)&scale)); + args.push_back( make_pair( sizeof(cl_mem), (void *)&gauss_w_lut.data)); args.push_back( make_pair( sizeof(cl_mem), (void *)&block_hists.data)); args.push_back( make_pair( smem, (void *)NULL)); - openCLExecuteKernel(clCxt, &objdetect_hog, kernelName, globalThreads, - localThreads, args, -1, -1); + if(hog_device_cpu) + { + openCLExecuteKernel(clCxt, &objdetect_hog, kernelName, globalThreads, + localThreads, args, -1, -1, "-D CPU"); + }else + { + cl_kernel kernel = openCLGetKernelFromSource(clCxt, &objdetect_hog, kernelName); + int wave_size = queryDeviceInfo(kernel); + char opt[32] = {0}; + sprintf(opt, "-D WAVE_SIZE=%d", wave_size); + openCLExecuteKernel(clCxt, &objdetect_hog, kernelName, globalThreads, + localThreads, args, -1, -1, opt); + } } void cv::ocl::device::hog::normalize_hists(int nbins, diff --git a/modules/ocl/src/initialization.cpp b/modules/ocl/src/initialization.cpp index d1ad695ff8..5d81517959 100644 --- a/modules/ocl/src/initialization.cpp +++ b/modules/ocl/src/initialization.cpp @@ -319,7 +319,7 @@ namespace cv char clVersion[256]; for (unsigned i = 0; i < numPlatforms; ++i) { - cl_uint numsdev; + cl_uint numsdev = 0; cl_int status = clGetDeviceIDs(platforms[i], devicetype, 0, NULL, &numsdev); if(status != CL_DEVICE_NOT_FOUND) openCLVerifyCall(status); diff --git a/modules/ocl/src/kmeans.cpp b/modules/ocl/src/kmeans.cpp new file mode 100644 index 0000000000..22f86600a8 --- /dev/null +++ b/modules/ocl/src/kmeans.cpp @@ -0,0 +1,438 @@ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved. +// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// @Authors +// Xiaopeng Fu, fuxiaopeng2222@163.com +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other oclMaterials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors as is and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#include +#include "precomp.hpp" + +using namespace cv; +using namespace ocl; + +namespace cv +{ +namespace ocl +{ +////////////////////////////////////OpenCL kernel strings////////////////////////// +extern const char *kmeans_kernel; +} +} + +static void generateRandomCenter(const vector& box, float* center, RNG& rng) +{ + size_t j, dims = box.size(); + float margin = 1.f/dims; + for( j = 0; j < dims; j++ ) + center[j] = ((float)rng*(1.f+margin*2.f)-margin)*(box[j][1] - box[j][0]) + box[j][0]; +} + +// This class is copied from matrix.cpp in core module. +class KMeansPPDistanceComputer : public ParallelLoopBody +{ +public: + KMeansPPDistanceComputer( float *_tdist2, + const float *_data, + const float *_dist, + int _dims, + size_t _step, + size_t _stepci ) + : tdist2(_tdist2), + data(_data), + dist(_dist), + dims(_dims), + step(_step), + stepci(_stepci) { } + + void operator()( const cv::Range& range ) const + { + const int begin = range.start; + const int end = range.end; + + for ( int i = begin; i _centers(K); + int* centers = &_centers[0]; + vector _dist(N*3); + float* dist = &_dist[0], *tdist = dist + N, *tdist2 = tdist + N; + double sum0 = 0; + + centers[0] = (unsigned)rng % N; + + for( i = 0; i < N; i++ ) + { + dist[i] = normL2Sqr_(data + step*i, data + step*centers[0], dims); + sum0 += dist[i]; + } + + for( k = 1; k < K; k++ ) + { + double bestSum = DBL_MAX; + int bestCenter = -1; + + for( j = 0; j < trials; j++ ) + { + double p = (double)rng*sum0, s = 0; + for( i = 0; i < N-1; i++ ) + if( (p -= dist[i]) <= 0 ) + break; + int ci = i; + + parallel_for_(Range(0, N), + KMeansPPDistanceComputer(tdist2, data, dist, dims, step, step*ci)); + for( i = 0; i < N; i++ ) + { + s += tdist2[i]; + } + + if( s < bestSum ) + { + bestSum = s; + bestCenter = ci; + std::swap(tdist, tdist2); + } + } + centers[k] = bestCenter; + sum0 = bestSum; + std::swap(dist, tdist); + } + + for( k = 0; k < K; k++ ) + { + const float* src = data + step*centers[k]; + float* dst = _out_centers.ptr(k); + for( j = 0; j < dims; j++ ) + dst[j] = src[j]; + } +} + +void cv::ocl::distanceToCenters(oclMat &dists, oclMat &labels, const oclMat &src, const oclMat ¢ers) +{ + //if(src.clCxt -> impl -> double_support == 0 && src.type() == CV_64F) + //{ + // CV_Error(CV_GpuNotSupported, "Selected device don't support double\r\n"); + // return; + //} + + Context *clCxt = src.clCxt; + int labels_step = (int)(labels.step/labels.elemSize()); + string kernelname = "distanceToCenters"; + int threadNum = src.rows > 256 ? 256 : src.rows; + size_t localThreads[3] = {1, threadNum, 1}; + size_t globalThreads[3] = {1, src.rows, 1}; + + vector > args; + args.push_back(make_pair(sizeof(cl_int), (void *)&labels_step)); + args.push_back(make_pair(sizeof(cl_int), (void *)¢ers.rows)); + args.push_back(make_pair(sizeof(cl_mem), (void *)&src.data)); + args.push_back(make_pair(sizeof(cl_mem), (void *)&labels.data)); + args.push_back(make_pair(sizeof(cl_int), (void *)¢ers.cols)); + args.push_back(make_pair(sizeof(cl_int), (void *)&src.rows)); + args.push_back(make_pair(sizeof(cl_mem), (void *)¢ers.data)); + args.push_back(make_pair(sizeof(cl_mem), (void*)&dists.data)); + + openCLExecuteKernel(clCxt, &kmeans_kernel, kernelname, globalThreads, localThreads, args, -1, -1, NULL); +} +///////////////////////////////////k - means ///////////////////////////////////////////////////////// +double cv::ocl::kmeans(const oclMat &_src, int K, oclMat &_bestLabels, + TermCriteria criteria, int attempts, int flags, oclMat &_centers) +{ + const int SPP_TRIALS = 3; + bool isrow = _src.rows == 1 && _src.oclchannels() > 1; + int N = !isrow ? _src.rows : _src.cols; + int dims = (!isrow ? _src.cols : 1) * _src.oclchannels(); + int type = _src.depth(); + + attempts = std::max(attempts, 1); + CV_Assert(type == CV_32F && K > 0 ); + CV_Assert( N >= K ); + + Mat _labels; + if( flags & CV_KMEANS_USE_INITIAL_LABELS ) + { + CV_Assert( (_bestLabels.cols == 1 || _bestLabels.rows == 1) && + _bestLabels.cols * _bestLabels.rows == N && + _bestLabels.type() == CV_32S ); + _bestLabels.download(_labels); + } + else + { + if( !((_bestLabels.cols == 1 || _bestLabels.rows == 1) && + _bestLabels.cols * _bestLabels.rows == N && + _bestLabels.type() == CV_32S && + _bestLabels.isContinuous())) + _bestLabels.create(N, 1, CV_32S); + _labels.create(_bestLabels.size(), _bestLabels.type()); + } + int* labels = _labels.ptr(); + + Mat data; + _src.download(data); + Mat centers(K, dims, type), old_centers(K, dims, type), temp(1, dims, type); + vector counters(K); + vector _box(dims); + Vec2f* box = &_box[0]; + double best_compactness = DBL_MAX, compactness = 0; + RNG& rng = theRNG(); + int a, iter, i, j, k; + + if( criteria.type & TermCriteria::EPS ) + criteria.epsilon = std::max(criteria.epsilon, 0.); + else + criteria.epsilon = FLT_EPSILON; + criteria.epsilon *= criteria.epsilon; + + if( criteria.type & TermCriteria::COUNT ) + criteria.maxCount = std::min(std::max(criteria.maxCount, 2), 100); + else + criteria.maxCount = 100; + + if( K == 1 ) + { + attempts = 1; + criteria.maxCount = 2; + } + + const float* sample = data.ptr(); + for( j = 0; j < dims; j++ ) + box[j] = Vec2f(sample[j], sample[j]); + + for( i = 1; i < N; i++ ) + { + sample = data.ptr(i); + for( j = 0; j < dims; j++ ) + { + float v = sample[j]; + box[j][0] = std::min(box[j][0], v); + box[j][1] = std::max(box[j][1], v); + } + } + + for( a = 0; a < attempts; a++ ) + { + double max_center_shift = DBL_MAX; + for( iter = 0;; ) + { + swap(centers, old_centers); + + if( iter == 0 && (a > 0 || !(flags & KMEANS_USE_INITIAL_LABELS)) ) + { + if( flags & KMEANS_PP_CENTERS ) + generateCentersPP(data, centers, K, rng, SPP_TRIALS); + else + { + for( k = 0; k < K; k++ ) + generateRandomCenter(_box, centers.ptr(k), rng); + } + } + else + { + if( iter == 0 && a == 0 && (flags & KMEANS_USE_INITIAL_LABELS) ) + { + for( i = 0; i < N; i++ ) + CV_Assert( (unsigned)labels[i] < (unsigned)K ); + } + + // compute centers + centers = Scalar(0); + for( k = 0; k < K; k++ ) + counters[k] = 0; + + for( i = 0; i < N; i++ ) + { + sample = data.ptr(i); + k = labels[i]; + float* center = centers.ptr(k); + j=0; +#if CV_ENABLE_UNROLLED + for(; j <= dims - 4; j += 4 ) + { + float t0 = center[j] + sample[j]; + float t1 = center[j+1] + sample[j+1]; + + center[j] = t0; + center[j+1] = t1; + + t0 = center[j+2] + sample[j+2]; + t1 = center[j+3] + sample[j+3]; + + center[j+2] = t0; + center[j+3] = t1; + } +#endif + for( ; j < dims; j++ ) + center[j] += sample[j]; + counters[k]++; + } + + if( iter > 0 ) + max_center_shift = 0; + + for( k = 0; k < K; k++ ) + { + if( counters[k] != 0 ) + continue; + + // if some cluster appeared to be empty then: + // 1. find the biggest cluster + // 2. find the farthest from the center point in the biggest cluster + // 3. exclude the farthest point from the biggest cluster and form a new 1-point cluster. + int max_k = 0; + for( int k1 = 1; k1 < K; k1++ ) + { + if( counters[max_k] < counters[k1] ) + max_k = k1; + } + + double max_dist = 0; + int farthest_i = -1; + float* new_center = centers.ptr(k); + float* old_center = centers.ptr(max_k); + float* _old_center = temp.ptr(); // normalized + float scale = 1.f/counters[max_k]; + for( j = 0; j < dims; j++ ) + _old_center[j] = old_center[j]*scale; + + for( i = 0; i < N; i++ ) + { + if( labels[i] != max_k ) + continue; + sample = data.ptr(i); + double dist = normL2Sqr_(sample, _old_center, dims); + + if( max_dist <= dist ) + { + max_dist = dist; + farthest_i = i; + } + } + + counters[max_k]--; + counters[k]++; + labels[farthest_i] = k; + sample = data.ptr(farthest_i); + + for( j = 0; j < dims; j++ ) + { + old_center[j] -= sample[j]; + new_center[j] += sample[j]; + } + } + + for( k = 0; k < K; k++ ) + { + float* center = centers.ptr(k); + CV_Assert( counters[k] != 0 ); + + float scale = 1.f/counters[k]; + for( j = 0; j < dims; j++ ) + center[j] *= scale; + + if( iter > 0 ) + { + double dist = 0; + const float* old_center = old_centers.ptr(k); + for( j = 0; j < dims; j++ ) + { + double t = center[j] - old_center[j]; + dist += t*t; + } + max_center_shift = std::max(max_center_shift, dist); + } + } + } + + if( ++iter == MAX(criteria.maxCount, 2) || max_center_shift <= criteria.epsilon ) + break; + + // assign labels + oclMat _dists(1, N, CV_64F); + + _bestLabels.upload(_labels); + _centers.upload(centers); + distanceToCenters(_dists, _bestLabels, _src, _centers); + + Mat dists; + _dists.download(dists); + _bestLabels.download(_labels); + + double* dist = dists.ptr(0); + compactness = 0; + for( i = 0; i < N; i++ ) + { + compactness += dist[i]; + } + } + + if( compactness < best_compactness ) + { + best_compactness = compactness; + } + } + + return best_compactness; +} + diff --git a/modules/ocl/src/opencl/imgproc_gfft.cl b/modules/ocl/src/opencl/imgproc_gftt.cl similarity index 100% rename from modules/ocl/src/opencl/imgproc_gfft.cl rename to modules/ocl/src/opencl/imgproc_gftt.cl diff --git a/modules/ocl/src/opencl/kernel_radix_sort_by_key.cl b/modules/ocl/src/opencl/kernel_radix_sort_by_key.cl new file mode 100644 index 0000000000..fdb440aeea --- /dev/null +++ b/modules/ocl/src/opencl/kernel_radix_sort_by_key.cl @@ -0,0 +1,176 @@ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved. +// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// @Authors +// Peng Xiao, pengxiao@outlook.com +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other oclMaterials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors as is and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#pragma OPENCL EXTENSION cl_khr_byte_addressable_store : enable + +#ifndef N // number of radices +#define N 4 +#endif + +#ifndef K_T +#define K_T float +#endif + +#ifndef V_T +#define V_T float +#endif + +#ifndef IS_GT +#define IS_GT 0 +#endif + + +// from Thrust::b40c, link: +// https://github.com/thrust/thrust/blob/master/thrust/system/cuda/detail/detail/b40c/radixsort_key_conversion.h +__inline uint convertKey(uint converted_key) +{ +#ifdef K_FLT + unsigned int mask = (converted_key & 0x80000000) ? 0xffffffff : 0x80000000; + converted_key ^= mask; +#elif defined(K_INT) + const uint SIGN_MASK = 1u << ((sizeof(int) * 8) - 1); + converted_key ^= SIGN_MASK; +#else + +#endif + return converted_key; +} + +//FIXME(pengx17): +// exclusive scan, need to be optimized as this is too naive... +kernel + void naiveScanAddition( + __global int * input, + __global int * output, + int size + ) +{ + if(get_global_id(0) == 0) + { + output[0] = 0; + for(int i = 1; i < size; i ++) + { + output[i] = output[i - 1] + input[i - 1]; + } + } +} + +// following is ported from +// https://github.com/HSA-Libraries/Bolt/blob/master/include/bolt/cl/sort_uint_kernels.cl +kernel + void histogramRadixN ( + __global K_T* unsortedKeys, + __global int * buckets, + uint shiftCount + ) +{ + const int RADIX_T = N; + const int RADICES_T = (1 << RADIX_T); + const int NUM_OF_ELEMENTS_PER_WORK_ITEM_T = RADICES_T; + const int MASK_T = (1 << RADIX_T) - 1; + int localBuckets[16] = {0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0}; + int globalId = get_global_id(0); + int numOfGroups = get_num_groups(0); + + /* Calculate thread-histograms */ + for(int i = 0; i < NUM_OF_ELEMENTS_PER_WORK_ITEM_T; ++i) + { + uint value = convertKey(as_uint(unsortedKeys[mad24(globalId, NUM_OF_ELEMENTS_PER_WORK_ITEM_T, i)])); + value = (value >> shiftCount) & MASK_T; +#if IS_GT + localBuckets[RADICES_T - value - 1]++; +#else + localBuckets[value]++; +#endif + } + + for(int i = 0; i < NUM_OF_ELEMENTS_PER_WORK_ITEM_T; ++i) + { + buckets[mad24(i, RADICES_T * numOfGroups, globalId) ] = localBuckets[i]; + } +} + +kernel + void permuteRadixN ( + __global K_T* unsortedKeys, + __global V_T* unsortedVals, + __global int* scanedBuckets, + uint shiftCount, + __global K_T* sortedKeys, + __global V_T* sortedVals + ) +{ + const int RADIX_T = N; + const int RADICES_T = (1 << RADIX_T); + const int MASK_T = (1<> shiftCount) & MASK_T; + uint index = localIndex[maskedValue]; + sortedKeys[index] = ovalue; + sortedVals[index] = unsortedVals[old_idx]; + localIndex[maskedValue] = index + 1; + } +} diff --git a/modules/ocl/src/opencl/kernel_sort_by_key.cl b/modules/ocl/src/opencl/kernel_sort_by_key.cl new file mode 100644 index 0000000000..18e9d419aa --- /dev/null +++ b/modules/ocl/src/opencl/kernel_sort_by_key.cl @@ -0,0 +1,245 @@ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved. +// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// @Authors +// Peng Xiao, pengxiao@outlook.com +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other oclMaterials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors as is and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef K_T +#define K_T float +#endif + +#ifndef V_T +#define V_T float +#endif + +#ifndef IS_GT +#define IS_GT false +#endif + +#if IS_GT +#define my_comp(x,y) ((x) > (y)) +#else +#define my_comp(x,y) ((x) < (y)) +#endif + +/////////////////////// Bitonic sort //////////////////////////// +// ported from +// https://github.com/HSA-Libraries/Bolt/blob/master/include/bolt/cl/sort_by_key_kernels.cl +__kernel + void bitonicSort + ( + __global K_T * keys, + __global V_T * vals, + int count, + int stage, + int passOfStage + ) +{ + const int threadId = get_global_id(0); + if(threadId >= count / 2) + { + return; + } + const int pairDistance = 1 << (stage - passOfStage); + const int blockWidth = 2 * pairDistance; + + int leftId = min( (threadId % pairDistance) + + (threadId / pairDistance) * blockWidth, count ); + + int rightId = min( leftId + pairDistance, count ); + + int temp; + + const V_T lval = vals[leftId]; + const V_T rval = vals[rightId]; + + const K_T lkey = keys[leftId]; + const K_T rkey = keys[rightId]; + + int sameDirectionBlockWidth = 1 << stage; + + if((threadId/sameDirectionBlockWidth) % 2 == 1) + { + temp = rightId; + rightId = leftId; + leftId = temp; + } + + const bool compareResult = my_comp(lkey, rkey); + + if(compareResult) + { + keys[rightId] = rkey; + keys[leftId] = lkey; + vals[rightId] = rval; + vals[leftId] = lval; + } + else + { + keys[rightId] = lkey; + keys[leftId] = rkey; + vals[rightId] = lval; + vals[leftId] = rval; + } +} + +/////////////////////// Selection sort //////////////////////////// +//kernel is ported from Bolt library: +//https://github.com/HSA-Libraries/Bolt/blob/master/include/bolt/cl/sort_kernels.cl +__kernel + void selectionSortLocal + ( + __global K_T * keys, + __global V_T * vals, + const int count, + __local K_T * scratch + ) +{ + int i = get_local_id(0); // index in workgroup + int numOfGroups = get_num_groups(0); // index in workgroup + int groupID = get_group_id(0); + int wg = get_local_size(0); // workgroup size = block size + int n; // number of elements to be processed for this work group + + int offset = groupID * wg; + int same = 0; + + vals += offset; + keys += offset; + n = (groupID == (numOfGroups-1))? (count - wg*(numOfGroups-1)) : wg; + + int clamped_i= min(i, n - 1); + + K_T key1 = keys[clamped_i], key2; + V_T val1 = vals[clamped_i]; + scratch[i] = key1; + barrier(CLK_LOCAL_MEM_FENCE); + + if(i >= n) + { + return; + } + + int pos = 0; + for (int j=0;j= count) + return; + V_T val1 = vals[offset + i]; + + K_T key1 = keys[offset + i]; + K_T key2; + + for(int j=0; j (y)) +#else +#define my_comp(x,y) ((x) < (y)) +#endif + +///////////// parallel merge sort /////////////// +// ported from https://github.com/HSA-Libraries/Bolt/blob/master/include/bolt/cl/stablesort_by_key_kernels.cl +uint lowerBoundLinear( global K_T* data, uint left, uint right, K_T searchVal) +{ + // The values firstIndex and lastIndex get modified within the loop, narrowing down the potential sequence + uint firstIndex = left; + uint lastIndex = right; + + // This loops through [firstIndex, lastIndex) + // Since firstIndex and lastIndex will be different for every thread depending on the nested branch, + // this while loop will be divergent within a wavefront + while( firstIndex < lastIndex ) + { + K_T dataVal = data[ firstIndex ]; + + // This branch will create divergent wavefronts + if( my_comp( dataVal, searchVal ) ) + { + firstIndex = firstIndex+1; + } + else + { + break; + } + } + + return firstIndex; +} + +// This implements a binary search routine to look for an 'insertion point' in a sequence, denoted +// by a base pointer and left and right index for a particular candidate value. The comparison operator is +// passed as a functor parameter my_comp +// This function returns an index that is the first index whos value would be equal to the searched value +uint lowerBoundBinary( global K_T* data, uint left, uint right, K_T searchVal) +{ + // The values firstIndex and lastIndex get modified within the loop, narrowing down the potential sequence + uint firstIndex = left; + uint lastIndex = right; + + // This loops through [firstIndex, lastIndex) + // Since firstIndex and lastIndex will be different for every thread depending on the nested branch, + // this while loop will be divergent within a wavefront + while( firstIndex < lastIndex ) + { + // midIndex is the average of first and last, rounded down + uint midIndex = ( firstIndex + lastIndex ) / 2; + K_T midValue = data[ midIndex ]; + + // This branch will create divergent wavefronts + if( my_comp( midValue, searchVal ) ) + { + firstIndex = midIndex+1; + // printf( "lowerBound: lastIndex[ %i ]=%i\n", get_local_id( 0 ), lastIndex ); + } + else + { + lastIndex = midIndex; + // printf( "lowerBound: firstIndex[ %i ]=%i\n", get_local_id( 0 ), firstIndex ); + } + } + + return firstIndex; +} + +// This implements a binary search routine to look for an 'insertion point' in a sequence, denoted +// by a base pointer and left and right index for a particular candidate value. The comparison operator is +// passed as a functor parameter my_comp +// This function returns an index that is the first index whos value would be greater than the searched value +// If the search value is not found in the sequence, upperbound returns the same result as lowerbound +uint upperBoundBinary( global K_T* data, uint left, uint right, K_T searchVal) +{ + uint upperBound = lowerBoundBinary( data, left, right, searchVal ); + + // printf( "upperBoundBinary: upperBound[ %i, %i ]= %i\n", left, right, upperBound ); + // If upperBound == right, then searchVal was not found in the sequence. Just return. + if( upperBound != right ) + { + // While the values are equal i.e. !(x < y) && !(y < x) increment the index + K_T upperValue = data[ upperBound ]; + while( !my_comp( upperValue, searchVal ) && !my_comp( searchVal, upperValue) && (upperBound != right) ) + { + upperBound++; + upperValue = data[ upperBound ]; + } + } + + return upperBound; +} + +// This kernel implements merging of blocks of sorted data. The input to this kernel most likely is +// the output of blockInsertionSortTemplate. It is expected that the source array contains multiple +// blocks, each block is independently sorted. The goal is to write into the output buffer half as +// many blocks, of double the size. The even and odd blocks are stably merged together to form +// a new sorted block of twice the size. The algorithm is out-of-place. +kernel void merge( + global K_T* iKey_ptr, + global V_T* iValue_ptr, + global K_T* oKey_ptr, + global V_T* oValue_ptr, + const uint srcVecSize, + const uint srcLogicalBlockSize, + local K_T* key_lds, + local V_T* val_lds +) +{ + size_t globalID = get_global_id( 0 ); + size_t groupID = get_group_id( 0 ); + size_t localID = get_local_id( 0 ); + size_t wgSize = get_local_size( 0 ); + + // Abort threads that are passed the end of the input vector + if( globalID >= srcVecSize ) + return; // on SI this doesn't mess-up barriers + + // For an element in sequence A, find the lowerbound index for it in sequence B + uint srcBlockNum = globalID / srcLogicalBlockSize; + uint srcBlockIndex = globalID % srcLogicalBlockSize; + + // printf( "mergeTemplate: srcBlockNum[%i]=%i\n", srcBlockNum, srcBlockIndex ); + + // Pairs of even-odd blocks will be merged together + // An even block should search for an insertion point in the next odd block, + // and the odd block should look for an insertion point in the corresponding previous even block + uint dstLogicalBlockSize = srcLogicalBlockSize<<1; + uint leftBlockIndex = globalID & ~((dstLogicalBlockSize) - 1 ); + leftBlockIndex += (srcBlockNum & 0x1) ? 0 : srcLogicalBlockSize; + leftBlockIndex = min( leftBlockIndex, srcVecSize ); + uint rightBlockIndex = min( leftBlockIndex + srcLogicalBlockSize, srcVecSize ); + + // if( localID == 0 ) + // { + // printf( "mergeTemplate: wavefront[ %i ] logicalBlock[ %i ] logicalIndex[ %i ] leftBlockIndex[ %i ] <=> rightBlockIndex[ %i ]\n", groupID, srcBlockNum, srcBlockIndex, leftBlockIndex, rightBlockIndex ); + // } + + // For a particular element in the input array, find the lowerbound index for it in the search sequence given by leftBlockIndex & rightBlockIndex + // uint insertionIndex = lowerBoundLinear( iKey_ptr, leftBlockIndex, rightBlockIndex, iKey_ptr[ globalID ], my_comp ) - leftBlockIndex; + uint insertionIndex = 0; + if( (srcBlockNum & 0x1) == 0 ) + { + insertionIndex = lowerBoundBinary( iKey_ptr, leftBlockIndex, rightBlockIndex, iKey_ptr[ globalID ] ) - leftBlockIndex; + } + else + { + insertionIndex = upperBoundBinary( iKey_ptr, leftBlockIndex, rightBlockIndex, iKey_ptr[ globalID ] ) - leftBlockIndex; + } + + // The index of an element in the result sequence is the summation of it's indixes in the two input + // sequences + uint dstBlockIndex = srcBlockIndex + insertionIndex; + uint dstBlockNum = srcBlockNum/2; + + // if( (dstBlockNum*dstLogicalBlockSize)+dstBlockIndex == 395 ) + // { + // printf( "mergeTemplate: (dstBlockNum[ %i ] * dstLogicalBlockSize[ %i ]) + dstBlockIndex[ %i ] = srcBlockIndex[ %i ] + insertionIndex[ %i ]\n", dstBlockNum, dstLogicalBlockSize, dstBlockIndex, srcBlockIndex, insertionIndex ); + // printf( "mergeTemplate: dstBlockIndex[ %i ] = iKey_ptr[ %i ] ( %i )\n", (dstBlockNum*dstLogicalBlockSize)+dstBlockIndex, globalID, iKey_ptr[ globalID ] ); + // } + oKey_ptr[ (dstBlockNum*dstLogicalBlockSize)+dstBlockIndex ] = iKey_ptr[ globalID ]; + oValue_ptr[ (dstBlockNum*dstLogicalBlockSize)+dstBlockIndex ] = iValue_ptr[ globalID ]; + // printf( "mergeTemplate: leftResultIndex[ %i ]=%i + %i\n", leftResultIndex, srcBlockIndex, leftInsertionIndex ); +} + +kernel void blockInsertionSort( + global K_T* key_ptr, + global V_T* value_ptr, + const uint vecSize, + local K_T* key_lds, + local V_T* val_lds +) +{ + size_t gloId = get_global_id( 0 ); + size_t groId = get_group_id( 0 ); + size_t locId = get_local_id( 0 ); + size_t wgSize = get_local_size( 0 ); + + bool in_range = gloId < vecSize; + K_T key; + V_T val; + // Abort threads that are passed the end of the input vector + if (in_range) + { + // Make a copy of the entire input array into fast local memory + key = key_ptr[ gloId ]; + val = value_ptr[ gloId ]; + key_lds[ locId ] = key; + val_lds[ locId ] = val; + } + barrier( CLK_LOCAL_MEM_FENCE ); + // Sorts a workgroup using a naive insertion sort + // The sort uses one thread within a workgroup to sort the entire workgroup + if( locId == 0 && in_range ) + { + // The last workgroup may have an irregular size, so we calculate a per-block endIndex + // endIndex is essentially emulating a mod operator with subtraction and multiply + size_t endIndex = vecSize - ( groId * wgSize ); + endIndex = min( endIndex, wgSize ); + + // printf( "Debug: endIndex[%i]=%i\n", groId, endIndex ); + + // Indices are signed because the while loop will generate a -1 index inside of the max function + for( int currIndex = 1; currIndex < endIndex; ++currIndex ) + { + key = key_lds[ currIndex ]; + val = val_lds[ currIndex ]; + int scanIndex = currIndex; + K_T ldsKey = key_lds[scanIndex - 1]; + while( scanIndex > 0 && my_comp( key, ldsKey ) ) + { + V_T ldsVal = val_lds[scanIndex - 1]; + + // If the keys are being swapped, make sure the values are swapped identicaly + key_lds[ scanIndex ] = ldsKey; + val_lds[ scanIndex ] = ldsVal; + + scanIndex = scanIndex - 1; + ldsKey = key_lds[ max( 0, scanIndex - 1 ) ]; // scanIndex-1 may be -1 + } + key_lds[ scanIndex ] = key; + val_lds[ scanIndex ] = val; + } + } + barrier( CLK_LOCAL_MEM_FENCE ); + + if(in_range) + { + key = key_lds[ locId ]; + key_ptr[ gloId ] = key; + + val = val_lds[ locId ]; + value_ptr[ gloId ] = val; + } +} + +///////////// Radix sort from b40c library ///////////// diff --git a/modules/ocl/src/precomp.cpp b/modules/ocl/src/opencl/kmeans_kernel.cl similarity index 66% rename from modules/ocl/src/precomp.cpp rename to modules/ocl/src/opencl/kmeans_kernel.cl index 766138c577..c6af0ad249 100644 --- a/modules/ocl/src/precomp.cpp +++ b/modules/ocl/src/opencl/kmeans_kernel.cl @@ -10,11 +10,12 @@ // License Agreement // For Open Source Computer Vision Library // -// Copyright (C) 2010-2012, Institute Of Software Chinese Academy Of Science, all rights reserved. +// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved. // Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // @Authors +// Xiaopeng Fu, fuxiaopeng2222@163.com // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: @@ -24,12 +25,12 @@ // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation -// and/or other oclMaterials provided with the distribution. +// 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 +// 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, @@ -42,6 +43,42 @@ // //M*/ -#include "precomp.hpp" -//CriticalSection cs; -/* End of file. */ +__kernel void distanceToCenters( + int label_step, int K, + __global float *src, + __global int *labels, int dims, int rows, + __global float *centers, + __global float *dists) +{ + int gid = get_global_id(1); + + float dist, euDist, min; + int minCentroid; + + if(gid >= rows) + return; + + for(int i = 0 ; i < K; i++) + { + euDist = 0; + for(int j = 0; j < dims; j++) + { + dist = (src[j + gid * dims] + - centers[j + i * dims]); + euDist += dist * dist; + } + + if(i == 0) + { + min = euDist; + minCentroid = 0; + } + else if(euDist < min) + { + min = euDist; + minCentroid = i; + } + } + dists[gid] = min; + labels[label_step * gid] = minCentroid; +} diff --git a/modules/ocl/src/opencl/objdetect_hog.cl b/modules/ocl/src/opencl/objdetect_hog.cl index 8ca12704e5..0363227606 100644 --- a/modules/ocl/src/opencl/objdetect_hog.cl +++ b/modules/ocl/src/opencl/objdetect_hog.cl @@ -53,7 +53,7 @@ //---------------------------------------------------------------------------- // Histogram computation // 12 threads for a cell, 12x4 threads per block -// Use pre-computed gaussian and interp_weight lookup tables if sigma is 4.0f +// Use pre-computed gaussian and interp_weight lookup tables __kernel void compute_hists_lut_kernel( const int cblock_stride_x, const int cblock_stride_y, const int cnbins, const int cblock_hist_size, const int img_block_width, @@ -146,99 +146,6 @@ __kernel void compute_hists_lut_kernel( } } -//---------------------------------------------------------------------------- -// Histogram computation -// 12 threads for a cell, 12x4 threads per block -__kernel void compute_hists_kernel( - const int cblock_stride_x, const int cblock_stride_y, - const int cnbins, const int cblock_hist_size, const int img_block_width, - const int blocks_in_group, const int blocks_total, - const int grad_quadstep, const int qangle_step, - __global const float* grad, __global const uchar* qangle, - const float scale, __global float* block_hists, __local float* smem) -{ - const int lx = get_local_id(0); - const int lp = lx / 24; /* local group id */ - const int gid = get_group_id(0) * blocks_in_group + lp;/* global group id */ - const int gidY = gid / img_block_width; - const int gidX = gid - gidY * img_block_width; - - const int lidX = lx - lp * 24; - const int lidY = get_local_id(1); - - const int cell_x = lidX / 12; - const int cell_y = lidY; - const int cell_thread_x = lidX - cell_x * 12; - - __local float* hists = smem + lp * cnbins * (CELLS_PER_BLOCK_X * - CELLS_PER_BLOCK_Y * 12 + CELLS_PER_BLOCK_X * CELLS_PER_BLOCK_Y); - __local float* final_hist = hists + cnbins * - (CELLS_PER_BLOCK_X * CELLS_PER_BLOCK_Y * 12); - - const int offset_x = gidX * cblock_stride_x + (cell_x << 2) + cell_thread_x; - const int offset_y = gidY * cblock_stride_y + (cell_y << 2); - - __global const float* grad_ptr = (gid < blocks_total) ? - grad + offset_y * grad_quadstep + (offset_x << 1) : grad; - __global const uchar* qangle_ptr = (gid < blocks_total) ? - qangle + offset_y * qangle_step + (offset_x << 1) : qangle; - - __local float* hist = hists + 12 * (cell_y * CELLS_PER_BLOCK_Y + cell_x) + - cell_thread_x; - for (int bin_id = 0; bin_id < cnbins; ++bin_id) - hist[bin_id * 48] = 0.f; - - const int dist_x = -4 + cell_thread_x - 4 * cell_x; - const int dist_center_x = dist_x - 4 * (1 - 2 * cell_x); - - const int dist_y_begin = -4 - 4 * lidY; - for (int dist_y = dist_y_begin; dist_y < dist_y_begin + 12; ++dist_y) - { - float2 vote = (float2) (grad_ptr[0], grad_ptr[1]); - uchar2 bin = (uchar2) (qangle_ptr[0], qangle_ptr[1]); - - grad_ptr += grad_quadstep; - qangle_ptr += qangle_step; - - int dist_center_y = dist_y - 4 * (1 - 2 * cell_y); - - float gaussian = exp(-(dist_center_y * dist_center_y + dist_center_x * - dist_center_x) * scale); - float interp_weight = (8.f - fabs(dist_y + 0.5f)) * - (8.f - fabs(dist_x + 0.5f)) / 64.f; - - hist[bin.x * 48] += gaussian * interp_weight * vote.x; - hist[bin.y * 48] += gaussian * interp_weight * vote.y; - } - barrier(CLK_LOCAL_MEM_FENCE); - - volatile __local float* hist_ = hist; - for (int bin_id = 0; bin_id < cnbins; ++bin_id, hist_ += 48) - { - if (cell_thread_x < 6) - hist_[0] += hist_[6]; - barrier(CLK_LOCAL_MEM_FENCE); - if (cell_thread_x < 3) - hist_[0] += hist_[3]; -#ifdef CPU - barrier(CLK_LOCAL_MEM_FENCE); -#endif - if (cell_thread_x == 0) - final_hist[(cell_x * 2 + cell_y) * cnbins + bin_id] = - hist_[0] + hist_[1] + hist_[2]; - } -#ifdef CPU - barrier(CLK_LOCAL_MEM_FENCE); -#endif - int tid = (cell_y * CELLS_PER_BLOCK_Y + cell_x) * 12 + cell_thread_x; - if ((tid < cblock_hist_size) && (gid < blocks_total)) - { - __global float* block_hist = block_hists + - (gidY * img_block_width + gidX) * cblock_hist_size; - block_hist[tid] = final_hist[tid]; - } -} - //------------------------------------------------------------- // Normalization of histograms via L2Hys_norm // optimized for the case of 9 bins diff --git a/modules/ocl/src/opencl/pyrlk.cl b/modules/ocl/src/opencl/pyrlk.cl index 40a1993952..02cf3afa44 100644 --- a/modules/ocl/src/opencl/pyrlk.cl +++ b/modules/ocl/src/opencl/pyrlk.cl @@ -17,6 +17,7 @@ // @Authors // Dachuan Zhao, dachuan@multicorewareinc.com // Yao Wang, bitwangyaoyao@gmail.com +// Xiaopeng Fu, fuxiaopeng2222@163.com // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: @@ -47,6 +48,7 @@ //#pragma OPENCL EXTENSION cl_amd_printf : enable #define BUFFER 64 +#define BUFFER2 BUFFER>>1 #ifndef WAVE_SIZE #define WAVE_SIZE 1 #endif @@ -58,53 +60,16 @@ void reduce3(float val1, float val2, float val3, __local float* smem1, __local smem3[tid] = val3; barrier(CLK_LOCAL_MEM_FENCE); - if (tid < 32) - { - smem1[tid] += smem1[tid + 32]; - smem2[tid] += smem2[tid + 32]; - smem3[tid] += smem3[tid + 32]; - } - barrier(CLK_LOCAL_MEM_FENCE); - - if (tid < 16) - { - smem1[tid] += smem1[tid + 16]; - smem2[tid] += smem2[tid + 16]; - smem3[tid] += smem3[tid + 16]; - } - barrier(CLK_LOCAL_MEM_FENCE); - - if (tid < 8) - { - smem1[tid] += smem1[tid + 8]; - smem2[tid] += smem2[tid + 8]; - smem3[tid] += smem3[tid + 8]; - } - barrier(CLK_LOCAL_MEM_FENCE); - - if (tid < 4) - { - smem1[tid] += smem1[tid + 4]; - smem2[tid] += smem2[tid + 4]; - smem3[tid] += smem3[tid + 4]; - } - barrier(CLK_LOCAL_MEM_FENCE); - - if (tid < 2) - { - smem1[tid] += smem1[tid + 2]; - smem2[tid] += smem2[tid + 2]; - smem3[tid] += smem3[tid + 2]; - } - barrier(CLK_LOCAL_MEM_FENCE); - - if (tid < 1) + for(int i = BUFFER2; i > 0; i >>= 1) { - smem1[BUFFER] = smem1[tid] + smem1[tid + 1]; - smem2[BUFFER] = smem2[tid] + smem2[tid + 1]; - smem3[BUFFER] = smem3[tid] + smem3[tid + 1]; + if(tid < i) + { + smem1[tid] += smem1[tid + i]; + smem2[tid] += smem2[tid + i]; + smem3[tid] += smem3[tid + i]; + } + barrier(CLK_LOCAL_MEM_FENCE); } - barrier(CLK_LOCAL_MEM_FENCE); } void reduce2(float val1, float val2, volatile __local float* smem1, volatile __local float* smem2, int tid) @@ -113,47 +78,15 @@ void reduce2(float val1, float val2, volatile __local float* smem1, volatile __l smem2[tid] = val2; barrier(CLK_LOCAL_MEM_FENCE); - if (tid < 32) - { - smem1[tid] += smem1[tid + 32]; - smem2[tid] += smem2[tid + 32]; - } - barrier(CLK_LOCAL_MEM_FENCE); - - if (tid < 16) + for(int i = BUFFER2; i > 0; i >>= 1) { - smem1[tid] += smem1[tid + 16]; - smem2[tid] += smem2[tid + 16]; - } - barrier(CLK_LOCAL_MEM_FENCE); - - if (tid < 8) - { - smem1[tid] += smem1[tid + 8]; - smem2[tid] += smem2[tid + 8]; - } - barrier(CLK_LOCAL_MEM_FENCE); - - if (tid < 4) - { - smem1[tid] += smem1[tid + 4]; - smem2[tid] += smem2[tid + 4]; - } - barrier(CLK_LOCAL_MEM_FENCE); - - if (tid < 2) - { - smem1[tid] += smem1[tid + 2]; - smem2[tid] += smem2[tid + 2]; - } - barrier(CLK_LOCAL_MEM_FENCE); - - if (tid < 1) - { - smem1[BUFFER] = smem1[tid] + smem1[tid + 1]; - smem2[BUFFER] = smem2[tid] + smem2[tid + 1]; + if(tid < i) + { + smem1[tid] += smem1[tid + i]; + smem2[tid] += smem2[tid + i]; + } + barrier(CLK_LOCAL_MEM_FENCE); } - barrier(CLK_LOCAL_MEM_FENCE); } void reduce1(float val1, volatile __local float* smem1, int tid) @@ -161,45 +94,18 @@ void reduce1(float val1, volatile __local float* smem1, int tid) smem1[tid] = val1; barrier(CLK_LOCAL_MEM_FENCE); - if (tid < 32) + for(int i = BUFFER2; i > 0; i >>= 1) { - smem1[tid] += smem1[tid + 32]; - } - barrier(CLK_LOCAL_MEM_FENCE); - - if (tid < 16) - { - smem1[tid] += smem1[tid + 16]; - } - barrier(CLK_LOCAL_MEM_FENCE); - - if (tid < 8) - { - smem1[tid] += smem1[tid + 8]; - } - barrier(CLK_LOCAL_MEM_FENCE); - - if (tid < 4) - { - smem1[tid] += smem1[tid + 4]; - } - barrier(CLK_LOCAL_MEM_FENCE); - - if (tid < 2) - { - smem1[tid] += smem1[tid + 2]; - } - barrier(CLK_LOCAL_MEM_FENCE); - - if (tid < 1) - { - smem1[BUFFER] = smem1[tid] + smem1[tid + 1]; + if(tid < i) + { + smem1[tid] += smem1[tid + i]; + } + barrier(CLK_LOCAL_MEM_FENCE); } - barrier(CLK_LOCAL_MEM_FENCE); } #else -void reduce3(float val1, float val2, float val3, -__local volatile float* smem1, __local volatile float* smem2, __local volatile float* smem3, int tid) +void reduce3(float val1, float val2, float val3, + __local volatile float* smem1, __local volatile float* smem2, __local volatile float* smem3, int tid) { smem1[tid] = val1; smem2[tid] = val2; @@ -212,15 +118,19 @@ __local volatile float* smem1, __local volatile float* smem2, __local volatile f smem2[tid] += smem2[tid + 32]; smem3[tid] += smem3[tid + 32]; #if WAVE_SIZE < 32 - } barrier(CLK_LOCAL_MEM_FENCE); - if (tid < 16) { + } + barrier(CLK_LOCAL_MEM_FENCE); + if (tid < 16) + { #endif smem1[tid] += smem1[tid + 16]; smem2[tid] += smem2[tid + 16]; smem3[tid] += smem3[tid + 16]; #if WAVE_SIZE <16 - } barrier(CLK_LOCAL_MEM_FENCE); - if (tid < 8) { + } + barrier(CLK_LOCAL_MEM_FENCE); + if (tid < 8) + { #endif smem1[tid] += smem1[tid + 8]; smem2[tid] += smem2[tid + 8]; @@ -238,6 +148,7 @@ __local volatile float* smem1, __local volatile float* smem2, __local volatile f smem2[tid] += smem2[tid + 1]; smem3[tid] += smem3[tid + 1]; } + barrier(CLK_LOCAL_MEM_FENCE); } void reduce2(float val1, float val2, __local volatile float* smem1, __local volatile float* smem2, int tid) @@ -251,14 +162,18 @@ void reduce2(float val1, float val2, __local volatile float* smem1, __local vola smem1[tid] += smem1[tid + 32]; smem2[tid] += smem2[tid + 32]; #if WAVE_SIZE < 32 - } barrier(CLK_LOCAL_MEM_FENCE); - if (tid < 16) { + } + barrier(CLK_LOCAL_MEM_FENCE); + if (tid < 16) + { #endif smem1[tid] += smem1[tid + 16]; smem2[tid] += smem2[tid + 16]; #if WAVE_SIZE <16 - } barrier(CLK_LOCAL_MEM_FENCE); - if (tid < 8) { + } + barrier(CLK_LOCAL_MEM_FENCE); + if (tid < 8) + { #endif smem1[tid] += smem1[tid + 8]; smem2[tid] += smem2[tid + 8]; @@ -272,6 +187,7 @@ void reduce2(float val1, float val2, __local volatile float* smem1, __local vola smem1[tid] += smem1[tid + 1]; smem2[tid] += smem2[tid + 1]; } + barrier(CLK_LOCAL_MEM_FENCE); } void reduce1(float val1, __local volatile float* smem1, int tid) @@ -283,19 +199,24 @@ void reduce1(float val1, __local volatile float* smem1, int tid) { smem1[tid] += smem1[tid + 32]; #if WAVE_SIZE < 32 - } barrier(CLK_LOCAL_MEM_FENCE); - if (tid < 16) { + } + barrier(CLK_LOCAL_MEM_FENCE); + if (tid < 16) + { #endif smem1[tid] += smem1[tid + 16]; #if WAVE_SIZE <16 - } barrier(CLK_LOCAL_MEM_FENCE); - if (tid < 8) { + } + barrier(CLK_LOCAL_MEM_FENCE); + if (tid < 8) + { #endif smem1[tid] += smem1[tid + 8]; smem1[tid] += smem1[tid + 4]; smem1[tid] += smem1[tid + 2]; smem1[tid] += smem1[tid + 1]; } + barrier(CLK_LOCAL_MEM_FENCE); } #endif @@ -306,106 +227,100 @@ void reduce1(float val1, __local volatile float* smem1, int tid) __constant sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP_TO_EDGE | CLK_FILTER_LINEAR; void SetPatch(image2d_t I, float x, float y, - float* Pch, float* Dx, float* Dy, - float* A11, float* A12, float* A22) + float* Pch, float* Dx, float* Dy, + float* A11, float* A12, float* A22) { - *Pch = read_imagef(I, sampler, (float2)(x, y)).x; + *Pch = read_imagef(I, sampler, (float2)(x, y)).x; - float dIdx = 3.0f * read_imagef(I, sampler, (float2)(x + 1, y - 1)).x + 10.0f * read_imagef(I, sampler, (float2)(x + 1, y)).x + 3.0f * read_imagef(I, sampler, (float2)(x + 1, y + 1)).x - - (3.0f * read_imagef(I, sampler, (float2)(x - 1, y - 1)).x + 10.0f * read_imagef(I, sampler, (float2)(x - 1, y)).x + 3.0f * read_imagef(I, sampler, (float2)(x - 1, y + 1)).x); + float dIdx = 3.0f * read_imagef(I, sampler, (float2)(x + 1, y - 1)).x + 10.0f * read_imagef(I, sampler, (float2)(x + 1, y)).x + 3.0f * read_imagef(I, sampler, (float2)(x + 1, y + 1)).x - + (3.0f * read_imagef(I, sampler, (float2)(x - 1, y - 1)).x + 10.0f * read_imagef(I, sampler, (float2)(x - 1, y)).x + 3.0f * read_imagef(I, sampler, (float2)(x - 1, y + 1)).x); - float dIdy = 3.0f * read_imagef(I, sampler, (float2)(x - 1, y + 1)).x + 10.0f * read_imagef(I, sampler, (float2)(x, y + 1)).x + 3.0f * read_imagef(I, sampler, (float2)(x + 1, y + 1)).x - - (3.0f * read_imagef(I, sampler, (float2)(x - 1, y - 1)).x + 10.0f * read_imagef(I, sampler, (float2)(x, y - 1)).x + 3.0f * read_imagef(I, sampler, (float2)(x + 1, y - 1)).x); + float dIdy = 3.0f * read_imagef(I, sampler, (float2)(x - 1, y + 1)).x + 10.0f * read_imagef(I, sampler, (float2)(x, y + 1)).x + 3.0f * read_imagef(I, sampler, (float2)(x + 1, y + 1)).x - + (3.0f * read_imagef(I, sampler, (float2)(x - 1, y - 1)).x + 10.0f * read_imagef(I, sampler, (float2)(x, y - 1)).x + 3.0f * read_imagef(I, sampler, (float2)(x + 1, y - 1)).x); - *Dx = dIdx; - *Dy = dIdy; + *Dx = dIdx; + *Dy = dIdy; - *A11 += dIdx * dIdx; - *A12 += dIdx * dIdy; - *A22 += dIdy * dIdy; + *A11 += dIdx * dIdx; + *A12 += dIdx * dIdy; + *A22 += dIdy * dIdy; } void GetPatch(image2d_t J, float x, float y, - float* Pch, float* Dx, float* Dy, - float* b1, float* b2) + float* Pch, float* Dx, float* Dy, + float* b1, float* b2) { - float J_val = read_imagef(J, sampler, (float2)(x, y)).x; - float diff = (J_val - *Pch) * 32.0f; - *b1 += diff**Dx; - *b2 += diff**Dy; + float J_val = read_imagef(J, sampler, (float2)(x, y)).x; + float diff = (J_val - *Pch) * 32.0f; + *b1 += diff**Dx; + *b2 += diff**Dy; } void GetError(image2d_t J, const float x, const float y, const float* Pch, float* errval) { - float diff = read_imagef(J, sampler, (float2)(x,y)).x-*Pch; - *errval += fabs(diff); + float diff = read_imagef(J, sampler, (float2)(x,y)).x-*Pch; + *errval += fabs(diff); } void SetPatch4(image2d_t I, const float x, const float y, - float4* Pch, float4* Dx, float4* Dy, - float* A11, float* A12, float* A22) + float4* Pch, float4* Dx, float4* Dy, + float* A11, float* A12, float* A22) { - *Pch = read_imagef(I, sampler, (float2)(x, y)); + *Pch = read_imagef(I, sampler, (float2)(x, y)); - float4 dIdx = 3.0f * read_imagef(I, sampler, (float2)(x + 1, y - 1)) + 10.0f * read_imagef(I, sampler, (float2)(x + 1, y)) + 3.0f * read_imagef(I, sampler, (float2)(x + 1, y + 1)) - - (3.0f * read_imagef(I, sampler, (float2)(x - 1, y - 1)) + 10.0f * read_imagef(I, sampler, (float2)(x - 1, y)) + 3.0f * read_imagef(I, sampler, (float2)(x - 1, y + 1))); + float4 dIdx = 3.0f * read_imagef(I, sampler, (float2)(x + 1, y - 1)) + 10.0f * read_imagef(I, sampler, (float2)(x + 1, y)) + 3.0f * read_imagef(I, sampler, (float2)(x + 1, y + 1)) - + (3.0f * read_imagef(I, sampler, (float2)(x - 1, y - 1)) + 10.0f * read_imagef(I, sampler, (float2)(x - 1, y)) + 3.0f * read_imagef(I, sampler, (float2)(x - 1, y + 1))); - float4 dIdy = 3.0f * read_imagef(I, sampler, (float2)(x - 1, y + 1)) + 10.0f * read_imagef(I, sampler, (float2)(x, y + 1)) + 3.0f * read_imagef(I, sampler, (float2)(x + 1, y + 1)) - - (3.0f * read_imagef(I, sampler, (float2)(x - 1, y - 1)) + 10.0f * read_imagef(I, sampler, (float2)(x, y - 1)) + 3.0f * read_imagef(I, sampler, (float2)(x + 1, y - 1))); + float4 dIdy = 3.0f * read_imagef(I, sampler, (float2)(x - 1, y + 1)) + 10.0f * read_imagef(I, sampler, (float2)(x, y + 1)) + 3.0f * read_imagef(I, sampler, (float2)(x + 1, y + 1)) - + (3.0f * read_imagef(I, sampler, (float2)(x - 1, y - 1)) + 10.0f * read_imagef(I, sampler, (float2)(x, y - 1)) + 3.0f * read_imagef(I, sampler, (float2)(x + 1, y - 1))); - *Dx = dIdx; - *Dy = dIdy; - float4 sqIdx = dIdx * dIdx; - *A11 += sqIdx.x + sqIdx.y + sqIdx.z; - sqIdx = dIdx * dIdy; - *A12 += sqIdx.x + sqIdx.y + sqIdx.z; - sqIdx = dIdy * dIdy; - *A22 += sqIdx.x + sqIdx.y + sqIdx.z; + *Dx = dIdx; + *Dy = dIdy; + float4 sqIdx = dIdx * dIdx; + *A11 += sqIdx.x + sqIdx.y + sqIdx.z; + sqIdx = dIdx * dIdy; + *A12 += sqIdx.x + sqIdx.y + sqIdx.z; + sqIdx = dIdy * dIdy; + *A22 += sqIdx.x + sqIdx.y + sqIdx.z; } void GetPatch4(image2d_t J, const float x, const float y, - const float4* Pch, const float4* Dx, const float4* Dy, - float* b1, float* b2) + const float4* Pch, const float4* Dx, const float4* Dy, + float* b1, float* b2) { - float4 J_val = read_imagef(J, sampler, (float2)(x, y)); - float4 diff = (J_val - *Pch) * 32.0f; - float4 xdiff = diff* *Dx; - *b1 += xdiff.x + xdiff.y + xdiff.z; - xdiff = diff* *Dy; - *b2 += xdiff.x + xdiff.y + xdiff.z; + float4 J_val = read_imagef(J, sampler, (float2)(x, y)); + float4 diff = (J_val - *Pch) * 32.0f; + float4 xdiff = diff* *Dx; + *b1 += xdiff.x + xdiff.y + xdiff.z; + xdiff = diff* *Dy; + *b2 += xdiff.x + xdiff.y + xdiff.z; } void GetError4(image2d_t J, const float x, const float y, const float4* Pch, float* errval) { - float4 diff = read_imagef(J, sampler, (float2)(x,y))-*Pch; - *errval += fabs(diff.x) + fabs(diff.y) + fabs(diff.z); + float4 diff = read_imagef(J, sampler, (float2)(x,y))-*Pch; + *errval += fabs(diff.x) + fabs(diff.y) + fabs(diff.z); } #define GRIDSIZE 3 __kernel void lkSparse_C1_D5(image2d_t I, image2d_t J, - __global const float2* prevPts, int prevPtsStep, __global float2* nextPts, int nextPtsStep, __global uchar* status, __global float* err, - const int level, const int rows, const int cols, int PATCH_X, int PATCH_Y, int cn, int c_winSize_x, int c_winSize_y, int c_iters, char calcErr) + __global const float2* prevPts, int prevPtsStep, __global float2* nextPts, int nextPtsStep, __global uchar* status, __global float* err, + const int level, const int rows, const int cols, int PATCH_X, int PATCH_Y, int cn, int c_winSize_x, int c_winSize_y, int c_iters, char calcErr) { -#ifdef CPU - __local float smem1[BUFFER+1]; - __local float smem2[BUFFER+1]; - __local float smem3[BUFFER+1]; -#else __local float smem1[BUFFER]; __local float smem2[BUFFER]; __local float smem3[BUFFER]; -#endif - unsigned int xid=get_local_id(0); - unsigned int yid=get_local_id(1); - unsigned int gid=get_group_id(0); - unsigned int xsize=get_local_size(0); - unsigned int ysize=get_local_size(1); - int xBase, yBase, i, j, k; + unsigned int xid=get_local_id(0); + unsigned int yid=get_local_id(1); + unsigned int gid=get_group_id(0); + unsigned int xsize=get_local_size(0); + unsigned int ysize=get_local_size(1); + int xBase, yBase, i, j, k; - float2 c_halfWin = (float2)((c_winSize_x - 1)>>1, (c_winSize_y - 1)>>1); + float2 c_halfWin = (float2)((c_winSize_x - 1)>>1, (c_winSize_y - 1)>>1); const int tid = mad24(yid, xsize, xid); @@ -432,77 +347,71 @@ __kernel void lkSparse_C1_D5(image2d_t I, image2d_t J, float dIdx_patch[GRIDSIZE][GRIDSIZE]; float dIdy_patch[GRIDSIZE][GRIDSIZE]; - yBase=yid; - { - xBase=xid; - SetPatch(I, prevPt.x + xBase + 0.5f, prevPt.y + yBase + 0.5f, - &I_patch[0][0], &dIdx_patch[0][0], &dIdy_patch[0][0], - &A11, &A12, &A22); - - - xBase+=xsize; - SetPatch(I, prevPt.x + xBase + 0.5f, prevPt.y + yBase + 0.5f, - &I_patch[0][1], &dIdx_patch[0][1], &dIdy_patch[0][1], - &A11, &A12, &A22); - - xBase+=xsize; - if(xBase>1, (c_winSize_y - 1)>>1); + float2 c_halfWin = (float2)((c_winSize_x - 1)>>1, (c_winSize_y - 1)>>1); const int tid = mad24(yid, xsize, xid); @@ -721,7 +615,7 @@ __kernel void lkSparse_C4_D5(image2d_t I, image2d_t J, return; } - nextPt -= c_halfWin; + nextPt -= c_halfWin; // extract the patch from the first image, compute covariation matrix of derivatives @@ -732,80 +626,74 @@ __kernel void lkSparse_C4_D5(image2d_t I, image2d_t J, float4 I_patch[8]; float4 dIdx_patch[8]; float4 dIdy_patch[8]; - float4 I_add,Dx_add,Dy_add; + float4 I_add,Dx_add,Dy_add; - yBase=yid; - { - xBase=xid; - SetPatch4(I, nextPt.x + xBase + 0.5f, nextPt.y + yBase + 0.5f, - &I_patch[0], &dIdx_patch[0], &dIdy_patch[0], - &A11, &A12, &A22); + yBase=yid; + { + xBase=xid; + SetPatch4(I, nextPt.x + xBase + 0.5f, nextPt.y + yBase + 0.5f, + &I_patch[0], &dIdx_patch[0], &dIdy_patch[0], + &A11, &A12, &A22); - xBase+=xsize; - SetPatch4(I, nextPt.x + xBase + 0.5f, nextPt.y + yBase + 0.5f, - &I_patch[1], &dIdx_patch[1], &dIdy_patch[1], - &A11, &A12, &A22); + xBase+=xsize; + SetPatch4(I, nextPt.x + xBase + 0.5f, nextPt.y + yBase + 0.5f, + &I_patch[1], &dIdx_patch[1], &dIdy_patch[1], + &A11, &A12, &A22); - xBase+=xsize; - if(xBase #include diff --git a/modules/ocl/src/sort_by_key.cpp b/modules/ocl/src/sort_by_key.cpp new file mode 100644 index 0000000000..32af2a2fef --- /dev/null +++ b/modules/ocl/src/sort_by_key.cpp @@ -0,0 +1,454 @@ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved. +// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// @Authors +// Peng Xiao, pengxiao@outlook.com +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other oclMaterials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors as is and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#include +#include "precomp.hpp" + +namespace cv +{ +namespace ocl +{ + +extern const char * kernel_sort_by_key; +extern const char * kernel_stablesort_by_key; +extern const char * kernel_radix_sort_by_key; + +void sortByKey(oclMat& keys, oclMat& vals, size_t vecSize, int method, bool isGreaterThan); + +//TODO(pengx17): change this value depending on device other than a constant +const static unsigned int GROUP_SIZE = 256; + +const char * depth_strings[] = +{ + "uchar", //CV_8U + "char", //CV_8S + "ushort", //CV_16U + "short", //CV_16S + "int", //CV_32S + "float", //CV_32F + "double" //CV_64F +}; + +void static genSortBuildOption(const oclMat& keys, const oclMat& vals, bool isGreaterThan, char * build_opt_buf) +{ + sprintf(build_opt_buf, "-D IS_GT=%d -D K_T=%s -D V_T=%s", + isGreaterThan?1:0, depth_strings[keys.depth()], depth_strings[vals.depth()]); + if(vals.oclchannels() > 1) + { + sprintf( build_opt_buf + strlen(build_opt_buf), "%d", vals.oclchannels()); + } +} +inline bool isSizePowerOf2(size_t size) +{ + return ((size - 1) & (size)) == 0; +} + +namespace bitonic_sort +{ +static void sortByKey(oclMat& keys, oclMat& vals, size_t vecSize, bool isGreaterThan) +{ + CV_Assert(isSizePowerOf2(vecSize)); + + Context * cxt = Context::getContext(); + size_t globalThreads[3] = {vecSize / 2, 1, 1}; + size_t localThreads[3] = {GROUP_SIZE, 1, 1}; + + // 2^numStages should be equal to vecSize or the output is invalid + int numStages = 0; + for(int i = vecSize; i > 1; i >>= 1) + { + ++numStages; + } + char build_opt_buf [100]; + genSortBuildOption(keys, vals, isGreaterThan, build_opt_buf); + const int argc = 5; + std::vector< std::pair > args(argc); + String kernelname = "bitonicSort"; + + args[0] = std::make_pair(sizeof(cl_mem), (void *)&keys.data); + args[1] = std::make_pair(sizeof(cl_mem), (void *)&vals.data); + args[2] = std::make_pair(sizeof(cl_int), (void *)&vecSize); + + for(int stage = 0; stage < numStages; ++stage) + { + args[3] = std::make_pair(sizeof(cl_int), (void *)&stage); + for(int passOfStage = 0; passOfStage < stage + 1; ++passOfStage) + { + args[4] = std::make_pair(sizeof(cl_int), (void *)&passOfStage); + openCLExecuteKernel(cxt, &kernel_sort_by_key, kernelname, globalThreads, localThreads, args, -1, -1, build_opt_buf); + } + } +} +} /* bitonic_sort */ + +namespace selection_sort +{ +// FIXME: +// This function cannot sort arrays with duplicated keys +static void sortByKey(oclMat& keys, oclMat& vals, size_t vecSize, bool isGreaterThan) +{ + CV_Error(-1, "This function is incorrect at the moment."); + Context * cxt = Context::getContext(); + + size_t globalThreads[3] = {vecSize, 1, 1}; + size_t localThreads[3] = {GROUP_SIZE, 1, 1}; + + std::vector< std::pair > args; + char build_opt_buf [100]; + genSortBuildOption(keys, vals, isGreaterThan, build_opt_buf); + + //local + String kernelname = "selectionSortLocal"; + int lds_size = GROUP_SIZE * keys.elemSize(); + args.push_back(std::make_pair(sizeof(cl_mem), (void *)&keys.data)); + args.push_back(std::make_pair(sizeof(cl_mem), (void *)&vals.data)); + args.push_back(std::make_pair(sizeof(cl_int), (void *)&vecSize)); + args.push_back(std::make_pair(lds_size, (void*)NULL)); + + openCLExecuteKernel(cxt, &kernel_sort_by_key, kernelname, globalThreads, localThreads, args, -1, -1, build_opt_buf); + + //final + kernelname = "selectionSortFinal"; + args.pop_back(); + openCLExecuteKernel(cxt, &kernel_sort_by_key, kernelname, globalThreads, localThreads, args, -1, -1, build_opt_buf); +} + +} /* selection_sort */ + + +namespace radix_sort +{ +//FIXME(pengx17): +// exclusive scan, need to be optimized as this is too naive... +//void naive_scan_addition(oclMat& input, oclMat& output) +//{ +// Context * cxt = Context::getContext(); +// size_t vecSize = input.cols; +// size_t globalThreads[3] = {1, 1, 1}; +// size_t localThreads[3] = {1, 1, 1}; +// +// String kernelname = "naiveScanAddition"; +// +// std::vector< std::pair > args; +// args.push_back(std::make_pair(sizeof(cl_mem), (void *)&input.data)); +// args.push_back(std::make_pair(sizeof(cl_mem), (void *)&output.data)); +// args.push_back(std::make_pair(sizeof(cl_int), (void *)&vecSize)); +// openCLExecuteKernel(cxt, &kernel_radix_sort_by_key, kernelname, globalThreads, localThreads, args, -1, -1); +//} + +void static naive_scan_addition_cpu(oclMat& input, oclMat& output) +{ + Mat m_input = input, m_output(output.size(), output.type()); + MatIterator_ i_mit = m_input.begin(); + MatIterator_ o_mit = m_output.begin(); + *o_mit = 0; + ++i_mit; + ++o_mit; + for(; i_mit != m_input.end(); ++i_mit, ++o_mit) + { + *o_mit = *(o_mit - 1) + *(i_mit - 1); + } + output = m_output; +} + + +//radix sort ported from Bolt +static void sortByKey(oclMat& keys, oclMat& vals, size_t origVecSize, bool isGreaterThan) +{ + CV_Assert(keys.depth() == CV_32S || keys.depth() == CV_32F); // we assume keys are 4 bytes + + bool isKeyFloat = keys.type() == CV_32F; + + const int RADIX = 4; //Now you cannot replace this with Radix 8 since there is a + //local array of 16 elements in the histogram kernel. + const int RADICES = (1 << RADIX); //Values handeled by each work-item? + + bool newBuffer = false; + size_t vecSize = origVecSize; + + unsigned int groupSize = RADICES; + + size_t mulFactor = groupSize * RADICES; + + oclMat buffer_keys, buffer_vals; + + if(origVecSize % mulFactor != 0) + { + vecSize = ((vecSize + mulFactor) / mulFactor) * mulFactor; + buffer_keys.create(1, vecSize, keys.type()); + buffer_vals.create(1, vecSize, vals.type()); + Scalar padding_value; + oclMat roi_buffer_vals = buffer_vals(Rect(0,0,origVecSize,1)); + + if(isGreaterThan) + { + switch(buffer_keys.depth()) + { + case CV_32F: + padding_value = Scalar::all(-FLT_MAX); + break; + case CV_32S: + padding_value = Scalar::all(INT_MIN); + break; + } + } + else + { + switch(buffer_keys.depth()) + { + case CV_32F: + padding_value = Scalar::all(FLT_MAX); + break; + case CV_32S: + padding_value = Scalar::all(INT_MAX); + break; + } + } + ocl::copyMakeBorder( + keys(Rect(0,0,origVecSize,1)), buffer_keys, + 0, 0, 0, vecSize - origVecSize, + BORDER_CONSTANT, padding_value); + vals(Rect(0,0,origVecSize,1)).copyTo(roi_buffer_vals); + newBuffer = true; + } + else + { + buffer_keys = keys; + buffer_vals = vals; + newBuffer = false; + } + oclMat swap_input_keys(1, vecSize, keys.type()); + oclMat swap_input_vals(1, vecSize, vals.type()); + oclMat hist_bin_keys(1, vecSize, CV_32SC1); + oclMat hist_bin_dest_keys(1, vecSize, CV_32SC1); + + Context * cxt = Context::getContext(); + + size_t globalThreads[3] = {vecSize / RADICES, 1, 1}; + size_t localThreads[3] = {groupSize, 1, 1}; + + std::vector< std::pair > args; + char build_opt_buf [100]; + genSortBuildOption(keys, vals, isGreaterThan, build_opt_buf); + + //additional build option for radix sort + sprintf(build_opt_buf + strlen(build_opt_buf), " -D K_%s", isKeyFloat?"FLT":"INT"); + + String kernelnames[2] = {String("histogramRadixN"), String("permuteRadixN")}; + + int swap = 0; + for(int bits = 0; bits < (static_cast(keys.elemSize()) * 8); bits += RADIX) + { + args.clear(); + //Do a histogram pass locally + if(swap == 0) + { + args.push_back(std::make_pair(sizeof(cl_mem), (void *)&buffer_keys.data)); + } + else + { + args.push_back(std::make_pair(sizeof(cl_mem), (void *)&swap_input_keys.data)); + } + args.push_back(std::make_pair(sizeof(cl_mem), (void *)&hist_bin_keys.data)); + args.push_back(std::make_pair(sizeof(cl_int), (void *)&bits)); + openCLExecuteKernel(cxt, &kernel_radix_sort_by_key, kernelnames[0], globalThreads, localThreads, + args, -1, -1, build_opt_buf); + + args.clear(); + //Perform a global scan + naive_scan_addition_cpu(hist_bin_keys, hist_bin_dest_keys); + // end of scan + if(swap == 0) + { + args.push_back(std::make_pair(sizeof(cl_mem), (void *)&buffer_keys.data)); + args.push_back(std::make_pair(sizeof(cl_mem), (void *)&buffer_vals.data)); + } + else + { + args.push_back(std::make_pair(sizeof(cl_mem), (void *)&swap_input_keys.data)); + args.push_back(std::make_pair(sizeof(cl_mem), (void *)&swap_input_vals.data)); + } + args.push_back(std::make_pair(sizeof(cl_mem), (void *)&hist_bin_dest_keys.data)); + args.push_back(std::make_pair(sizeof(cl_int), (void *)&bits)); + + if(swap == 0) + { + args.push_back(std::make_pair(sizeof(cl_mem), (void *)&swap_input_keys.data)); + args.push_back(std::make_pair(sizeof(cl_mem), (void *)&swap_input_vals.data)); + } + else + { + args.push_back(std::make_pair(sizeof(cl_mem), (void *)&buffer_keys.data)); + args.push_back(std::make_pair(sizeof(cl_mem), (void *)&buffer_vals.data)); + } + openCLExecuteKernel(cxt, &kernel_radix_sort_by_key, kernelnames[1], globalThreads, localThreads, + args, -1, -1, build_opt_buf); + swap = swap ? 0 : 1; + } + if(newBuffer) + { + buffer_keys(Rect(0,0,origVecSize,1)).copyTo(keys); + buffer_vals(Rect(0,0,origVecSize,1)).copyTo(vals); + } +} + +} /* radix_sort */ + +namespace merge_sort +{ +static void sortByKey(oclMat& keys, oclMat& vals, size_t vecSize, bool isGreaterThan) +{ + Context * cxt = Context::getContext(); + + size_t globalThreads[3] = {vecSize, 1, 1}; + size_t localThreads[3] = {GROUP_SIZE, 1, 1}; + + std::vector< std::pair > args; + char build_opt_buf [100]; + genSortBuildOption(keys, vals, isGreaterThan, build_opt_buf); + + String kernelname[] = {String("blockInsertionSort"), String("merge")}; + int keylds_size = GROUP_SIZE * keys.elemSize(); + int vallds_size = GROUP_SIZE * vals.elemSize(); + args.push_back(std::make_pair(sizeof(cl_mem), (void *)&keys.data)); + args.push_back(std::make_pair(sizeof(cl_mem), (void *)&vals.data)); + args.push_back(std::make_pair(sizeof(cl_uint), (void *)&vecSize)); + args.push_back(std::make_pair(keylds_size, (void*)NULL)); + args.push_back(std::make_pair(vallds_size, (void*)NULL)); + + openCLExecuteKernel(cxt, &kernel_stablesort_by_key, kernelname[0], globalThreads, localThreads, args, -1, -1, build_opt_buf); + + // Early exit for the case of no merge passes, values are already in destination vector + if(vecSize <= GROUP_SIZE) + { + return; + } + + // An odd number of elements requires an extra merge pass to sort + size_t numMerges = 0; + // Calculate the log2 of vecSize, taking into acvecSize our block size from kernel 1 is 64 + // this is how many merge passes we want + size_t log2BlockSize = vecSize >> 6; + for( ; log2BlockSize > 1; log2BlockSize >>= 1 ) + { + ++numMerges; + } + // Check to see if the input vector size is a power of 2, if not we will need last merge pass + numMerges += isSizePowerOf2(vecSize)? 1: 0; + + // Allocate a flipflop buffer because the merge passes are out of place + oclMat tmpKeyBuffer(keys.size(), keys.type()); + oclMat tmpValBuffer(vals.size(), vals.type()); + args.resize(8); + + args[4] = std::make_pair(sizeof(cl_uint), (void *)&vecSize); + args[6] = std::make_pair(keylds_size, (void*)NULL); + args[7] = std::make_pair(vallds_size, (void*)NULL); + + for(size_t pass = 1; pass <= numMerges; ++pass ) + { + // For each pass, flip the input-output buffers + if( pass & 0x1 ) + { + args[0] = std::make_pair(sizeof(cl_mem), (void *)&keys.data); + args[1] = std::make_pair(sizeof(cl_mem), (void *)&vals.data); + args[2] = std::make_pair(sizeof(cl_mem), (void *)&tmpKeyBuffer.data); + args[3] = std::make_pair(sizeof(cl_mem), (void *)&tmpValBuffer.data); + } + else + { + args[0] = std::make_pair(sizeof(cl_mem), (void *)&tmpKeyBuffer.data); + args[1] = std::make_pair(sizeof(cl_mem), (void *)&tmpValBuffer.data); + args[2] = std::make_pair(sizeof(cl_mem), (void *)&keys.data); + args[3] = std::make_pair(sizeof(cl_mem), (void *)&vals.data); + } + // For each pass, the merge window doubles + unsigned int srcLogicalBlockSize = static_cast( localThreads[0] << (pass-1) ); + args[5] = std::make_pair(sizeof(cl_uint), (void *)&srcLogicalBlockSize); + openCLExecuteKernel(cxt, &kernel_stablesort_by_key, kernelname[1], globalThreads, localThreads, args, -1, -1, build_opt_buf); + } + // If there are an odd number of merges, then the output data is sitting in the temp buffer. We need to copy + // the results back into the input array + if( numMerges & 1 ) + { + tmpKeyBuffer.copyTo(keys); + tmpValBuffer.copyTo(vals); + } +} +} /* merge_sort */ + +} +} /* namespace cv { namespace ocl */ + + +void cv::ocl::sortByKey(oclMat& keys, oclMat& vals, size_t vecSize, int method, bool isGreaterThan) +{ + CV_Assert( keys.rows == 1 ); // we only allow one dimensional input + CV_Assert( keys.channels() == 1 ); // we only allow one channel keys + CV_Assert( vecSize <= static_cast(keys.cols) ); + switch(method) + { + case SORT_BITONIC: + bitonic_sort::sortByKey(keys, vals, vecSize, isGreaterThan); + break; + case SORT_SELECTION: + selection_sort::sortByKey(keys, vals, vecSize, isGreaterThan); + break; + case SORT_RADIX: + radix_sort::sortByKey(keys, vals, vecSize, isGreaterThan); + break; + case SORT_MERGE: + merge_sort::sortByKey(keys, vals, vecSize, isGreaterThan); + break; + } +} + +void cv::ocl::sortByKey(oclMat& keys, oclMat& vals, int method, bool isGreaterThan) +{ + CV_Assert( keys.size() == vals.size() ); + CV_Assert( keys.rows == 1 ); // we only allow one dimensional input + size_t vecSize = static_cast(keys.cols); + sortByKey(keys, vals, vecSize, method, isGreaterThan); +} diff --git a/modules/ocl/test/main.cpp b/modules/ocl/test/main.cpp index 4ba02cf9bc..594c196a59 100644 --- a/modules/ocl/test/main.cpp +++ b/modules/ocl/test/main.cpp @@ -39,7 +39,7 @@ // //M*/ -#include "precomp.hpp" +#include "test_precomp.hpp" #ifdef HAVE_OPENCL @@ -73,14 +73,12 @@ void print_info() #endif } -std::string workdir; int main(int argc, char **argv) { - TS::ptr()->init("ocl"); + TS::ptr()->init("."); InitGoogleTest(&argc, argv); const char *keys = "{ h | help | false | print help message }" - "{ w | workdir | ../../../samples/c/| set working directory }" "{ t | type | gpu | set device type:cpu or gpu}" "{ p | platform | 0 | set platform id }" "{ d | device | 0 | set device id }"; @@ -92,7 +90,6 @@ int main(int argc, char **argv) cmd.printParams(); return 0; } - workdir = cmd.get("workdir"); string type = cmd.get("type"); unsigned int pid = cmd.get("platform"); int device = cmd.get("device"); diff --git a/modules/ocl/test/precomp.cpp b/modules/ocl/test/precomp.cpp deleted file mode 100644 index 7d287004ee..0000000000 --- a/modules/ocl/test/precomp.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/*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 "precomp.hpp" - - diff --git a/modules/ocl/test/test_arithm.cpp b/modules/ocl/test/test_arithm.cpp index d12cef0b22..149c172efa 100644 --- a/modules/ocl/test/test_arithm.cpp +++ b/modules/ocl/test/test_arithm.cpp @@ -54,7 +54,7 @@ //#define PRINT_TIME -#include "precomp.hpp" +#include "test_precomp.hpp" #include #ifdef HAVE_OPENCL diff --git a/modules/ocl/test/test_blend.cpp b/modules/ocl/test/test_blend.cpp index fa1aea1727..9341981609 100644 --- a/modules/ocl/test/test_blend.cpp +++ b/modules/ocl/test/test_blend.cpp @@ -42,7 +42,7 @@ // the use of this software, even if advised of the possibility of such damage. // //M*/ -#include "precomp.hpp" +#include "test_precomp.hpp" #include using namespace cv; diff --git a/modules/ocl/test/test_brute_force_matcher.cpp b/modules/ocl/test/test_brute_force_matcher.cpp index 11fdbb3598..7d8fc368f8 100644 --- a/modules/ocl/test/test_brute_force_matcher.cpp +++ b/modules/ocl/test/test_brute_force_matcher.cpp @@ -43,7 +43,7 @@ // //M*/ -#include "precomp.hpp" +#include "test_precomp.hpp" #ifdef HAVE_OPENCL namespace { diff --git a/modules/ocl/test/test_calib3d.cpp b/modules/ocl/test/test_calib3d.cpp index 14fb31f53a..7e5c4a4196 100644 --- a/modules/ocl/test/test_calib3d.cpp +++ b/modules/ocl/test/test_calib3d.cpp @@ -43,14 +43,13 @@ // //M*/ -#include "precomp.hpp" +#include "test_precomp.hpp" #include #ifdef HAVE_OPENCL using namespace cv; -extern std::string workdir; PARAM_TEST_CASE(StereoMatchBM, int, int) { int n_disp; @@ -66,9 +65,9 @@ PARAM_TEST_CASE(StereoMatchBM, int, int) TEST_P(StereoMatchBM, Regression) { - Mat left_image = readImage("stereobm/aloe-L.png", IMREAD_GRAYSCALE); - Mat right_image = readImage("stereobm/aloe-R.png", IMREAD_GRAYSCALE); - Mat disp_gold = readImage("stereobm/aloe-disp.png", IMREAD_GRAYSCALE); + Mat left_image = readImage("gpu/stereobm/aloe-L.png", IMREAD_GRAYSCALE); + Mat right_image = readImage("gpu/stereobm/aloe-R.png", IMREAD_GRAYSCALE); + Mat disp_gold = readImage("gpu/stereobm/aloe-disp.png", IMREAD_GRAYSCALE); ocl::oclMat d_left, d_right; ocl::oclMat d_disp(left_image.size(), CV_8U); Mat disp; @@ -113,9 +112,9 @@ PARAM_TEST_CASE(StereoMatchBP, int, int, int, float, float, float, float) }; TEST_P(StereoMatchBP, Regression) { - Mat left_image = readImage("stereobp/aloe-L.png"); - Mat right_image = readImage("stereobp/aloe-R.png"); - Mat disp_gold = readImage("stereobp/aloe-disp.png", IMREAD_GRAYSCALE); + Mat left_image = readImage("gpu/stereobp/aloe-L.png"); + Mat right_image = readImage("gpu/stereobp/aloe-R.png"); + Mat disp_gold = readImage("gpu/stereobp/aloe-disp.png", IMREAD_GRAYSCALE); ocl::oclMat d_left, d_right; ocl::oclMat d_disp; Mat disp; @@ -166,9 +165,9 @@ PARAM_TEST_CASE(StereoMatchConstSpaceBP, int, int, int, int, float, float, float }; TEST_P(StereoMatchConstSpaceBP, Regression) { - Mat left_image = readImage("csstereobp/aloe-L.png"); - Mat right_image = readImage("csstereobp/aloe-R.png"); - Mat disp_gold = readImage("csstereobp/aloe-disp.png", IMREAD_GRAYSCALE); + Mat left_image = readImage("gpu/csstereobp/aloe-L.png"); + Mat right_image = readImage("gpu/csstereobp/aloe-R.png"); + Mat disp_gold = readImage("gpu/csstereobp/aloe-disp.png", IMREAD_GRAYSCALE); ocl::oclMat d_left, d_right; ocl::oclMat d_disp; diff --git a/modules/ocl/test/test_canny.cpp b/modules/ocl/test/test_canny.cpp index 10032e897c..6c6ea4eddb 100644 --- a/modules/ocl/test/test_canny.cpp +++ b/modules/ocl/test/test_canny.cpp @@ -43,12 +43,11 @@ // //M*/ -#include "precomp.hpp" +#include "test_precomp.hpp" #ifdef HAVE_OPENCL //////////////////////////////////////////////////////// // Canny -extern std::string workdir; IMPLEMENT_PARAM_CLASS(AppertureSize, int); IMPLEMENT_PARAM_CLASS(L2gradient, bool); @@ -67,7 +66,7 @@ PARAM_TEST_CASE(Canny, AppertureSize, L2gradient) TEST_P(Canny, Accuracy) { - cv::Mat img = readImage(workdir + "fruits.jpg", cv::IMREAD_GRAYSCALE); + cv::Mat img = readImage("cv/shared/fruits.png", cv::IMREAD_GRAYSCALE); ASSERT_FALSE(img.empty()); double low_thresh = 50.0; diff --git a/modules/ocl/test/test_color.cpp b/modules/ocl/test/test_color.cpp index 9748104de6..a0293fc454 100644 --- a/modules/ocl/test/test_color.cpp +++ b/modules/ocl/test/test_color.cpp @@ -43,7 +43,7 @@ // //M*/ -#include "precomp.hpp" +#include "test_precomp.hpp" #ifdef HAVE_OPENCL //#define MAT_DEBUG diff --git a/modules/ocl/test/test_fft.cpp b/modules/ocl/test/test_fft.cpp index fda55ddcc2..08e70e2f96 100644 --- a/modules/ocl/test/test_fft.cpp +++ b/modules/ocl/test/test_fft.cpp @@ -43,7 +43,7 @@ // //M*/ -#include "precomp.hpp" +#include "test_precomp.hpp" using namespace std; #ifdef HAVE_CLAMDFFT //////////////////////////////////////////////////////////////////////////// diff --git a/modules/ocl/test/test_filters.cpp b/modules/ocl/test/test_filters.cpp index cfd57413e1..ec46a5cd6a 100644 --- a/modules/ocl/test/test_filters.cpp +++ b/modules/ocl/test/test_filters.cpp @@ -48,7 +48,7 @@ // //M*/ -#include "precomp.hpp" +#include "test_precomp.hpp" #ifdef HAVE_OPENCL diff --git a/modules/ocl/test/test_gemm.cpp b/modules/ocl/test/test_gemm.cpp index 5548456568..00d428770f 100644 --- a/modules/ocl/test/test_gemm.cpp +++ b/modules/ocl/test/test_gemm.cpp @@ -43,7 +43,7 @@ //M*/ -#include "precomp.hpp" +#include "test_precomp.hpp" using namespace std; #ifdef HAVE_CLAMDBLAS //////////////////////////////////////////////////////////////////////////// diff --git a/modules/ocl/test/test_imgproc.cpp b/modules/ocl/test/test_imgproc.cpp index 3228b6c0cf..225925c03e 100644 --- a/modules/ocl/test/test_imgproc.cpp +++ b/modules/ocl/test/test_imgproc.cpp @@ -51,7 +51,7 @@ // //M*/ -#include "precomp.hpp" +#include "test_precomp.hpp" #ifdef HAVE_OPENCL diff --git a/modules/ocl/test/test_kmeans.cpp b/modules/ocl/test/test_kmeans.cpp new file mode 100644 index 0000000000..a3e472bdf1 --- /dev/null +++ b/modules/ocl/test/test_kmeans.cpp @@ -0,0 +1,162 @@ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved. +// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// @Authors +// Erping Pang, pang_er_ping@163.com +// Xiaopeng Fu, fuxiaopeng2222@163.com +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other oclMaterials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#include "test_precomp.hpp" + +#ifdef HAVE_OPENCL + +using namespace cvtest; +using namespace testing; +using namespace std; +using namespace cv; + +#define OCL_KMEANS_USE_INITIAL_LABELS 1 +#define OCL_KMEANS_PP_CENTERS 2 + +PARAM_TEST_CASE(Kmeans, int, int, int) +{ + int type; + int K; + int flags; + cv::Mat src ; + ocl::oclMat d_src, d_dists; + + Mat labels, centers; + ocl::oclMat d_labels, d_centers; + cv::RNG rng ; + virtual void SetUp(){ + K = GET_PARAM(0); + type = GET_PARAM(1); + flags = GET_PARAM(2); + rng = TS::ptr()->get_rng(); + + // MWIDTH=256, MHEIGHT=256. defined in utility.hpp + cv::Size size = cv::Size(MWIDTH, MHEIGHT); + src.create(size, type); + int row_idx = 0; + const int max_neighbour = MHEIGHT / K - 1; + CV_Assert(K <= MWIDTH); + for(int i = 0; i < K; i++ ) + { + Mat center_row_header = src.row(row_idx); + center_row_header.setTo(0); + int nchannel = center_row_header.channels(); + for(int j = 0; j < nchannel; j++) + center_row_header.at(0, i*nchannel+j) = 50000.0; + + for(int j = 0; (j < max_neighbour) || + (i == K-1 && j < max_neighbour + MHEIGHT%K); j ++) + { + Mat cur_row_header = src.row(row_idx + 1 + j); + center_row_header.copyTo(cur_row_header); + Mat tmpmat = randomMat(rng, cur_row_header.size(), cur_row_header.type(), -200, 200, false); + cur_row_header += tmpmat; + } + row_idx += 1 + max_neighbour; + } + } +}; +TEST_P(Kmeans, Mat){ + + if(flags & KMEANS_USE_INITIAL_LABELS) + { + // inital a given labels + labels.create(src.rows, 1, CV_32S); + int *label = labels.ptr(); + for(int i = 0; i < src.rows; i++) + label[i] = rng.uniform(0, K); + d_labels.upload(labels); + } + d_src.upload(src); + + for(int j = 0; j < LOOP_TIMES; j++) + { + kmeans(src, K, labels, + TermCriteria( CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 100, 0), + 1, flags, centers); + + ocl::kmeans(d_src, K, d_labels, + TermCriteria( CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 100, 0), + 1, flags, d_centers); + + Mat dd_labels(d_labels); + Mat dd_centers(d_centers); + if(flags & KMEANS_USE_INITIAL_LABELS) + { + EXPECT_MAT_NEAR(labels, dd_labels, 0); + EXPECT_MAT_NEAR(centers, dd_centers, 1e-3); + } + else + { + int row_idx = 0; + for(int i = 0; i < K; i++) + { + // verify lables with ground truth resutls + int label = labels.at(row_idx); + int header_label = dd_labels.at(row_idx); + for(int j = 0; (j < MHEIGHT/K)||(i == K-1 && j < MHEIGHT/K+MHEIGHT%K); j++) + { + ASSERT_NEAR(labels.at(row_idx+j), label, 0); + ASSERT_NEAR(dd_labels.at(row_idx+j), header_label, 0); + } + + // verify centers + float *center = centers.ptr(label); + float *header_center = dd_centers.ptr(header_label); + for(int t = 0; t < centers.cols; t++) + ASSERT_NEAR(center[t], header_center[t], 1e-3); + + row_idx += MHEIGHT/K; + } + } + } +} +INSTANTIATE_TEST_CASE_P(OCL_ML, Kmeans, Combine( + Values(3, 5, 8), + Values(CV_32FC1, CV_32FC2, CV_32FC4), + Values(OCL_KMEANS_USE_INITIAL_LABELS/*, OCL_KMEANS_PP_CENTERS*/))); + +#endif diff --git a/modules/ocl/test/test_match_template.cpp b/modules/ocl/test/test_match_template.cpp index a393abdeb3..551c9ff12a 100644 --- a/modules/ocl/test/test_match_template.cpp +++ b/modules/ocl/test/test_match_template.cpp @@ -43,7 +43,7 @@ //M*/ -#include "precomp.hpp" +#include "test_precomp.hpp" #ifdef HAVE_OPENCL //////////////////////////////////////////////////////////////////////////////// diff --git a/modules/ocl/test/test_matrix_operation.cpp b/modules/ocl/test/test_matrix_operation.cpp index 92d810818b..e8b5022324 100644 --- a/modules/ocl/test/test_matrix_operation.cpp +++ b/modules/ocl/test/test_matrix_operation.cpp @@ -44,7 +44,7 @@ // //M*/ -#include "precomp.hpp" +#include "test_precomp.hpp" #ifdef HAVE_OPENCL diff --git a/modules/ocl/test/test_moments.cpp b/modules/ocl/test/test_moments.cpp index 86f4779d68..65034acfe3 100644 --- a/modules/ocl/test/test_moments.cpp +++ b/modules/ocl/test/test_moments.cpp @@ -1,4 +1,4 @@ -#include "precomp.hpp" +#include "test_precomp.hpp" #include #include "opencv2/imgproc/imgproc_c.h" @@ -45,7 +45,7 @@ TEST_P(MomentsTest, Mat) { if(test_contours) { - Mat src = imread( workdir + "../cpp/pic3.png", IMREAD_GRAYSCALE ); + Mat src = readImage( "cv/shared/pic3.png", IMREAD_GRAYSCALE ); ASSERT_FALSE(src.empty()); Mat canny_output; vector > contours; diff --git a/modules/ocl/test/test_objdetect.cpp b/modules/ocl/test/test_objdetect.cpp index bc719b0974..d75d99198b 100644 --- a/modules/ocl/test/test_objdetect.cpp +++ b/modules/ocl/test/test_objdetect.cpp @@ -43,7 +43,7 @@ // //M*/ -#include "precomp.hpp" +#include "test_precomp.hpp" #include "opencv2/core/core.hpp" #include "opencv2/objdetect/objdetect.hpp" @@ -63,11 +63,8 @@ PARAM_TEST_CASE(HOG, Size, int) { winSize = GET_PARAM(0); type = GET_PARAM(1); - img_rgb = readImage(workdir + "../gpu/road.png"); - if(img_rgb.empty()) - { - std::cout << "Couldn't read road.png" << std::endl; - } + img_rgb = readImage("gpu/hog/road.png"); + ASSERT_FALSE(img_rgb.empty()); } }; @@ -211,18 +208,11 @@ PARAM_TEST_CASE(Haar, int, CascadeName) virtual void SetUp() { flags = GET_PARAM(0); - cascadeName = (workdir + "../../data/haarcascades/").append(GET_PARAM(1)); - if( (!cascade.load( cascadeName )) || (!cpucascade.load(cascadeName)) ) - { - std::cout << "ERROR: Could not load classifier cascade" << std::endl; - return; - } - img = readImage(workdir + "lena.jpg", IMREAD_GRAYSCALE); - if(img.empty()) - { - std::cout << "Couldn't read lena.jpg" << std::endl; - return ; - } + cascadeName = (string(cvtest::TS::ptr()->get_data_path()) + "cv/cascadeandhog/cascades/").append(GET_PARAM(1)); + ASSERT_TRUE(cascade.load( cascadeName )); + ASSERT_TRUE(cpucascade.load(cascadeName)); + img = readImage("cv/shared/lena.png", IMREAD_GRAYSCALE); + ASSERT_FALSE(img.empty()); equalizeHist(img, img); d_img.upload(img); } diff --git a/modules/ocl/test/test_optflow.cpp b/modules/ocl/test/test_optflow.cpp index 34adb352c2..4693d46ddf 100644 --- a/modules/ocl/test/test_optflow.cpp +++ b/modules/ocl/test/test_optflow.cpp @@ -43,7 +43,7 @@ // //M*/ -#include "precomp.hpp" +#include "test_precomp.hpp" #include #ifdef HAVE_OPENCL @@ -75,7 +75,7 @@ PARAM_TEST_CASE(GoodFeaturesToTrack, MinDistance) TEST_P(GoodFeaturesToTrack, Accuracy) { - cv::Mat frame = readImage(workdir + "../gpu/rubberwhale1.png", cv::IMREAD_GRAYSCALE); + cv::Mat frame = readImage("gpu/opticalflow/rubberwhale1.png", cv::IMREAD_GRAYSCALE); ASSERT_FALSE(frame.empty()); int maxCorners = 1000; @@ -146,10 +146,10 @@ PARAM_TEST_CASE(TVL1, bool) TEST_P(TVL1, Accuracy) { - cv::Mat frame0 = readImage(workdir + "../gpu/rubberwhale1.png", cv::IMREAD_GRAYSCALE); + cv::Mat frame0 = readImage("gpu/opticalflow/rubberwhale1.png", cv::IMREAD_GRAYSCALE); ASSERT_FALSE(frame0.empty()); - cv::Mat frame1 = readImage(workdir + "../gpu/rubberwhale2.png", cv::IMREAD_GRAYSCALE); + cv::Mat frame1 = readImage("gpu/opticalflow/rubberwhale2.png", cv::IMREAD_GRAYSCALE); ASSERT_FALSE(frame1.empty()); cv::ocl::OpticalFlowDual_TVL1_OCL d_alg; @@ -188,10 +188,10 @@ PARAM_TEST_CASE(Sparse, bool, bool) TEST_P(Sparse, Mat) { - cv::Mat frame0 = readImage(workdir + "../gpu/rubberwhale1.png", useGray ? cv::IMREAD_GRAYSCALE : cv::IMREAD_COLOR); + cv::Mat frame0 = readImage("gpu/opticalflow/rubberwhale1.png", useGray ? cv::IMREAD_GRAYSCALE : cv::IMREAD_COLOR); ASSERT_FALSE(frame0.empty()); - cv::Mat frame1 = readImage(workdir + "../gpu/rubberwhale2.png", useGray ? cv::IMREAD_GRAYSCALE : cv::IMREAD_COLOR); + cv::Mat frame1 = readImage("gpu/opticalflow/rubberwhale2.png", useGray ? cv::IMREAD_GRAYSCALE : cv::IMREAD_COLOR); ASSERT_FALSE(frame1.empty()); cv::Mat gray_frame; @@ -301,10 +301,10 @@ PARAM_TEST_CASE(Farneback, PyrScale, PolyN, FarnebackOptFlowFlags, UseInitFlow) TEST_P(Farneback, Accuracy) { - cv::Mat frame0 = imread(workdir + "/rubberwhale1.png", cv::IMREAD_GRAYSCALE); + cv::Mat frame0 = readImage("gpu/opticalflow/rubberwhale1.png", cv::IMREAD_GRAYSCALE); ASSERT_FALSE(frame0.empty()); - cv::Mat frame1 = imread(workdir + "/rubberwhale2.png", cv::IMREAD_GRAYSCALE); + cv::Mat frame1 = readImage("gpu/opticalflow/rubberwhale2.png", cv::IMREAD_GRAYSCALE); ASSERT_FALSE(frame1.empty()); double polySigma = polyN <= 5 ? 1.1 : 1.5; diff --git a/modules/ocl/test/precomp.hpp b/modules/ocl/test/test_precomp.hpp similarity index 100% rename from modules/ocl/test/precomp.hpp rename to modules/ocl/test/test_precomp.hpp diff --git a/modules/ocl/test/test_pyramids.cpp b/modules/ocl/test/test_pyramids.cpp index 1bd188dea6..b7bc752d67 100644 --- a/modules/ocl/test/test_pyramids.cpp +++ b/modules/ocl/test/test_pyramids.cpp @@ -44,7 +44,7 @@ //M*/ -#include "precomp.hpp" +#include "test_precomp.hpp" #include #ifdef HAVE_OPENCL diff --git a/modules/ocl/test/test_sort.cpp b/modules/ocl/test/test_sort.cpp new file mode 100644 index 0000000000..83326a5426 --- /dev/null +++ b/modules/ocl/test/test_sort.cpp @@ -0,0 +1,244 @@ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved. +// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// @Authors +// Peng Xiao, pengxiao@outlook.com +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other oclMaterials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors as is and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ +#include +#include +#include "test_precomp.hpp" + +using namespace std; +using namespace cvtest; +using namespace testing; +using namespace cv; + + +namespace +{ +IMPLEMENT_PARAM_CLASS(IsGreaterThan, bool) +IMPLEMENT_PARAM_CLASS(InputSize, int) +IMPLEMENT_PARAM_CLASS(SortMethod, int) + + +template +struct KV_CVTYPE{ static int toType() {return 0;} }; + +template<> struct KV_CVTYPE { static int toType() {return CV_32SC1;} }; +template<> struct KV_CVTYPE{ static int toType() {return CV_32FC1;} }; +template<> struct KV_CVTYPE{ static int toType() {return CV_32SC2;} }; +template<> struct KV_CVTYPE{ static int toType() {return CV_32FC2;} }; + +template +bool kvgreater(pair p1, pair p2) +{ + return p1.first > p2.first; +} + +template +bool kvless(pair p1, pair p2) +{ + return p1.first < p2.first; +} + +template +void toKVPair( + MatConstIterator_ kit, + MatConstIterator_ vit, + int vecSize, + vector >& kvres + ) +{ + kvres.clear(); + for(int i = 0; i < vecSize; i ++) + { + kvres.push_back(make_pair(*kit, *vit)); + ++kit; + ++vit; + } +} + +template +void kvquicksort(Mat& keys, Mat& vals, bool isGreater = false) +{ + vector > kvres; + toKVPair(keys.begin(), vals.begin(), keys.cols, kvres); + + if(isGreater) + { + std::sort(kvres.begin(), kvres.end(), kvgreater); + } + else + { + std::sort(kvres.begin(), kvres.end(), kvless); + } + key_type * kptr = keys.ptr(); + val_type * vptr = vals.ptr(); + for(int i = 0; i < keys.cols; i ++) + { + kptr[i] = kvres[i].first; + vptr[i] = kvres[i].second; + } +} + +class SortByKey_STL +{ +public: + static void sort(cv::Mat&, cv::Mat&, bool is_gt); +private: + typedef void (*quick_sorter)(cv::Mat&, cv::Mat&, bool); + SortByKey_STL(); + quick_sorter quick_sorters[CV_64FC4][CV_64FC4]; + static SortByKey_STL instance; +}; + +SortByKey_STL SortByKey_STL::instance = SortByKey_STL(); + +SortByKey_STL::SortByKey_STL() +{ + memset(instance.quick_sorters, 0, sizeof(quick_sorters)); +#define NEW_SORTER(KT, VT) \ + instance.quick_sorters[KV_CVTYPE::toType()][KV_CVTYPE::toType()] = kvquicksort; + + NEW_SORTER(int, int); + NEW_SORTER(int, Vec2i); + NEW_SORTER(int, float); + NEW_SORTER(int, Vec2f); + + NEW_SORTER(float, int); + NEW_SORTER(float, Vec2i); + NEW_SORTER(float, float); + NEW_SORTER(float, Vec2f); +#undef NEW_SORTER +} + +void SortByKey_STL::sort(cv::Mat& keys, cv::Mat& vals, bool is_gt) +{ + instance.quick_sorters[keys.type()][vals.type()](keys, vals, is_gt); +} + +bool checkUnstableSorterResult(const Mat& gkeys_, const Mat& gvals_, + const Mat& /*dkeys_*/, const Mat& dvals_) +{ + int cn_val = gvals_.channels(); + int count = gkeys_.cols; + + //for convenience we convert depth to float and channels to 1 + Mat gkeys, gvals, dkeys, dvals; + gkeys_.reshape(1).convertTo(gkeys, CV_32F); + gvals_.reshape(1).convertTo(gvals, CV_32F); + //dkeys_.reshape(1).convertTo(dkeys, CV_32F); + dvals_.reshape(1).convertTo(dvals, CV_32F); + float * gkptr = gkeys.ptr(); + float * gvptr = gvals.ptr(); + //float * dkptr = dkeys.ptr(); + float * dvptr = dvals.ptr(); + + for(int i = 0; i < count - 1; ++i) + { + int iden_count = 0; + // firstly calculate the number of identical keys + while(gkptr[i + iden_count] == gkptr[i + 1 + iden_count]) + { + ++ iden_count; + } + + // sort dv and gv + int num_of_val = (iden_count + 1) * cn_val; + std::sort(gvptr + i * cn_val, gvptr + i * cn_val + num_of_val); + std::sort(dvptr + i * cn_val, dvptr + i * cn_val + num_of_val); + + // then check if [i, i + iden_count) is the same + for(int j = 0; j < num_of_val; ++j) + { + if(gvptr[i + j] != dvptr[i + j]) + { + return false; + } + } + i += iden_count; + } + return true; +} +} + +#define INPUT_SIZES Values(InputSize(0x10), InputSize(0x100), InputSize(0x10000)) //2^4, 2^8, 2^16 +#define KEY_TYPES Values(MatType(CV_32SC1), MatType(CV_32FC1)) +#define VAL_TYPES Values(MatType(CV_32SC1), MatType(CV_32SC2), MatType(CV_32FC1), MatType(CV_32FC2)) +#define SORT_METHODS Values(SortMethod(cv::ocl::SORT_BITONIC),SortMethod(cv::ocl::SORT_MERGE),SortMethod(cv::ocl::SORT_RADIX)/*,SortMethod(cv::ocl::SORT_SELECTION)*/) +#define F_OR_T Values(IsGreaterThan(false), IsGreaterThan(true)) + +PARAM_TEST_CASE(SortByKey, InputSize, MatType, MatType, SortMethod, IsGreaterThan) +{ + InputSize input_size; + MatType key_type, val_type; + SortMethod method; + IsGreaterThan is_gt; + + Mat mat_key, mat_val; + virtual void SetUp() + { + input_size = GET_PARAM(0); + key_type = GET_PARAM(1); + val_type = GET_PARAM(2); + method = GET_PARAM(3); + is_gt = GET_PARAM(4); + + using namespace cv; + // fill key and val + mat_key = randomMat(Size(input_size, 1), key_type, INT_MIN, INT_MAX); + mat_val = randomMat(Size(input_size, 1), val_type, INT_MIN, INT_MAX); + } +}; + +TEST_P(SortByKey, Accuracy) +{ + using namespace cv; + ocl::oclMat oclmat_key(mat_key); + ocl::oclMat oclmat_val(mat_val); + + ocl::sortByKey(oclmat_key, oclmat_val, method, is_gt); + SortByKey_STL::sort(mat_key, mat_val, is_gt); + + EXPECT_MAT_NEAR(mat_key, oclmat_key, 0.0); + EXPECT_TRUE(checkUnstableSorterResult(mat_key, mat_val, oclmat_key, oclmat_val)); +} +INSTANTIATE_TEST_CASE_P(OCL_SORT, SortByKey, Combine(INPUT_SIZES, KEY_TYPES, VAL_TYPES, SORT_METHODS, F_OR_T)); diff --git a/modules/ocl/test/test_split_merge.cpp b/modules/ocl/test/test_split_merge.cpp index 854ce309c2..9663f5321c 100644 --- a/modules/ocl/test/test_split_merge.cpp +++ b/modules/ocl/test/test_split_merge.cpp @@ -44,7 +44,7 @@ // //M*/ -#include "precomp.hpp" +#include "test_precomp.hpp" #ifdef HAVE_OPENCL diff --git a/modules/ocl/test/utility.cpp b/modules/ocl/test/utility.cpp index 27f9cec079..440a89d4a0 100644 --- a/modules/ocl/test/utility.cpp +++ b/modules/ocl/test/utility.cpp @@ -39,7 +39,7 @@ // //M*/ -#include "precomp.hpp" +#include "test_precomp.hpp" #define VARNAME(A) #A using namespace std; using namespace cv; diff --git a/modules/photo/doc/inpainting.rst b/modules/photo/doc/inpainting.rst index ef69ebc708..6c967969df 100644 --- a/modules/photo/doc/inpainting.rst +++ b/modules/photo/doc/inpainting.rst @@ -31,3 +31,9 @@ Restores the selected region in an image using the region neighborhood. The function reconstructs the selected image area from the pixel near the area boundary. The function may be used to remove dust and scratches from a scanned photo, or to remove undesirable objects from still images or video. See http://en.wikipedia.org/wiki/Inpainting for more details. + +.. note:: + + * An example using the inpainting technique can be found at opencv_source_code/samples/cpp/inpaint.cpp + + * (Python) An example using the inpainting technique can be found at opencv_source_code/samples/python2/inpaint.py \ No newline at end of file diff --git a/modules/photo/perf/perf_precomp.cpp b/modules/photo/perf/perf_precomp.cpp deleted file mode 100644 index 8552ac3d42..0000000000 --- a/modules/photo/perf/perf_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "perf_precomp.hpp" diff --git a/modules/photo/src/precomp.cpp b/modules/photo/src/precomp.cpp deleted file mode 100644 index 3e0ec42de9..0000000000 --- a/modules/photo/src/precomp.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/*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 "precomp.hpp" - -/* End of file. */ diff --git a/modules/photo/src/precomp.hpp b/modules/photo/src/precomp.hpp index 3185a18b86..196867625a 100644 --- a/modules/photo/src/precomp.hpp +++ b/modules/photo/src/precomp.hpp @@ -43,9 +43,7 @@ #ifndef __OPENCV_PRECOMP_H__ #define __OPENCV_PRECOMP_H__ -#ifdef HAVE_CVCONFIG_H #include "cvconfig.h" -#endif #include "opencv2/photo/photo.hpp" diff --git a/modules/photo/test/test_precomp.cpp b/modules/photo/test/test_precomp.cpp deleted file mode 100644 index 5956e13e3e..0000000000 --- a/modules/photo/test/test_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "test_precomp.hpp" diff --git a/modules/python/src2/cv2.cpp b/modules/python/src2/cv2.cpp index 64c4ad9ff3..745914ca4d 100644 --- a/modules/python/src2/cv2.cpp +++ b/modules/python/src2/cv2.cpp @@ -6,6 +6,7 @@ #define MODULESTR "cv2" +#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include "numpy/ndarrayobject.h" #include "opencv2/core/core.hpp" @@ -123,6 +124,7 @@ typedef Ptr Ptr_FeatureDetector; typedef Ptr Ptr_DescriptorExtractor; typedef Ptr Ptr_Feature2D; typedef Ptr Ptr_DescriptorMatcher; +typedef Ptr Ptr_CLAHE; typedef SimpleBlobDetector::Params SimpleBlobDetector_Params; @@ -193,10 +195,10 @@ public: if(!o) CV_Error_(CV_StsError, ("The numpy array of typenum=%d, ndims=%d can not be created", typenum, dims)); refcount = refcountFromPyObject(o); - npy_intp* _strides = PyArray_STRIDES(o); + npy_intp* _strides = PyArray_STRIDES((PyArrayObject*) o); for( i = 0; i < dims - (cn > 1); i++ ) step[i] = (size_t)_strides[i]; - datastart = data = (uchar*)PyArray_DATA(o); + datastart = data = (uchar*)PyArray_DATA((PyArrayObject*) o); } void deallocate(int* refcount, uchar*, uchar*) @@ -263,8 +265,10 @@ static int pyopencv_to(const PyObject* o, Mat& m, const ArgInfo info, bool allow return false; } + PyArrayObject* oarr = (PyArrayObject*) o; + bool needcopy = false, needcast = false; - int typenum = PyArray_TYPE(o), new_typenum = typenum; + int typenum = PyArray_TYPE(oarr), new_typenum = typenum; int type = typenum == NPY_UBYTE ? CV_8U : typenum == NPY_BYTE ? CV_8S : typenum == NPY_USHORT ? CV_16U : @@ -289,7 +293,7 @@ static int pyopencv_to(const PyObject* o, Mat& m, const ArgInfo info, bool allow } } - int ndims = PyArray_NDIM(o); + int ndims = PyArray_NDIM(oarr); if(ndims >= CV_MAX_DIM) { failmsg("%s dimensionality (=%d) is too high", info.name, ndims); @@ -298,8 +302,8 @@ static int pyopencv_to(const PyObject* o, Mat& m, const ArgInfo info, bool allow int size[CV_MAX_DIM+1]; size_t step[CV_MAX_DIM+1], elemsize = CV_ELEM_SIZE1(type); - const npy_intp* _sizes = PyArray_DIMS(o); - const npy_intp* _strides = PyArray_STRIDES(o); + const npy_intp* _sizes = PyArray_DIMS(oarr); + const npy_intp* _strides = PyArray_STRIDES(oarr); bool ismultichannel = ndims == 3 && _sizes[2] <= CV_CN_MAX; for( int i = ndims-1; i >= 0 && !needcopy; i-- ) @@ -323,11 +327,17 @@ static int pyopencv_to(const PyObject* o, Mat& m, const ArgInfo info, bool allow failmsg("Layout of the output array %s is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)", info.name); return false; } - if( needcast ) - o = (PyObject*)PyArray_Cast((PyArrayObject*)o, new_typenum); - else - o = (PyObject*)PyArray_GETCONTIGUOUS((PyArrayObject*)o); - _strides = PyArray_STRIDES(o); + + if( needcast ) { + o = PyArray_Cast(oarr, new_typenum); + oarr = (PyArrayObject*) o; + } + else { + oarr = PyArray_GETCONTIGUOUS(oarr); + o = (PyObject*) oarr; + } + + _strides = PyArray_STRIDES(oarr); } for(int i = 0; i < ndims; i++) @@ -355,7 +365,7 @@ static int pyopencv_to(const PyObject* o, Mat& m, const ArgInfo info, bool allow return false; } - m = Mat(ndims, size, type, PyArray_DATA(o), step); + m = Mat(ndims, size, type, PyArray_DATA(oarr), step); if( m.data ) { diff --git a/modules/python/src2/cv2.cv.hpp b/modules/python/src2/cv2.cv.hpp index 06c37cbb3f..31bb77687b 100644 --- a/modules/python/src2/cv2.cv.hpp +++ b/modules/python/src2/cv2.cv.hpp @@ -510,7 +510,11 @@ static void arrayinterface_common(PyArrayInterface *s, int mtype) assert(0); } +#ifdef NPY_1_7_API_VERSION + s->flags = NPY_ARRAY_WRITEABLE | NPY_ARRAY_NOTSWAPPED; +#else s->flags = NPY_WRITEABLE | NPY_NOTSWAPPED; +#endif } static PyObject *cvmat_array_struct(cvmat_t *cva) diff --git a/modules/stitching/doc/high_level.rst b/modules/stitching/doc/high_level.rst index 5834072089..07e785002d 100644 --- a/modules/stitching/doc/high_level.rst +++ b/modules/stitching/doc/high_level.rst @@ -88,6 +88,11 @@ High level image stitcher. It's possible to use this class without being aware o /* hidden */ }; +.. note:: + + * A basic example on image stitching can be found at opencv_source_code/samples/cpp/stitching.cpp + * A detailed example on image stitching can be found at opencv_source_code/samples/cpp/stitching_detailed.cpp + Stitcher::createDefault ----------------------- Creates a stitcher with the default parameters. diff --git a/modules/stitching/perf/perf_precomp.cpp b/modules/stitching/perf/perf_precomp.cpp deleted file mode 100644 index 8552ac3d42..0000000000 --- a/modules/stitching/perf/perf_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "perf_precomp.hpp" diff --git a/modules/stitching/src/precomp.cpp b/modules/stitching/src/precomp.cpp deleted file mode 100644 index 390dbfbc6b..0000000000 --- a/modules/stitching/src/precomp.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "precomp.hpp" \ No newline at end of file diff --git a/modules/stitching/src/precomp.hpp b/modules/stitching/src/precomp.hpp index 4849ace1eb..1050856d31 100644 --- a/modules/stitching/src/precomp.hpp +++ b/modules/stitching/src/precomp.hpp @@ -43,9 +43,7 @@ #ifndef __OPENCV_STITCHING_PRECOMP_H__ #define __OPENCV_STITCHING_PRECOMP_H__ -#ifdef HAVE_CVCONFIG_H #include "cvconfig.h" -#endif #include "opencv2/opencv_modules.hpp" #include diff --git a/modules/stitching/test/test_precomp.cpp b/modules/stitching/test/test_precomp.cpp deleted file mode 100644 index 14a070e817..0000000000 --- a/modules/stitching/test/test_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "test_precomp.hpp" \ No newline at end of file diff --git a/modules/superres/CMakeLists.txt b/modules/superres/CMakeLists.txt index 6c6022c72c..44e9dc0f3b 100644 --- a/modules/superres/CMakeLists.txt +++ b/modules/superres/CMakeLists.txt @@ -4,4 +4,4 @@ endif() set(the_description "Super Resolution") ocv_warnings_disable(CMAKE_CXX_FLAGS /wd4127 -Wundef) -ocv_define_module(superres opencv_imgproc opencv_video OPTIONAL opencv_gpu opencv_highgui) +ocv_define_module(superres opencv_imgproc opencv_video OPTIONAL opencv_gpu opencv_highgui opencv_ocl) diff --git a/modules/superres/include/opencv2/superres/optical_flow.hpp b/modules/superres/include/opencv2/superres/optical_flow.hpp index 7a0ed833f4..d51ce793ea 100644 --- a/modules/superres/include/opencv2/superres/optical_flow.hpp +++ b/modules/superres/include/opencv2/superres/optical_flow.hpp @@ -58,15 +58,18 @@ namespace cv CV_EXPORTS Ptr createOptFlow_Farneback(); CV_EXPORTS Ptr createOptFlow_Farneback_GPU(); + CV_EXPORTS Ptr createOptFlow_Farneback_OCL(); CV_EXPORTS Ptr createOptFlow_Simple(); CV_EXPORTS Ptr createOptFlow_DualTVL1(); CV_EXPORTS Ptr createOptFlow_DualTVL1_GPU(); + CV_EXPORTS Ptr createOptFlow_DualTVL1_OCL(); CV_EXPORTS Ptr createOptFlow_Brox_GPU(); CV_EXPORTS Ptr createOptFlow_PyrLK_GPU(); + CV_EXPORTS Ptr createOptFlow_PyrLK_OCL(); } } diff --git a/modules/superres/include/opencv2/superres/superres.hpp b/modules/superres/include/opencv2/superres/superres.hpp index 1245c122a6..8daeb5ba0e 100644 --- a/modules/superres/include/opencv2/superres/superres.hpp +++ b/modules/superres/include/opencv2/superres/superres.hpp @@ -92,6 +92,7 @@ namespace cv // Dennis Mitzel, Thomas Pock, Thomas Schoenemann, Daniel Cremers. Video Super Resolution using Duality Based TV-L1 Optical Flow. CV_EXPORTS Ptr createSuperResolution_BTVL1(); CV_EXPORTS Ptr createSuperResolution_BTVL1_GPU(); + CV_EXPORTS Ptr createSuperResolution_BTVL1_OCL(); } } diff --git a/modules/superres/perf/perf_precomp.cpp b/modules/superres/perf/perf_precomp.cpp deleted file mode 100644 index 81f16e8f14..0000000000 --- a/modules/superres/perf/perf_precomp.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "perf_precomp.hpp" diff --git a/modules/superres/perf/perf_precomp.hpp b/modules/superres/perf/perf_precomp.hpp index f05203718c..d64d5008c6 100644 --- a/modules/superres/perf/perf_precomp.hpp +++ b/modules/superres/perf/perf_precomp.hpp @@ -51,9 +51,7 @@ #ifndef __OPENCV_PERF_PRECOMP_HPP__ #define __OPENCV_PERF_PRECOMP_HPP__ -#ifdef HAVE_CVCONFIG_H #include "cvconfig.h" -#endif #include "opencv2/ts/ts.hpp" #include "opencv2/ts/gpu_perf.hpp" diff --git a/modules/superres/perf/perf_superres_ocl.cpp b/modules/superres/perf/perf_superres_ocl.cpp new file mode 100644 index 0000000000..0b9864cbd3 --- /dev/null +++ b/modules/superres/perf/perf_superres_ocl.cpp @@ -0,0 +1,146 @@ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved. +// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#include "perf_precomp.hpp" + +#ifdef HAVE_OPENCL + +#include "opencv2/ocl/ocl.hpp" +using namespace std; +using namespace testing; +using namespace perf; +using namespace cv; +using namespace cv::superres; + +namespace +{ + class OneFrameSource_OCL : public FrameSource + { + public: + explicit OneFrameSource_OCL(const ocl::oclMat& frame) : frame_(frame) {} + + void nextFrame(OutputArray frame) + { + ocl::getOclMatRef(frame) = frame_; + } + void reset() + { + } + + private: + ocl::oclMat frame_; + }; + + + class ZeroOpticalFlowOCL : public DenseOpticalFlowExt + { + public: + void calc(InputArray frame0, InputArray, OutputArray flow1, OutputArray flow2) + { + ocl::oclMat& frame0_ = ocl::getOclMatRef(frame0); + ocl::oclMat& flow1_ = ocl::getOclMatRef(flow1); + ocl::oclMat& flow2_ = ocl::getOclMatRef(flow2); + + cv::Size size = frame0_.size(); + + if(!flow2.needed()) + { + flow1_.create(size, CV_32FC2); + flow1_.setTo(Scalar::all(0)); + } + else + { + flow1_.create(size, CV_32FC1); + flow2_.create(size, CV_32FC1); + + flow1_.setTo(Scalar::all(0)); + flow2_.setTo(Scalar::all(0)); + } + } + + void collectGarbage() + { + } + }; +} + +PERF_TEST_P(Size_MatType, SuperResolution_BTVL1_OCL, + Combine(Values(szSmall64, szSmall128), + Values(MatType(CV_8UC1), MatType(CV_8UC3)))) +{ + std::vectorinfo; + cv::ocl::getDevice(info); + + declare.time(5 * 60); + + const Size size = std::tr1::get<0>(GetParam()); + const int type = std::tr1::get<1>(GetParam()); + + Mat frame(size, type); + declare.in(frame, WARMUP_RNG); + + ocl::oclMat frame_ocl; + frame_ocl.upload(frame); + + + const int scale = 2; + const int iterations = 50; + const int temporalAreaRadius = 1; + Ptr opticalFlowOcl(new ZeroOpticalFlowOCL); + + Ptr superRes_ocl = createSuperResolution_BTVL1_OCL(); + + superRes_ocl->set("scale", scale); + superRes_ocl->set("iterations", iterations); + superRes_ocl->set("temporalAreaRadius", temporalAreaRadius); + superRes_ocl->set("opticalFlow", opticalFlowOcl); + + superRes_ocl->setInput(new OneFrameSource_OCL(frame_ocl)); + + ocl::oclMat dst_ocl; + superRes_ocl->nextFrame(dst_ocl); + + TEST_CYCLE_N(10) superRes_ocl->nextFrame(dst_ocl); + frame_ocl.release(); + CPU_SANITY_CHECK(dst_ocl); +} +#endif diff --git a/modules/superres/src/btv_l1_ocl.cpp b/modules/superres/src/btv_l1_ocl.cpp new file mode 100644 index 0000000000..5f9e32675e --- /dev/null +++ b/modules/superres/src/btv_l1_ocl.cpp @@ -0,0 +1,748 @@ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved. +// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// @Authors +// Jin Ma, jin@multicorewareinc.com +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other 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*/ + +// S. Farsiu , D. Robinson, M. Elad, P. Milanfar. Fast and robust multiframe super resolution. +// Dennis Mitzel, Thomas Pock, Thomas Schoenemann, Daniel Cremers. Video Super Resolution using Duality Based TV-L1 Optical Flow. + +#include "precomp.hpp" + +#if !defined(HAVE_OPENCL) || !defined(HAVE_OPENCV_OCL) + +cv::Ptr cv::superres::createSuperResolution_BTVL1_OCL() +{ + CV_Error(CV_StsNotImplemented, "The called functionality is disabled for current build or platform"); + return Ptr(); +} + +#else + +using namespace std; +using namespace cv; +using namespace cv::ocl; +using namespace cv::superres; +using namespace cv::superres::detail; + +namespace cv +{ + namespace ocl + { + extern const char* superres_btvl1; + + float* btvWeights_ = NULL; + size_t btvWeights_size = 0; + } +} + +namespace btv_l1_device_ocl +{ + void buildMotionMaps(const oclMat& forwardMotionX, const oclMat& forwardMotionY, + const oclMat& backwardMotionX, const oclMat& bacwardMotionY, + oclMat& forwardMapX, oclMat& forwardMapY, + oclMat& backwardMapX, oclMat& backwardMapY); + + void upscale(const oclMat& src, oclMat& dst, int scale); + + float diffSign(float a, float b); + + Point3f diffSign(Point3f a, Point3f b); + + void diffSign(const oclMat& src1, const oclMat& src2, oclMat& dst); + + void calcBtvRegularization(const oclMat& src, oclMat& dst, int ksize); +} + +void btv_l1_device_ocl::buildMotionMaps(const oclMat& forwardMotionX, const oclMat& forwardMotionY, + const oclMat& backwardMotionX, const oclMat& backwardMotionY, + oclMat& forwardMapX, oclMat& forwardMapY, + oclMat& backwardMapX, oclMat& backwardMapY) +{ + Context* clCxt = Context::getContext(); + + size_t local_thread[] = {32, 8, 1}; + size_t global_thread[] = {forwardMapX.cols, forwardMapX.rows, 1}; + + int forwardMotionX_step = (int)(forwardMotionX.step/forwardMotionX.elemSize()); + int forwardMotionY_step = (int)(forwardMotionY.step/forwardMotionY.elemSize()); + int backwardMotionX_step = (int)(backwardMotionX.step/backwardMotionX.elemSize()); + int backwardMotionY_step = (int)(backwardMotionY.step/backwardMotionY.elemSize()); + int forwardMapX_step = (int)(forwardMapX.step/forwardMapX.elemSize()); + int forwardMapY_step = (int)(forwardMapY.step/forwardMapY.elemSize()); + int backwardMapX_step = (int)(backwardMapX.step/backwardMapX.elemSize()); + int backwardMapY_step = (int)(backwardMapY.step/backwardMapY.elemSize()); + + String kernel_name = "buildMotionMapsKernel"; + vector< pair > args; + + args.push_back(make_pair(sizeof(cl_mem), (void*)&forwardMotionX.data)); + args.push_back(make_pair(sizeof(cl_mem), (void*)&forwardMotionY.data)); + args.push_back(make_pair(sizeof(cl_mem), (void*)&backwardMotionX.data)); + args.push_back(make_pair(sizeof(cl_mem), (void*)&backwardMotionY.data)); + args.push_back(make_pair(sizeof(cl_mem), (void*)&forwardMapX.data)); + args.push_back(make_pair(sizeof(cl_mem), (void*)&forwardMapY.data)); + args.push_back(make_pair(sizeof(cl_mem), (void*)&backwardMapX.data)); + args.push_back(make_pair(sizeof(cl_mem), (void*)&backwardMapY.data)); + + args.push_back(make_pair(sizeof(cl_int), (void*)&forwardMotionX.rows)); + args.push_back(make_pair(sizeof(cl_int), (void*)&forwardMotionY.cols)); + + args.push_back(make_pair(sizeof(cl_int), (void*)&forwardMotionX_step)); + args.push_back(make_pair(sizeof(cl_int), (void*)&forwardMotionY_step)); + args.push_back(make_pair(sizeof(cl_int), (void*)&backwardMotionX_step)); + args.push_back(make_pair(sizeof(cl_int), (void*)&backwardMotionY_step)); + args.push_back(make_pair(sizeof(cl_int), (void*)&forwardMapX_step)); + args.push_back(make_pair(sizeof(cl_int), (void*)&forwardMapY_step)); + args.push_back(make_pair(sizeof(cl_int), (void*)&backwardMapX_step)); + args.push_back(make_pair(sizeof(cl_int), (void*)&backwardMapY_step)); + + openCLExecuteKernel(clCxt, &superres_btvl1, kernel_name, global_thread, local_thread, args, -1, -1); +} + +void btv_l1_device_ocl::upscale(const oclMat& src, oclMat& dst, int scale) +{ + Context* clCxt = Context::getContext(); + + size_t local_thread[] = {32, 8, 1}; + size_t global_thread[] = {src.cols, src.rows, 1}; + + int src_step = (int)(src.step/src.elemSize()); + int dst_step = (int)(dst.step/dst.elemSize()); + + String kernel_name = "upscaleKernel"; + vector< pair > args; + + int cn = src.oclchannels(); + + args.push_back(make_pair(sizeof(cl_mem), (void*)&src.data)); + args.push_back(make_pair(sizeof(cl_mem), (void*)&dst.data)); + args.push_back(make_pair(sizeof(cl_int), (void*)&src_step)); + args.push_back(make_pair(sizeof(cl_int), (void*)&dst_step)); + args.push_back(make_pair(sizeof(cl_int), (void*)&src.rows)); + args.push_back(make_pair(sizeof(cl_int), (void*)&src.cols)); + args.push_back(make_pair(sizeof(cl_int), (void*)&scale)); + args.push_back(make_pair(sizeof(cl_int), (void*)&cn)); + + openCLExecuteKernel(clCxt, &superres_btvl1, kernel_name, global_thread, local_thread, args, -1, -1); + +} + +float btv_l1_device_ocl::diffSign(float a, float b) +{ + return a > b ? 1.0f : a < b ? -1.0f : 0.0f; +} + +Point3f btv_l1_device_ocl::diffSign(Point3f a, Point3f b) +{ + return Point3f( + a.x > b.x ? 1.0f : a.x < b.x ? -1.0f : 0.0f, + a.y > b.y ? 1.0f : a.y < b.y ? -1.0f : 0.0f, + a.z > b.z ? 1.0f : a.z < b.z ? -1.0f : 0.0f + ); +} + +void btv_l1_device_ocl::diffSign(const oclMat& src1, const oclMat& src2, oclMat& dst) +{ + Context* clCxt = Context::getContext(); + + oclMat src1_ = src1.reshape(1); + oclMat src2_ = src2.reshape(1); + oclMat dst_ = dst.reshape(1); + + int src1_step = (int)(src1_.step/src1_.elemSize()); + int src2_step = (int)(src2_.step/src2_.elemSize()); + int dst_step = (int)(dst_.step/dst_.elemSize()); + + size_t local_thread[] = {32, 8, 1}; + size_t global_thread[] = {src1_.cols, src1_.rows, 1}; + + String kernel_name = "diffSignKernel"; + vector< pair > args; + + args.push_back(make_pair(sizeof(cl_mem), (void*)&src1_.data)); + args.push_back(make_pair(sizeof(cl_mem), (void*)&src2_.data)); + args.push_back(make_pair(sizeof(cl_mem), (void*)&dst_.data)); + + args.push_back(make_pair(sizeof(cl_int), (void*)&src1_.rows)); + args.push_back(make_pair(sizeof(cl_int), (void*)&src1_.cols)); + args.push_back(make_pair(sizeof(cl_int), (void*)&dst_step)); + args.push_back(make_pair(sizeof(cl_int), (void*)&src1_step)); + args.push_back(make_pair(sizeof(cl_int), (void*)&src2_step)); + + openCLExecuteKernel(clCxt, &superres_btvl1, kernel_name, global_thread, local_thread, args, -1, -1); +} + +void btv_l1_device_ocl::calcBtvRegularization(const oclMat& src, oclMat& dst, int ksize) +{ + Context* clCxt = Context::getContext(); + + oclMat src_ = src.reshape(1); + oclMat dst_ = dst.reshape(1); + + size_t local_thread[] = {32, 8, 1}; + size_t global_thread[] = {src.cols, src.rows, 1}; + + int src_step = (int)(src_.step/src_.elemSize()); + int dst_step = (int)(dst_.step/dst_.elemSize()); + + String kernel_name = "calcBtvRegularizationKernel"; + vector< pair > args; + + int cn = src.oclchannels(); + + cl_mem c_btvRegWeights; + size_t count = btvWeights_size * sizeof(float); + c_btvRegWeights = openCLCreateBuffer(clCxt, CL_MEM_READ_ONLY, count); + int cl_safe_check = clEnqueueWriteBuffer((cl_command_queue)clCxt->oclCommandQueue(), c_btvRegWeights, 1, 0, count, btvWeights_, 0, NULL, NULL); + CV_Assert(cl_safe_check == CL_SUCCESS); + + args.push_back(make_pair(sizeof(cl_mem), (void*)&src_.data)); + args.push_back(make_pair(sizeof(cl_mem), (void*)&dst_.data)); + args.push_back(make_pair(sizeof(cl_int), (void*)&src_step)); + args.push_back(make_pair(sizeof(cl_int), (void*)&dst_step)); + args.push_back(make_pair(sizeof(cl_int), (void*)&src.rows)); + args.push_back(make_pair(sizeof(cl_int), (void*)&src.cols)); + args.push_back(make_pair(sizeof(cl_int), (void*)&ksize)); + args.push_back(make_pair(sizeof(cl_int), (void*)&cn)); + args.push_back(make_pair(sizeof(cl_mem), (void*)&c_btvRegWeights)); + + openCLExecuteKernel(clCxt, &superres_btvl1, kernel_name, global_thread, local_thread, args, -1, -1); + cl_safe_check = clReleaseMemObject(c_btvRegWeights); + CV_Assert(cl_safe_check == CL_SUCCESS); +} + +namespace +{ + void calcRelativeMotions(const vector >& forwardMotions, const vector >& backwardMotions, + vector >& relForwardMotions, vector >& relBackwardMotions, + int baseIdx, Size size) + { + const int count = static_cast(forwardMotions.size()); + + relForwardMotions.resize(count); + relForwardMotions[baseIdx].first.create(size, CV_32FC1); + relForwardMotions[baseIdx].first.setTo(Scalar::all(0)); + relForwardMotions[baseIdx].second.create(size, CV_32FC1); + relForwardMotions[baseIdx].second.setTo(Scalar::all(0)); + + relBackwardMotions.resize(count); + relBackwardMotions[baseIdx].first.create(size, CV_32FC1); + relBackwardMotions[baseIdx].first.setTo(Scalar::all(0)); + relBackwardMotions[baseIdx].second.create(size, CV_32FC1); + relBackwardMotions[baseIdx].second.setTo(Scalar::all(0)); + + for (int i = baseIdx - 1; i >= 0; --i) + { + ocl::add(relForwardMotions[i + 1].first, forwardMotions[i].first, relForwardMotions[i].first); + ocl::add(relForwardMotions[i + 1].second, forwardMotions[i].second, relForwardMotions[i].second); + + ocl::add(relBackwardMotions[i + 1].first, backwardMotions[i + 1].first, relBackwardMotions[i].first); + ocl::add(relBackwardMotions[i + 1].second, backwardMotions[i + 1].second, relBackwardMotions[i].second); + } + + for (int i = baseIdx + 1; i < count; ++i) + { + ocl::add(relForwardMotions[i - 1].first, backwardMotions[i].first, relForwardMotions[i].first); + ocl::add(relForwardMotions[i - 1].second, backwardMotions[i].second, relForwardMotions[i].second); + + ocl::add(relBackwardMotions[i - 1].first, forwardMotions[i - 1].first, relBackwardMotions[i].first); + ocl::add(relBackwardMotions[i - 1].second, forwardMotions[i - 1].second, relBackwardMotions[i].second); + } + } + + void upscaleMotions(const vector >& lowResMotions, vector >& highResMotions, int scale) + { + highResMotions.resize(lowResMotions.size()); + + for (size_t i = 0; i < lowResMotions.size(); ++i) + { + ocl::resize(lowResMotions[i].first, highResMotions[i].first, Size(), scale, scale, INTER_LINEAR); + ocl::resize(lowResMotions[i].second, highResMotions[i].second, Size(), scale, scale, INTER_LINEAR); + + ocl::multiply(scale, highResMotions[i].first, highResMotions[i].first); + ocl::multiply(scale, highResMotions[i].second, highResMotions[i].second); + } + } + + void buildMotionMaps(const pair& forwardMotion, const pair& backwardMotion, + pair& forwardMap, pair& backwardMap) + { + forwardMap.first.create(forwardMotion.first.size(), CV_32FC1); + forwardMap.second.create(forwardMotion.first.size(), CV_32FC1); + + backwardMap.first.create(forwardMotion.first.size(), CV_32FC1); + backwardMap.second.create(forwardMotion.first.size(), CV_32FC1); + + btv_l1_device_ocl::buildMotionMaps(forwardMotion.first, forwardMotion.second, + backwardMotion.first, backwardMotion.second, + forwardMap.first, forwardMap.second, + backwardMap.first, backwardMap.second); + } + + void upscale(const oclMat& src, oclMat& dst, int scale) + { + CV_Assert( src.channels() == 1 || src.channels() == 3 || src.channels() == 4 ); + + dst.create(src.rows * scale, src.cols * scale, src.type()); + dst.setTo(Scalar::all(0)); + + btv_l1_device_ocl::upscale(src, dst, scale); + } + + void diffSign(const oclMat& src1, const oclMat& src2, oclMat& dst) + { + dst.create(src1.size(), src1.type()); + + btv_l1_device_ocl::diffSign(src1, src2, dst); + } + + void calcBtvWeights(int btvKernelSize, double alpha, vector& btvWeights) + { + const size_t size = btvKernelSize * btvKernelSize; + + btvWeights.resize(size); + + const int ksize = (btvKernelSize - 1) / 2; + const float alpha_f = static_cast(alpha); + + for (int m = 0, ind = 0; m <= ksize; ++m) + { + for (int l = ksize; l + m >= 0; --l, ++ind) + btvWeights[ind] = pow(alpha_f, std::abs(m) + std::abs(l)); + } + + btvWeights_ = &btvWeights[0]; + btvWeights_size = size; + } + + void calcBtvRegularization(const oclMat& src, oclMat& dst, int btvKernelSize) + { + dst.create(src.size(), src.type()); + dst.setTo(Scalar::all(0)); + + const int ksize = (btvKernelSize - 1) / 2; + + btv_l1_device_ocl::calcBtvRegularization(src, dst, ksize); + } + + class BTVL1_OCL_Base + { + public: + BTVL1_OCL_Base(); + + void process(const vector& src, oclMat& dst, + const vector >& forwardMotions, const vector >& backwardMotions, + int baseIdx); + + void collectGarbage(); + + protected: + int scale_; + int iterations_; + double lambda_; + double tau_; + double alpha_; + int btvKernelSize_; + int blurKernelSize_; + double blurSigma_; + Ptr opticalFlow_; + + private: + vector > filters_; + int curBlurKernelSize_; + double curBlurSigma_; + int curSrcType_; + + vector btvWeights_; + int curBtvKernelSize_; + double curAlpha_; + + vector > lowResForwardMotions_; + vector > lowResBackwardMotions_; + + vector > highResForwardMotions_; + vector > highResBackwardMotions_; + + vector > forwardMaps_; + vector > backwardMaps_; + + oclMat highRes_; + + vector diffTerms_; + vector a_, b_, c_; + oclMat regTerm_; + }; + + BTVL1_OCL_Base::BTVL1_OCL_Base() + { + scale_ = 4; + iterations_ = 180; + lambda_ = 0.03; + tau_ = 1.3; + alpha_ = 0.7; + btvKernelSize_ = 7; + blurKernelSize_ = 5; + blurSigma_ = 0.0; + opticalFlow_ = createOptFlow_DualTVL1_OCL(); + + curBlurKernelSize_ = -1; + curBlurSigma_ = -1.0; + curSrcType_ = -1; + + curBtvKernelSize_ = -1; + curAlpha_ = -1.0; + } + + void BTVL1_OCL_Base::process(const vector& src, oclMat& dst, + const vector >& forwardMotions, const vector >& backwardMotions, + int baseIdx) + { + CV_Assert( scale_ > 1 ); + CV_Assert( iterations_ > 0 ); + CV_Assert( tau_ > 0.0 ); + CV_Assert( alpha_ > 0.0 ); + CV_Assert( btvKernelSize_ > 0 && btvKernelSize_ <= 16 ); + CV_Assert( blurKernelSize_ > 0 ); + CV_Assert( blurSigma_ >= 0.0 ); + + // update blur filter and btv weights + + if (filters_.size() != src.size() || blurKernelSize_ != curBlurKernelSize_ || blurSigma_ != curBlurSigma_ || src[0].type() != curSrcType_) + { + filters_.resize(src.size()); + for (size_t i = 0; i < src.size(); ++i) + filters_[i] = cv::ocl::createGaussianFilter_GPU(src[0].type(), Size(blurKernelSize_, blurKernelSize_), blurSigma_); + curBlurKernelSize_ = blurKernelSize_; + curBlurSigma_ = blurSigma_; + curSrcType_ = src[0].type(); + } + + if (btvWeights_.empty() || btvKernelSize_ != curBtvKernelSize_ || alpha_ != curAlpha_) + { + calcBtvWeights(btvKernelSize_, alpha_, btvWeights_); + curBtvKernelSize_ = btvKernelSize_; + curAlpha_ = alpha_; + } + + // calc motions between input frames + + calcRelativeMotions(forwardMotions, backwardMotions, + lowResForwardMotions_, lowResBackwardMotions_, + baseIdx, src[0].size()); + + upscaleMotions(lowResForwardMotions_, highResForwardMotions_, scale_); + upscaleMotions(lowResBackwardMotions_, highResBackwardMotions_, scale_); + + forwardMaps_.resize(highResForwardMotions_.size()); + backwardMaps_.resize(highResForwardMotions_.size()); + for (size_t i = 0; i < highResForwardMotions_.size(); ++i) + { + buildMotionMaps(highResForwardMotions_[i], highResBackwardMotions_[i], forwardMaps_[i], backwardMaps_[i]); + } + // initial estimation + + const Size lowResSize = src[0].size(); + const Size highResSize(lowResSize.width * scale_, lowResSize.height * scale_); + + ocl::resize(src[baseIdx], highRes_, highResSize, 0, 0, INTER_LINEAR); + + // iterations + + diffTerms_.resize(src.size()); + a_.resize(src.size()); + b_.resize(src.size()); + c_.resize(src.size()); + + for (int i = 0; i < iterations_; ++i) + { + for (size_t k = 0; k < src.size(); ++k) + { + diffTerms_[k].create(highRes_.size(), highRes_.type()); + a_[k].create(highRes_.size(), highRes_.type()); + b_[k].create(highRes_.size(), highRes_.type()); + c_[k].create(lowResSize, highRes_.type()); + + // a = M * Ih + ocl::remap(highRes_, a_[k], backwardMaps_[k].first, backwardMaps_[k].second, INTER_NEAREST, BORDER_CONSTANT, Scalar()); + // b = HM * Ih + filters_[k]->apply(a_[k], b_[k], Rect(0,0,-1,-1)); + // c = DHF * Ih + ocl::resize(b_[k], c_[k], lowResSize, 0, 0, INTER_NEAREST); + + diffSign(src[k], c_[k], c_[k]); + + // a = Dt * diff + upscale(c_[k], a_[k], scale_); + // b = HtDt * diff + filters_[k]->apply(a_[k], b_[k], Rect(0,0,-1,-1)); + // diffTerm = MtHtDt * diff + ocl::remap(b_[k], diffTerms_[k], forwardMaps_[k].first, forwardMaps_[k].second, INTER_NEAREST, BORDER_CONSTANT, Scalar()); + } + + if (lambda_ > 0) + { + calcBtvRegularization(highRes_, regTerm_, btvKernelSize_); + ocl::addWeighted(highRes_, 1.0, regTerm_, -tau_ * lambda_, 0.0, highRes_); + } + + for (size_t k = 0; k < src.size(); ++k) + { + ocl::addWeighted(highRes_, 1.0, diffTerms_[k], tau_, 0.0, highRes_); + } + } + + Rect inner(btvKernelSize_, btvKernelSize_, highRes_.cols - 2 * btvKernelSize_, highRes_.rows - 2 * btvKernelSize_); + highRes_(inner).copyTo(dst); + } + + void BTVL1_OCL_Base::collectGarbage() + { + filters_.clear(); + + lowResForwardMotions_.clear(); + lowResBackwardMotions_.clear(); + + highResForwardMotions_.clear(); + highResBackwardMotions_.clear(); + + forwardMaps_.clear(); + backwardMaps_.clear(); + + highRes_.release(); + + diffTerms_.clear(); + a_.clear(); + b_.clear(); + c_.clear(); + regTerm_.release(); + } + + //////////////////////////////////////////////////////////// + + class BTVL1_OCL : public SuperResolution, private BTVL1_OCL_Base + { + public: + AlgorithmInfo* info() const; + + BTVL1_OCL(); + + void collectGarbage(); + + protected: + void initImpl(Ptr& frameSource); + void processImpl(Ptr& frameSource, OutputArray output); + + private: + int temporalAreaRadius_; + + void readNextFrame(Ptr& frameSource); + void processFrame(int idx); + + oclMat curFrame_; + oclMat prevFrame_; + + vector frames_; + vector > forwardMotions_; + vector > backwardMotions_; + vector outputs_; + + int storePos_; + int procPos_; + int outPos_; + + vector srcFrames_; + vector > srcForwardMotions_; + vector > srcBackwardMotions_; + oclMat finalOutput_; + }; + + CV_INIT_ALGORITHM(BTVL1_OCL, "SuperResolution.BTVL1_OCL", + obj.info()->addParam(obj, "scale", obj.scale_, false, 0, 0, "Scale factor."); + obj.info()->addParam(obj, "iterations", obj.iterations_, false, 0, 0, "Iteration count."); + obj.info()->addParam(obj, "tau", obj.tau_, false, 0, 0, "Asymptotic value of steepest descent method."); + obj.info()->addParam(obj, "lambda", obj.lambda_, false, 0, 0, "Weight parameter to balance data term and smoothness term."); + obj.info()->addParam(obj, "alpha", obj.alpha_, false, 0, 0, "Parameter of spacial distribution in Bilateral-TV."); + obj.info()->addParam(obj, "btvKernelSize", obj.btvKernelSize_, false, 0, 0, "Kernel size of Bilateral-TV filter."); + obj.info()->addParam(obj, "blurKernelSize", obj.blurKernelSize_, false, 0, 0, "Gaussian blur kernel size."); + obj.info()->addParam(obj, "blurSigma", obj.blurSigma_, false, 0, 0, "Gaussian blur sigma."); + obj.info()->addParam(obj, "temporalAreaRadius", obj.temporalAreaRadius_, false, 0, 0, "Radius of the temporal search area."); + obj.info()->addParam(obj, "opticalFlow", obj.opticalFlow_, false, 0, 0, "Dense optical flow algorithm.")); + + BTVL1_OCL::BTVL1_OCL() + { + temporalAreaRadius_ = 4; + } + + void BTVL1_OCL::collectGarbage() + { + curFrame_.release(); + prevFrame_.release(); + + frames_.clear(); + forwardMotions_.clear(); + backwardMotions_.clear(); + outputs_.clear(); + + srcFrames_.clear(); + srcForwardMotions_.clear(); + srcBackwardMotions_.clear(); + finalOutput_.release(); + + SuperResolution::collectGarbage(); + BTVL1_OCL_Base::collectGarbage(); + } + + void BTVL1_OCL::initImpl(Ptr& frameSource) + { + const int cacheSize = 2 * temporalAreaRadius_ + 1; + + frames_.resize(cacheSize); + forwardMotions_.resize(cacheSize); + backwardMotions_.resize(cacheSize); + outputs_.resize(cacheSize); + + storePos_ = -1; + + for (int t = -temporalAreaRadius_; t <= temporalAreaRadius_; ++t) + readNextFrame(frameSource); + + for (int i = 0; i <= temporalAreaRadius_; ++i) + processFrame(i); + + procPos_ = temporalAreaRadius_; + outPos_ = -1; + } + + void BTVL1_OCL::processImpl(Ptr& frameSource, OutputArray _output) + { + if (outPos_ >= storePos_) + { + if(_output.kind() == _InputArray::OCL_MAT) + { + getOclMatRef(_output).release(); + } + else + { + _output.release(); + } + return; + } + + readNextFrame(frameSource); + + if (procPos_ < storePos_) + { + ++procPos_; + processFrame(procPos_); + } + + ++outPos_; + const oclMat& curOutput = at(outPos_, outputs_); + + if (_output.kind() == _InputArray::OCL_MAT) + curOutput.convertTo(getOclMatRef(_output), CV_8U); + else + { + curOutput.convertTo(finalOutput_, CV_8U); + arrCopy(finalOutput_, _output); + } + } + + void BTVL1_OCL::readNextFrame(Ptr& frameSource) + { + curFrame_.release(); + frameSource->nextFrame(curFrame_); + + if (curFrame_.empty()) + return; + + ++storePos_; + curFrame_.convertTo(at(storePos_, frames_), CV_32F); + + if (storePos_ > 0) + { + pair& forwardMotion = at(storePos_ - 1, forwardMotions_); + pair& backwardMotion = at(storePos_, backwardMotions_); + + opticalFlow_->calc(prevFrame_, curFrame_, forwardMotion.first, forwardMotion.second); + opticalFlow_->calc(curFrame_, prevFrame_, backwardMotion.first, backwardMotion.second); + } + + curFrame_.copyTo(prevFrame_); + } + + void BTVL1_OCL::processFrame(int idx) + { + const int startIdx = max(idx - temporalAreaRadius_, 0); + const int procIdx = idx; + const int endIdx = min(startIdx + 2 * temporalAreaRadius_, storePos_); + + const int count = endIdx - startIdx + 1; + + srcFrames_.resize(count); + srcForwardMotions_.resize(count); + srcBackwardMotions_.resize(count); + + int baseIdx = -1; + + for (int i = startIdx, k = 0; i <= endIdx; ++i, ++k) + { + if (i == procIdx) + baseIdx = k; + + srcFrames_[k] = at(i, frames_); + + if (i < endIdx) + srcForwardMotions_[k] = at(i, forwardMotions_); + if (i > startIdx) + srcBackwardMotions_[k] = at(i, backwardMotions_); + } + + process(srcFrames_, at(idx, outputs_), srcForwardMotions_, srcBackwardMotions_, baseIdx); + } +} + +Ptr cv::superres::createSuperResolution_BTVL1_OCL() +{ + return new BTVL1_OCL; +} +#endif \ No newline at end of file diff --git a/modules/superres/src/frame_source.cpp b/modules/superres/src/frame_source.cpp index 052141616d..20e45d9518 100644 --- a/modules/superres/src/frame_source.cpp +++ b/modules/superres/src/frame_source.cpp @@ -119,11 +119,23 @@ namespace { vc_ >> _frame.getMatRef(); } - else + else if(_frame.kind() == _InputArray::GPU_MAT) { vc_ >> frame_; arrCopy(frame_, _frame); } + else if(_frame.kind() == _InputArray::OCL_MAT) + { + vc_ >> frame_; + if(!frame_.empty()) + { + arrCopy(frame_, _frame); + } + } + else + { + //should never get here + } } class VideoFrameSource : public CaptureFrameSource diff --git a/modules/superres/src/input_array_utility.cpp b/modules/superres/src/input_array_utility.cpp index 5a6682526a..075cf95144 100644 --- a/modules/superres/src/input_array_utility.cpp +++ b/modules/superres/src/input_array_utility.cpp @@ -125,30 +125,59 @@ namespace { src.getGpuMat().copyTo(dst.getGpuMatRef()); } +#ifdef HAVE_OPENCV_OCL + void ocl2mat(InputArray src, OutputArray dst) + { + dst.getMatRef() = (Mat)ocl::getOclMatRef(src); + } + void mat2ocl(InputArray src, OutputArray dst) + { + Mat m = src.getMat(); + ocl::getOclMatRef(dst) = (ocl::oclMat)m; + } + void ocl2ocl(InputArray src, OutputArray dst) + { + ocl::getOclMatRef(src).copyTo(ocl::getOclMatRef(dst)); + } +#else + void ocl2mat(InputArray, OutputArray) + { + CV_Error(CV_StsNotImplemented, "The called functionality is disabled for current build or platform");; + } + void mat2ocl(InputArray, OutputArray) + { + CV_Error(CV_StsNotImplemented, "The called functionality is disabled for current build or platform");; + } + void ocl2ocl(InputArray, OutputArray) + { + CV_Error(CV_StsNotImplemented, "The called functionality is disabled for current build or platform"); + } +#endif } void cv::superres::arrCopy(InputArray src, OutputArray dst) { typedef void (*func_t)(InputArray src, OutputArray dst); - static const func_t funcs[10][10] = + static const func_t funcs[11][11] = { {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, - {0, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, arr2buf, arr2tex, mat2gpu}, - {0, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, arr2buf, arr2tex, mat2gpu}, - {0, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, arr2buf, arr2tex, mat2gpu}, - {0, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, arr2buf, arr2tex, mat2gpu}, - {0, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, arr2buf, arr2tex, mat2gpu}, - {0, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, arr2buf, arr2tex, mat2gpu}, - {0, buf2arr, buf2arr, buf2arr, buf2arr, buf2arr, buf2arr, buf2arr, buf2arr, buf2arr}, - {0, tex2arr, tex2arr, tex2arr, tex2arr, tex2arr, tex2arr, tex2arr, tex2arr, tex2arr}, - {0, gpu2mat, gpu2mat, gpu2mat, gpu2mat, gpu2mat, gpu2mat, arr2buf, arr2tex, gpu2gpu} + {0, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, arr2buf, arr2tex, mat2gpu, mat2ocl}, + {0, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, arr2buf, arr2tex, mat2gpu, mat2ocl}, + {0, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, arr2buf, arr2tex, mat2gpu, mat2ocl}, + {0, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, arr2buf, arr2tex, mat2gpu, mat2ocl}, + {0, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, arr2buf, arr2tex, mat2gpu, mat2ocl}, + {0, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, mat2mat, arr2buf, arr2tex, mat2gpu, mat2ocl}, + {0, buf2arr, buf2arr, buf2arr, buf2arr, buf2arr, buf2arr, buf2arr, buf2arr, buf2arr, 0 }, + {0, tex2arr, tex2arr, tex2arr, tex2arr, tex2arr, tex2arr, tex2arr, tex2arr, tex2arr, 0 }, + {0, gpu2mat, gpu2mat, gpu2mat, gpu2mat, gpu2mat, gpu2mat, arr2buf, arr2tex, gpu2gpu, 0 }, + {0, ocl2mat, ocl2mat, ocl2mat, ocl2mat, ocl2mat, ocl2mat, 0, 0, 0, ocl2ocl} }; const int src_kind = src.kind() >> _InputArray::KIND_SHIFT; const int dst_kind = dst.kind() >> _InputArray::KIND_SHIFT; - CV_DbgAssert( src_kind >= 0 && src_kind < 10 ); - CV_DbgAssert( dst_kind >= 0 && dst_kind < 10 ); + CV_DbgAssert( src_kind >= 0 && src_kind < 11 ); + CV_DbgAssert( dst_kind >= 0 && dst_kind < 11 ); const func_t func = funcs[src_kind][dst_kind]; CV_DbgAssert( func != 0 ); @@ -190,7 +219,6 @@ namespace break; } } - void convertToDepth(InputArray src, OutputArray dst, int depth) { CV_Assert( src.depth() <= CV_64F ); @@ -271,3 +299,70 @@ GpuMat cv::superres::convertToType(const GpuMat& src, int type, GpuMat& buf0, Gp convertToDepth(buf0, buf1, depth); return buf1; } +#ifdef HAVE_OPENCV_OCL +namespace +{ + // TODO(pengx17): remove these overloaded functions until IntputArray fully supports oclMat + void convertToCn(const ocl::oclMat& src, ocl::oclMat& dst, int cn) + { + CV_Assert( src.channels() == 1 || src.channels() == 3 || src.channels() == 4 ); + CV_Assert( cn == 1 || cn == 3 || cn == 4 ); + + static const int codes[5][5] = + { + {-1, -1, -1, -1, -1}, + {-1, -1, -1, COLOR_GRAY2BGR, COLOR_GRAY2BGRA}, + {-1, -1, -1, -1, -1}, + {-1, COLOR_BGR2GRAY, -1, -1, COLOR_BGR2BGRA}, + {-1, COLOR_BGRA2GRAY, -1, COLOR_BGRA2BGR, -1}, + }; + + const int code = codes[src.channels()][cn]; + CV_DbgAssert( code >= 0 ); + + ocl::cvtColor(src, dst, code, cn); + } + void convertToDepth(const ocl::oclMat& src, ocl::oclMat& dst, int depth) + { + CV_Assert( src.depth() <= CV_64F ); + CV_Assert( depth == CV_8U || depth == CV_32F ); + + static const double maxVals[] = + { + std::numeric_limits::max(), + std::numeric_limits::max(), + std::numeric_limits::max(), + std::numeric_limits::max(), + std::numeric_limits::max(), + 1.0, + 1.0, + }; + const double scale = maxVals[depth] / maxVals[src.depth()]; + src.convertTo(dst, depth, scale); + } +} +ocl::oclMat cv::superres::convertToType(const ocl::oclMat& src, int type, ocl::oclMat& buf0, ocl::oclMat& buf1) +{ + if (src.type() == type) + return src; + + const int depth = CV_MAT_DEPTH(type); + const int cn = CV_MAT_CN(type); + + if (src.depth() == depth) + { + convertToCn(src, buf0, cn); + return buf0; + } + + if (src.channels() == cn) + { + convertToDepth(src, buf1, depth); + return buf1; + } + + convertToCn(src, buf0, cn); + convertToDepth(buf0, buf1, depth); + return buf1; +} +#endif diff --git a/modules/superres/src/input_array_utility.hpp b/modules/superres/src/input_array_utility.hpp index 975783dc6f..9fa63da53e 100644 --- a/modules/superres/src/input_array_utility.hpp +++ b/modules/superres/src/input_array_utility.hpp @@ -45,6 +45,9 @@ #include "opencv2/core/core.hpp" #include "opencv2/core/gpumat.hpp" +#ifdef HAVE_OPENCV_OCL +#include "opencv2/ocl/ocl.hpp" +#endif namespace cv { @@ -57,6 +60,10 @@ namespace cv CV_EXPORTS Mat convertToType(const Mat& src, int type, Mat& buf0, Mat& buf1); CV_EXPORTS gpu::GpuMat convertToType(const gpu::GpuMat& src, int type, gpu::GpuMat& buf0, gpu::GpuMat& buf1); + +#ifdef HAVE_OPENCV_OCL + CV_EXPORTS ocl::oclMat convertToType(const ocl::oclMat& src, int type, ocl::oclMat& buf0, ocl::oclMat& buf1); +#endif } } diff --git a/modules/superres/src/opencl/superres_btvl1.cl b/modules/superres/src/opencl/superres_btvl1.cl new file mode 100644 index 0000000000..0efa1709c8 --- /dev/null +++ b/modules/superres/src/opencl/superres_btvl1.cl @@ -0,0 +1,261 @@ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved. +// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// @Authors +// Jin Ma jin@multicorewareinc.com +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other oclMaterials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors as is and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +__kernel void buildMotionMapsKernel(__global float* forwardMotionX, + __global float* forwardMotionY, + __global float* backwardMotionX, + __global float* backwardMotionY, + __global float* forwardMapX, + __global float* forwardMapY, + __global float* backwardMapX, + __global float* backwardMapY, + int forwardMotionX_row, + int forwardMotionX_col, + int forwardMotionX_step, + int forwardMotionY_step, + int backwardMotionX_step, + int backwardMotionY_step, + int forwardMapX_step, + int forwardMapY_step, + int backwardMapX_step, + int backwardMapY_step + ) +{ + int x = get_global_id(0); + int y = get_global_id(1); + + if(x < forwardMotionX_col && y < forwardMotionX_row) + { + float fx = forwardMotionX[y * forwardMotionX_step + x]; + float fy = forwardMotionY[y * forwardMotionY_step + x]; + + float bx = backwardMotionX[y * backwardMotionX_step + x]; + float by = backwardMotionY[y * backwardMotionY_step + x]; + + forwardMapX[y * forwardMapX_step + x] = x + bx; + forwardMapY[y * forwardMapY_step + x] = y + by; + + backwardMapX[y * backwardMapX_step + x] = x + fx; + backwardMapY[y * backwardMapY_step + x] = y + fy; + } +} + +__kernel void upscaleKernel(__global float* src, + __global float* dst, + int src_step, + int dst_step, + int src_row, + int src_col, + int scale, + int channels + ) +{ + int x = get_global_id(0); + int y = get_global_id(1); + + if(x < src_col && y < src_row) + { + if(channels == 1) + { + dst[y * scale * dst_step + x * scale] = src[y * src_step + x]; + }else if(channels == 3) + { + dst[y * channels * scale * dst_step + 3 * x * scale + 0] = src[y * channels * src_step + 3 * x + 0]; + dst[y * channels * scale * dst_step + 3 * x * scale + 1] = src[y * channels * src_step + 3 * x + 1]; + dst[y * channels * scale * dst_step + 3 * x * scale + 2] = src[y * channels * src_step + 3 * x + 2]; + }else + { + dst[y * channels * scale * dst_step + 4 * x * scale + 0] = src[y * channels * src_step + 4 * x + 0]; + dst[y * channels * scale * dst_step + 4 * x * scale + 1] = src[y * channels * src_step + 4 * x + 1]; + dst[y * channels * scale * dst_step + 4 * x * scale + 2] = src[y * channels * src_step + 4 * x + 2]; + dst[y * channels * scale * dst_step + 4 * x * scale + 3] = src[y * channels * src_step + 4 * x + 3]; + } + } +} + + +float diffSign(float a, float b) +{ + return a > b ? 1.0f : a < b ? -1.0f : 0.0f; +} + +float3 diffSign3(float3 a, float3 b) +{ + float3 pos; + pos.x = a.x > b.x ? 1.0f : a.x < b.x ? -1.0f : 0.0f; + pos.y = a.y > b.y ? 1.0f : a.y < b.y ? -1.0f : 0.0f; + pos.z = a.z > b.z ? 1.0f : a.z < b.z ? -1.0f : 0.0f; + return pos; +} + +float4 diffSign4(float4 a, float4 b) +{ + float4 pos; + pos.x = a.x > b.x ? 1.0f : a.x < b.x ? -1.0f : 0.0f; + pos.y = a.y > b.y ? 1.0f : a.y < b.y ? -1.0f : 0.0f; + pos.z = a.z > b.z ? 1.0f : a.z < b.z ? -1.0f : 0.0f; + pos.w = 0.0f; + return pos; +} + +__kernel void diffSignKernel(__global float* src1, + __global float* src2, + __global float* dst, + int src1_row, + int src1_col, + int dst_step, + int src1_step, + int src2_step) +{ + int x = get_global_id(0); + int y = get_global_id(1); + + if(x < src1_col && y < src1_row) + { + dst[y * dst_step + x] = diffSign(src1[y * src1_step + x], src2[y * src2_step + x]); + } + barrier(CLK_LOCAL_MEM_FENCE); +} + +__kernel void calcBtvRegularizationKernel(__global float* src, + __global float* dst, + int src_step, + int dst_step, + int src_row, + int src_col, + int ksize, + int channels, + __global float* c_btvRegWeights + ) +{ + int x = get_global_id(0) + ksize; + int y = get_global_id(1) + ksize; + + if ((y < src_row - ksize) && (x < src_col - ksize)) + { + if(channels == 1) + { + const float srcVal = src[y * src_step + x]; + float dstVal = 0.0f; + + for (int m = 0, count = 0; m <= ksize; ++m) + { + for (int l = ksize; l + m >= 0; --l, ++count) + dstVal = dstVal + c_btvRegWeights[count] * (diffSign(srcVal, src[(y + m) * src_step + (x + l)]) - diffSign(src[(y - m) * src_step + (x - l)], srcVal)); + } + dst[y * dst_step + x] = dstVal; + }else if(channels == 3) + { + float3 srcVal; + srcVal.x = src[y * src_step + 3 * x + 0]; + srcVal.y = src[y * src_step + 3 * x + 1]; + srcVal.z = src[y * src_step + 3 * x + 2]; + + float3 dstVal; + dstVal.x = 0.0f; + dstVal.y = 0.0f; + dstVal.z = 0.0f; + + for (int m = 0, count = 0; m <= ksize; ++m) + { + for (int l = ksize; l + m >= 0; --l, ++count) + { + float3 src1; + src1.x = src[(y + m) * src_step + 3 * (x + l) + 0]; + src1.y = src[(y + m) * src_step + 3 * (x + l) + 1]; + src1.z = src[(y + m) * src_step + 3 * (x + l) + 2]; + + float3 src2; + src2.x = src[(y - m) * src_step + 3 * (x - l) + 0]; + src2.y = src[(y - m) * src_step + 3 * (x - l) + 1]; + src2.z = src[(y - m) * src_step + 3 * (x - l) + 2]; + + dstVal = dstVal + c_btvRegWeights[count] * (diffSign3(srcVal, src1) - diffSign3(src2, srcVal)); + } + } + dst[y * dst_step + 3 * x + 0] = dstVal.x; + dst[y * dst_step + 3 * x + 1] = dstVal.y; + dst[y * dst_step + 3 * x + 2] = dstVal.z; + }else + { + float4 srcVal; + srcVal.x = src[y * src_step + 4 * x + 0];//r type =float + srcVal.y = src[y * src_step + 4 * x + 1];//g + srcVal.z = src[y * src_step + 4 * x + 2];//b + srcVal.w = src[y * src_step + 4 * x + 3];//a + + float4 dstVal; + dstVal.x = 0.0f; + dstVal.y = 0.0f; + dstVal.z = 0.0f; + dstVal.w = 0.0f; + + for (int m = 0, count = 0; m <= ksize; ++m) + { + for (int l = ksize; l + m >= 0; --l, ++count) + { + float4 src1; + src1.x = src[(y + m) * src_step + 4 * (x + l) + 0]; + src1.y = src[(y + m) * src_step + 4 * (x + l) + 1]; + src1.z = src[(y + m) * src_step + 4 * (x + l) + 2]; + src1.w = src[(y + m) * src_step + 4 * (x + l) + 3]; + + float4 src2; + src2.x = src[(y - m) * src_step + 4 * (x - l) + 0]; + src2.y = src[(y - m) * src_step + 4 * (x - l) + 1]; + src2.z = src[(y - m) * src_step + 4 * (x - l) + 2]; + src2.w = src[(y - m) * src_step + 4 * (x - l) + 3]; + + dstVal = dstVal + c_btvRegWeights[count] * (diffSign4(srcVal, src1) - diffSign4(src2, srcVal)); + + } + } + dst[y * dst_step + 4 * x + 0] = dstVal.x; + dst[y * dst_step + 4 * x + 1] = dstVal.y; + dst[y * dst_step + 4 * x + 2] = dstVal.z; + dst[y * dst_step + 4 * x + 3] = dstVal.w; + } + } +} \ No newline at end of file diff --git a/modules/superres/src/optical_flow.cpp b/modules/superres/src/optical_flow.cpp index 12642175d2..125969b3e2 100644 --- a/modules/superres/src/optical_flow.cpp +++ b/modules/superres/src/optical_flow.cpp @@ -719,3 +719,269 @@ Ptr cv::superres::createOptFlow_DualTVL1_GPU() } #endif // HAVE_OPENCV_GPU +#ifdef HAVE_OPENCV_OCL + +namespace +{ + class oclOpticalFlow : public DenseOpticalFlowExt + { + public: + explicit oclOpticalFlow(int work_type); + + void calc(InputArray frame0, InputArray frame1, OutputArray flow1, OutputArray flow2); + void collectGarbage(); + + protected: + virtual void impl(const cv::ocl::oclMat& input0, const cv::ocl::oclMat& input1, cv::ocl::oclMat& dst1, cv::ocl::oclMat& dst2) = 0; + + private: + int work_type_; + cv::ocl::oclMat buf_[6]; + cv::ocl::oclMat u_, v_, flow_; + }; + + oclOpticalFlow::oclOpticalFlow(int work_type) : work_type_(work_type) + { + } + + void oclOpticalFlow::calc(InputArray frame0, InputArray frame1, OutputArray flow1, OutputArray flow2) + { + ocl::oclMat& _frame0 = ocl::getOclMatRef(frame0); + ocl::oclMat& _frame1 = ocl::getOclMatRef(frame1); + ocl::oclMat& _flow1 = ocl::getOclMatRef(flow1); + ocl::oclMat& _flow2 = ocl::getOclMatRef(flow2); + + CV_Assert( _frame1.type() == _frame0.type() ); + CV_Assert( _frame1.size() == _frame0.size() ); + + cv::ocl::oclMat input0_ = convertToType(_frame0, work_type_, buf_[2], buf_[3]); + cv::ocl::oclMat input1_ = convertToType(_frame1, work_type_, buf_[4], buf_[5]); + + impl(input0_, input1_, u_, v_);//go to tvl1 algorithm + + u_.copyTo(_flow1); + v_.copyTo(_flow2); + } + + void oclOpticalFlow::collectGarbage() + { + for (int i = 0; i < 6; ++i) + buf_[i].release(); + u_.release(); + v_.release(); + flow_.release(); + } +} +/////////////////////////////////////////////////////////////////// +// PyrLK_OCL + +namespace +{ + class PyrLK_OCL : public oclOpticalFlow + { + public: + AlgorithmInfo* info() const; + + PyrLK_OCL(); + + void collectGarbage(); + + protected: + void impl(const ocl::oclMat& input0, const ocl::oclMat& input1, ocl::oclMat& dst1, ocl::oclMat& dst2); + + private: + int winSize_; + int maxLevel_; + int iterations_; + + ocl::PyrLKOpticalFlow alg_; + }; + + CV_INIT_ALGORITHM(PyrLK_OCL, "DenseOpticalFlowExt.PyrLK_OCL", + obj.info()->addParam(obj, "winSize", obj.winSize_); + obj.info()->addParam(obj, "maxLevel", obj.maxLevel_); + obj.info()->addParam(obj, "iterations", obj.iterations_)); + + PyrLK_OCL::PyrLK_OCL() : oclOpticalFlow(CV_8UC1) + { + winSize_ = alg_.winSize.width; + maxLevel_ = alg_.maxLevel; + iterations_ = alg_.iters; + } + + void PyrLK_OCL::impl(const cv::ocl::oclMat& input0, const cv::ocl::oclMat& input1, cv::ocl::oclMat& dst1, cv::ocl::oclMat& dst2) + { + alg_.winSize.width = winSize_; + alg_.winSize.height = winSize_; + alg_.maxLevel = maxLevel_; + alg_.iters = iterations_; + + alg_.dense(input0, input1, dst1, dst2); + } + + void PyrLK_OCL::collectGarbage() + { + alg_.releaseMemory(); + oclOpticalFlow::collectGarbage(); + } +} + +Ptr cv::superres::createOptFlow_PyrLK_OCL() +{ + return new PyrLK_OCL; +} + +/////////////////////////////////////////////////////////////////// +// DualTVL1_OCL + +namespace +{ + class DualTVL1_OCL : public oclOpticalFlow + { + public: + AlgorithmInfo* info() const; + + DualTVL1_OCL(); + + void collectGarbage(); + + protected: + void impl(const cv::ocl::oclMat& input0, const cv::ocl::oclMat& input1, cv::ocl::oclMat& dst1, cv::ocl::oclMat& dst2); + + private: + double tau_; + double lambda_; + double theta_; + int nscales_; + int warps_; + double epsilon_; + int iterations_; + bool useInitialFlow_; + + ocl::OpticalFlowDual_TVL1_OCL alg_; + }; + + CV_INIT_ALGORITHM(DualTVL1_OCL, "DenseOpticalFlowExt.DualTVL1_OCL", + obj.info()->addParam(obj, "tau", obj.tau_); + obj.info()->addParam(obj, "lambda", obj.lambda_); + obj.info()->addParam(obj, "theta", obj.theta_); + obj.info()->addParam(obj, "nscales", obj.nscales_); + obj.info()->addParam(obj, "warps", obj.warps_); + obj.info()->addParam(obj, "epsilon", obj.epsilon_); + obj.info()->addParam(obj, "iterations", obj.iterations_); + obj.info()->addParam(obj, "useInitialFlow", obj.useInitialFlow_)); + + DualTVL1_OCL::DualTVL1_OCL() : oclOpticalFlow(CV_8UC1) + { + tau_ = alg_.tau; + lambda_ = alg_.lambda; + theta_ = alg_.theta; + nscales_ = alg_.nscales; + warps_ = alg_.warps; + epsilon_ = alg_.epsilon; + iterations_ = alg_.iterations; + useInitialFlow_ = alg_.useInitialFlow; + } + + void DualTVL1_OCL::impl(const cv::ocl::oclMat& input0, const cv::ocl::oclMat& input1, cv::ocl::oclMat& dst1, cv::ocl::oclMat& dst2) + { + alg_.tau = tau_; + alg_.lambda = lambda_; + alg_.theta = theta_; + alg_.nscales = nscales_; + alg_.warps = warps_; + alg_.epsilon = epsilon_; + alg_.iterations = iterations_; + alg_.useInitialFlow = useInitialFlow_; + + alg_(input0, input1, dst1, dst2); + + } + + void DualTVL1_OCL::collectGarbage() + { + alg_.collectGarbage(); + oclOpticalFlow::collectGarbage(); + } +} + +Ptr cv::superres::createOptFlow_DualTVL1_OCL() +{ + return new DualTVL1_OCL; +} + +/////////////////////////////////////////////////////////////////// +// FarneBack + +namespace +{ + class FarneBack_OCL : public oclOpticalFlow + { + public: + AlgorithmInfo* info() const; + + FarneBack_OCL(); + + void collectGarbage(); + + protected: + void impl(const cv::ocl::oclMat& input0, const cv::ocl::oclMat& input1, cv::ocl::oclMat& dst1, cv::ocl::oclMat& dst2); + + private: + double pyrScale_; + int numLevels_; + int winSize_; + int numIters_; + int polyN_; + double polySigma_; + int flags_; + + ocl::FarnebackOpticalFlow alg_; + }; + + CV_INIT_ALGORITHM(FarneBack_OCL, "DenseOpticalFlowExt.FarneBack_OCL", + obj.info()->addParam(obj, "pyrScale", obj.pyrScale_); + obj.info()->addParam(obj, "numLevels", obj.numLevels_); + obj.info()->addParam(obj, "winSize", obj.winSize_); + obj.info()->addParam(obj, "numIters", obj.numIters_); + obj.info()->addParam(obj, "polyN", obj.polyN_); + obj.info()->addParam(obj, "polySigma", obj.polySigma_); + obj.info()->addParam(obj, "flags", obj.flags_)); + + FarneBack_OCL::FarneBack_OCL() : oclOpticalFlow(CV_8UC1) + { + pyrScale_ = alg_.pyrScale; + numLevels_ = alg_.numLevels; + winSize_ = alg_.winSize; + numIters_ = alg_.numIters; + polyN_ = alg_.polyN; + polySigma_ = alg_.polySigma; + flags_ = alg_.flags; + } + + void FarneBack_OCL::impl(const cv::ocl::oclMat& input0, const cv::ocl::oclMat& input1, cv::ocl::oclMat& dst1, cv::ocl::oclMat& dst2) + { + alg_.pyrScale = pyrScale_; + alg_.numLevels = numLevels_; + alg_.winSize = winSize_; + alg_.numIters = numIters_; + alg_.polyN = polyN_; + alg_.polySigma = polySigma_; + alg_.flags = flags_; + + alg_(input0, input1, dst1, dst2); + } + + void FarneBack_OCL::collectGarbage() + { + alg_.releaseMemory(); + oclOpticalFlow::collectGarbage(); + } +} + +Ptr cv::superres::createOptFlow_Farneback_OCL() +{ + return new FarneBack_OCL; +} + +#endif \ No newline at end of file diff --git a/modules/superres/src/precomp.cpp b/modules/superres/src/precomp.cpp deleted file mode 100644 index 3c01a2596d..0000000000 --- a/modules/superres/src/precomp.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "precomp.hpp" diff --git a/modules/superres/src/precomp.hpp b/modules/superres/src/precomp.hpp index 82b591b3c2..4cf49411b6 100644 --- a/modules/superres/src/precomp.hpp +++ b/modules/superres/src/precomp.hpp @@ -46,9 +46,7 @@ #include #include -#ifdef HAVE_CVCONFIG_H #include "cvconfig.h" -#endif #include "opencv2/opencv_modules.hpp" #include "opencv2/core/core.hpp" @@ -65,6 +63,10 @@ #endif #endif +#ifdef HAVE_OPENCV_OCL + #include "opencv2/ocl/private/util.hpp" +#endif + #ifdef HAVE_OPENCV_HIGHGUI #include "opencv2/highgui/highgui.hpp" #endif diff --git a/modules/superres/test/test_precomp.cpp b/modules/superres/test/test_precomp.cpp deleted file mode 100644 index 0fb6521809..0000000000 --- a/modules/superres/test/test_precomp.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "test_precomp.hpp" diff --git a/modules/superres/test/test_precomp.hpp b/modules/superres/test/test_precomp.hpp index 0371c34a91..8102d432b5 100644 --- a/modules/superres/test/test_precomp.hpp +++ b/modules/superres/test/test_precomp.hpp @@ -51,9 +51,7 @@ #ifndef __OPENCV_TEST_PRECOMP_HPP__ #define __OPENCV_TEST_PRECOMP_HPP__ -#ifdef HAVE_CVCONFIG_H #include "cvconfig.h" -#endif #include "opencv2/opencv_modules.hpp" #include "opencv2/core/core.hpp" diff --git a/modules/superres/test/test_superres.cpp b/modules/superres/test/test_superres.cpp index b4a546c621..9aa9a44bfb 100644 --- a/modules/superres/test/test_superres.cpp +++ b/modules/superres/test/test_superres.cpp @@ -274,5 +274,12 @@ TEST_F(SuperResolution, BTVL1_GPU) { RunTest(cv::superres::createSuperResolution_BTVL1_GPU()); } - #endif +#if defined(HAVE_OPENCV_OCL) && defined(HAVE_OPENCL) +TEST_F(SuperResolution, BTVL1_OCL) +{ + std::vector infos; + cv::ocl::getDevice(infos); + RunTest(cv::superres::createSuperResolution_BTVL1_OCL()); +} +#endif diff --git a/modules/ts/CMakeLists.txt b/modules/ts/CMakeLists.txt index 1eaeb39336..4af917b388 100644 --- a/modules/ts/CMakeLists.txt +++ b/modules/ts/CMakeLists.txt @@ -4,10 +4,7 @@ if(IOS) ocv_module_disable(ts) endif() -if(MINGW) - set(OPENCV_MODULE_TYPE STATIC) -endif() - +set(OPENCV_MODULE_TYPE STATIC) set(OPENCV_MODULE_IS_PART_OF_WORLD FALSE) if(HAVE_CUDA) @@ -22,10 +19,4 @@ ocv_glob_module_sources() ocv_module_include_directories() ocv_create_module() -if(BUILD_SHARED_LIBS AND NOT MINGW) - add_definitions(-DGTEST_CREATE_SHARED_LIBRARY=1) -else() - add_definitions(-DGTEST_CREATE_SHARED_LIBRARY=0) -endif() - ocv_add_precompiled_headers(${the_module}) diff --git a/modules/ts/include/opencv2/ts/ts.hpp b/modules/ts/include/opencv2/ts/ts.hpp index fcef5896c6..2f32c244cc 100644 --- a/modules/ts/include/opencv2/ts/ts.hpp +++ b/modules/ts/include/opencv2/ts/ts.hpp @@ -1,17 +1,12 @@ #ifndef __OPENCV_GTESTCV_HPP__ #define __OPENCV_GTESTCV_HPP__ -#ifdef HAVE_CVCONFIG_H -#include "cvconfig.h" -#endif -#ifndef GTEST_CREATE_SHARED_LIBRARY -#ifdef BUILD_SHARED_LIBS -#define GTEST_LINKED_AS_SHARED_LIBRARY 1 -#endif -#endif - #include // for va_list +#ifdef HAVE_WINRT + #pragma warning(disable:4447) // Disable warning 'main' signature found without threading model +#endif + #ifdef _MSC_VER #pragma warning( disable: 4127 ) #endif @@ -578,6 +573,13 @@ int main(int argc, char **argv) \ return RUN_ALL_TESTS(); \ } +// This usually only makes sense in perf tests with several implementations, +// some of which are not available. +#define CV_TEST_FAIL_NO_IMPL() do { \ + ::testing::Test::RecordProperty("custom_status", "noimpl"); \ + FAIL() << "No equivalent implementation."; \ +} while (0) + #endif #include "ts_perf.hpp" diff --git a/modules/ts/include/opencv2/ts/ts_perf.hpp b/modules/ts/include/opencv2/ts/ts_perf.hpp index 1e68cd49b0..fa88dadb8c 100644 --- a/modules/ts/include/opencv2/ts/ts_perf.hpp +++ b/modules/ts/include/opencv2/ts/ts_perf.hpp @@ -475,9 +475,16 @@ CV_EXPORTS void PrintTo(const Size& sz, ::std::ostream* os); INSTANTIATE_TEST_CASE_P(/*none*/, fixture##_##name, params);\ void fixture##_##name::PerfTestBody() +#if defined(_MSC_VER) && (_MSC_VER <= 1400) +#define CV_PERF_TEST_MAIN_INTERNALS_ARGS(...) \ + while (++argc >= (--argc,-1)) {__VA_ARGS__; break;} /*this ugly construction is needed for VS 2005*/ +#else +#define CV_PERF_TEST_MAIN_INTERNALS_ARGS(...) \ + __VA_ARGS__; +#endif -#define CV_PERF_TEST_MAIN_INTERNALS(modulename, impls, ...) \ - while (++argc >= (--argc,-1)) {__VA_ARGS__; break;} /*this ugly construction is needed for VS 2005*/\ +#define CV_PERF_TEST_MAIN_INTERNALS(modulename, impls, ...) \ + CV_PERF_TEST_MAIN_INTERNALS_ARGS(__VA_ARGS__) \ ::perf::Regression::Init(#modulename);\ ::perf::TestBase::Init(std::vector(impls, impls + sizeof impls / sizeof *impls),\ argc, argv);\ diff --git a/modules/ts/misc/testlog_parser.py b/modules/ts/misc/testlog_parser.py index 5d478645b2..4ab0a3ef2f 100755 --- a/modules/ts/misc/testlog_parser.py +++ b/modules/ts/misc/testlog_parser.py @@ -13,10 +13,17 @@ class TestInfo(object): self.name = xmlnode.getAttribute("name") self.value_param = xmlnode.getAttribute("value_param") self.type_param = xmlnode.getAttribute("type_param") - if xmlnode.getElementsByTagName("failure"): + + custom_status = xmlnode.getAttribute("custom_status") + failures = xmlnode.getElementsByTagName("failure") + + if len(custom_status) > 0: + self.status = custom_status + elif len(failures) > 0: self.status = "failed" else: self.status = xmlnode.getAttribute("status") + if self.name.startswith("DISABLED_"): self.status = "disabled" self.fixture = self.fixture.replace("DISABLED_", "") diff --git a/modules/ts/misc/xls-report.py b/modules/ts/misc/xls-report.py index 131f3fab59..e71a7f66c7 100755 --- a/modules/ts/misc/xls-report.py +++ b/modules/ts/misc/xls-report.py @@ -64,6 +64,10 @@ Name for the sheet. If this parameter is missing, the name of sheet's directory will be used. + * 'sheet_properties': [(string, string)] + List of arbitrary (key, value) pairs that somehow describe the sheet. Will be + dumped into the first row of the sheet in string form. + Note that all keys are optional, although to get useful results, you'll want to specify at least 'configurations' and 'configuration_matchers'. @@ -100,6 +104,7 @@ bad_speedup_style = xlwt.easyxf('font: color red', num_format_str='#0.00') no_speedup_style = no_time_style error_speedup_style = xlwt.easyxf('pattern: pattern solid, fore_color orange') header_style = xlwt.easyxf('font: bold true; alignment: horizontal centre, vertical top, wrap True') +subheader_style = xlwt.easyxf('alignment: horizontal centre, vertical top') class Collector(object): def __init__(self, config_match_func, include_unmatched): @@ -189,6 +194,8 @@ def main(): arg_parser.add_argument('-c', '--config', metavar='CONF', help='global configuration file') arg_parser.add_argument('--include-unmatched', action='store_true', help='include results from XML files that were not recognized by configuration matchers') + arg_parser.add_argument('--show-times-per-pixel', action='store_true', + help='for tests that have an image size parameter, show per-pixel time, as well as total time') args = arg_parser.parse_args() @@ -231,24 +238,66 @@ def main(): sheet = wb.add_sheet(sheet_conf.get('sheet_name', os.path.basename(os.path.abspath(sheet_path)))) - sheet.row(0).height = 800 + sheet_properties = sheet_conf.get('sheet_properties', []) + + sheet.write(0, 0, 'Properties:') + + sheet.write(0, 1, + 'N/A' if len(sheet_properties) == 0 else + ' '.join(str(k) + '=' + repr(v) for (k, v) in sheet_properties)) + + sheet.row(2).height = 800 sheet.panes_frozen = True sheet.remove_splits = True - sheet.horz_split_pos = 1 - sheet.horz_split_first_visible = 1 sheet_comparisons = sheet_conf.get('comparisons', []) - for i, w in enumerate([2000, 15000, 2500, 2000, 15000] - + (len(config_names) + 1 + len(sheet_comparisons)) * [4000]): - sheet.col(i).width = w + row = 2 - for i, caption in enumerate(['Module', 'Test', 'Image\nsize', 'Data\ntype', 'Parameters'] - + config_names + [None] - + [comp['to'] + '\nvs\n' + comp['from'] for comp in sheet_comparisons]): - sheet.row(0).write(i, caption, header_style) + col = 0 - row = 1 + for (w, caption) in [ + (2500, 'Module'), + (10000, 'Test'), + (2000, 'Image\nwidth'), + (2000, 'Image\nheight'), + (2000, 'Data\ntype'), + (7500, 'Other parameters')]: + sheet.col(col).width = w + if args.show_times_per_pixel: + sheet.write_merge(row, row + 1, col, col, caption, header_style) + else: + sheet.write(row, col, caption, header_style) + col += 1 + + for config_name in config_names: + if args.show_times_per_pixel: + sheet.col(col).width = 3000 + sheet.col(col + 1).width = 3000 + sheet.write_merge(row, row, col, col + 1, config_name, header_style) + sheet.write(row + 1, col, 'total, ms', subheader_style) + sheet.write(row + 1, col + 1, 'per pixel, ns', subheader_style) + col += 2 + else: + sheet.col(col).width = 4000 + sheet.write(row, col, config_name, header_style) + col += 1 + + col += 1 # blank column between configurations and comparisons + + for comp in sheet_comparisons: + sheet.col(col).width = 4000 + caption = comp['to'] + '\nvs\n' + comp['from'] + if args.show_times_per_pixel: + sheet.write_merge(row, row + 1, col, col, caption, header_style) + else: + sheet.write(row, col, caption, header_style) + col += 1 + + row += 2 if args.show_times_per_pixel else 1 + + sheet.horz_split_pos = row + sheet.horz_split_first_visible = row module_colors = sheet_conf.get('module_colors', {}) module_styles = {module: xlwt.easyxf('pattern: pattern solid, fore_color {}'.format(color)) @@ -259,21 +308,46 @@ def main(): sheet.write(row, 0, module, module_styles.get(module, xlwt.Style.default_style)) sheet.write(row, 1, test) - param_list = param[1:-1].split(", ") - sheet.write(row, 2, next(ifilter(re_image_size.match, param_list), None)) - sheet.write(row, 3, next(ifilter(re_data_type.match, param_list), None)) + param_list = param[1:-1].split(', ') if param.startswith('(') and param.endswith(')') else [param] + + image_size = next(ifilter(re_image_size.match, param_list), None) + if image_size is not None: + (image_width, image_height) = map(int, image_size.split('x', 1)) + sheet.write(row, 2, image_width) + sheet.write(row, 3, image_height) + del param_list[param_list.index(image_size)] + + data_type = next(ifilter(re_data_type.match, param_list), None) + if data_type is not None: + sheet.write(row, 4, data_type) + del param_list[param_list.index(data_type)] - sheet.row(row).write(4, param) - for i, c in enumerate(config_names): + sheet.row(row).write(5, ' | '.join(param_list)) + + col = 6 + + for c in config_names: if c in configs: - sheet.write(row, 5 + i, configs[c], time_style) + sheet.write(row, col, configs[c], time_style) else: - sheet.write(row, 5 + i, None, no_time_style) - - for i, comp in enumerate(sheet_comparisons): + sheet.write(row, col, None, no_time_style) + col += 1 + if args.show_times_per_pixel: + sheet.write(row, col, + xlwt.Formula('{0} * 1000000 / ({1} * {2})'.format( + xlwt.Utils.rowcol_to_cell(row, col - 1), + xlwt.Utils.rowcol_to_cell(row, 2), + xlwt.Utils.rowcol_to_cell(row, 3) + )), + time_style + ) + col += 1 + + col += 1 # blank column + + for comp in sheet_comparisons: cmp_from = configs.get(comp["from"]) cmp_to = configs.get(comp["to"]) - col = 5 + len(config_names) + 1 + i if isinstance(cmp_from, numbers.Number) and isinstance(cmp_to, numbers.Number): try: @@ -286,6 +360,8 @@ def main(): else: sheet.write(row, col, None, no_speedup_style) + col += 1 + row += 1 if row % 1000 == 0: sheet.flush_row_data() diff --git a/modules/ts/src/precomp.cpp b/modules/ts/src/precomp.cpp deleted file mode 100644 index c149df18f9..0000000000 --- a/modules/ts/src/precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "precomp.hpp" diff --git a/modules/ts/src/ts_perf.cpp b/modules/ts/src/ts_perf.cpp index c2c1ee6bd2..d84db18866 100644 --- a/modules/ts/src/ts_perf.cpp +++ b/modules/ts/src/ts_perf.cpp @@ -51,10 +51,6 @@ static void setCurrentThreadAffinityMask(int mask) } #endif -#ifdef HAVE_CUDA -# include -#endif - namespace { class PerfEnvironment: public ::testing::Environment @@ -135,7 +131,7 @@ Regression& Regression::addKeypoints(TestBase* test, const std::string& name, co Regression& Regression::addMatches(TestBase* test, const std::string& name, const std::vector& array, double eps, ERROR_TYPE err) { - int len = (int)array.size(); + int len = (int)array.size(); cv::Mat queryIdx(len, 1, CV_32SC1, len ? (void*)&array[0].queryIdx : 0, sizeof(cv::DMatch)); cv::Mat trainIdx(len, 1, CV_32SC1, len ? (void*)&array[0].trainIdx : 0, sizeof(cv::DMatch)); cv::Mat imgIdx (len, 1, CV_32SC1, len ? (void*)&array[0].imgIdx : 0, sizeof(cv::DMatch)); @@ -556,13 +552,6 @@ Regression& Regression::operator() (const std::string& name, cv::InputArray arra std::string nodename = getCurrentTestNodeName(); - // This is a hack for compatibility and it should eventually get removed. - // gpu's tests don't even have CPU sanity data anymore. - if(suiteName == "gpu") - { - nodename = (PERF_RUN_GPU() ? "GPU_" : "CPU_") + nodename; - } - cv::FileNode n = rootIn[nodename]; if(n.isNone()) { diff --git a/modules/video/doc/motion_analysis_and_object_tracking.rst b/modules/video/doc/motion_analysis_and_object_tracking.rst index 5653e21bdf..8f9f41f278 100644 --- a/modules/video/doc/motion_analysis_and_object_tracking.rst +++ b/modules/video/doc/motion_analysis_and_object_tracking.rst @@ -42,6 +42,13 @@ Calculates an optical flow for a sparse feature set using the iterative Lucas-Ka The function implements a sparse iterative version of the Lucas-Kanade optical flow in pyramids. See [Bouguet00]_. The function is parallelized with the TBB library. +.. note:: + + * An example using the Lucas-Kanade optical flow algorithm can be found at opencv_source_code/samples/cpp/lkdemo.cpp + + * (Python) An example using the Lucas-Kanade optical flow algorithm can be found at opencv_source_code/samples/python2/lk_track.py + * (Python) An example using the Lucas-Kanade tracker for homography matching can be found at opencv_source_code/samples/python2/lk_homography.py + buildOpticalFlowPyramid ----------------------- Constructs the image pyramid which can be passed to :ocv:func:`calcOpticalFlowPyrLK`. @@ -109,6 +116,11 @@ The function finds an optical flow for each ``prev`` pixel using the [Farneback2 \texttt{prev} (y,x) \sim \texttt{next} ( y + \texttt{flow} (y,x)[1], x + \texttt{flow} (y,x)[0]) +.. note:: + + * An example using the optical flow algorithm described by Gunnar Farneback can be found at opencv_source_code/samples/cpp/fback.cpp + + * (Python) An example using the optical flow algorithm described by Gunnar Farneback can be found at opencv_source_code/samples/python2/opt_flow.py estimateRigidTransform -------------------------- @@ -227,7 +239,9 @@ In fact, :ocv:func:`fastAtan2` and :ocv:func:`phase` are used so that the computed angle is measured in degrees and covers the full range 0..360. Also, the ``mask`` is filled to indicate pixels where the computed angle is valid. +.. note:: + * (Python) An example on how to perform a motion template technique can be found at opencv_source_code/samples/python2/motempl.py calcGlobalOrientation ------------------------- @@ -313,7 +327,9 @@ First, it finds an object center using See the OpenCV sample ``camshiftdemo.c`` that tracks colored objects. +.. note:: + * (Python) A sample explaining the camshift tracking algorithm can be found at opencv_source_code/samples/python2/camshift.py meanShift --------- @@ -342,7 +358,9 @@ The function implements the iterative object search algorithm. It takes the inpu :ocv:func:`contourArea` ), and rendering the remaining contours with :ocv:func:`drawContours` . +.. note:: + * A mean-shift tracking sample can be found at opencv_source_code/samples/cpp/camshiftdemo.cpp KalmanFilter ------------ @@ -353,7 +371,9 @@ KalmanFilter The class implements a standard Kalman filter http://en.wikipedia.org/wiki/Kalman_filter, [Welch95]_. However, you can modify ``transitionMatrix``, ``controlMatrix``, and ``measurementMatrix`` to get an extended Kalman filter functionality. See the OpenCV sample ``kalman.cpp`` . +.. note:: + * An example using the standard Kalman filter can be found at opencv_source_code/samples/cpp/kalman.cpp KalmanFilter::KalmanFilter @@ -641,7 +661,9 @@ Calculate an optical flow using "SimpleFlow" algorithm. See [Tao2012]_. And site of project - http://graphics.berkeley.edu/papers/Tao-SAN-2012-05/. +.. note:: + * An example using the simpleFlow algorithm can be found at opencv_source_code/samples/cpp/simpleflow_demo.cpp createOptFlow_DualTVL1 ---------------------- diff --git a/modules/video/perf/perf_precomp.cpp b/modules/video/perf/perf_precomp.cpp deleted file mode 100644 index 8552ac3d42..0000000000 --- a/modules/video/perf/perf_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "perf_precomp.hpp" diff --git a/modules/video/src/precomp.cpp b/modules/video/src/precomp.cpp deleted file mode 100644 index 3e0ec42de9..0000000000 --- a/modules/video/src/precomp.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/*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 "precomp.hpp" - -/* End of file. */ diff --git a/modules/video/src/precomp.hpp b/modules/video/src/precomp.hpp index 58fc550862..9b6077f1e5 100644 --- a/modules/video/src/precomp.hpp +++ b/modules/video/src/precomp.hpp @@ -43,9 +43,7 @@ #ifndef __OPENCV_PRECOMP_H__ #define __OPENCV_PRECOMP_H__ -#ifdef HAVE_CVCONFIG_H #include "cvconfig.h" -#endif #include "opencv2/video/tracking.hpp" #include "opencv2/video/background_segm.hpp" diff --git a/modules/video/test/test_precomp.cpp b/modules/video/test/test_precomp.cpp deleted file mode 100644 index 5956e13e3e..0000000000 --- a/modules/video/test/test_precomp.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "test_precomp.hpp" diff --git a/modules/videostab/src/precomp.cpp b/modules/videostab/src/precomp.cpp deleted file mode 100644 index 111385282e..0000000000 --- a/modules/videostab/src/precomp.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include "precomp.hpp" diff --git a/modules/videostab/src/precomp.hpp b/modules/videostab/src/precomp.hpp index c1d8e3039a..f718d0e8ed 100644 --- a/modules/videostab/src/precomp.hpp +++ b/modules/videostab/src/precomp.hpp @@ -43,9 +43,7 @@ #ifndef __OPENCV_PRECOMP_HPP__ #define __OPENCV_PRECOMP_HPP__ -#ifdef HAVE_CVCONFIG_H #include "cvconfig.h" -#endif #include #include diff --git a/modules/world/src/precomp.cpp b/modules/world/src/precomp.cpp deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/modules/world/src/precomp.hpp b/modules/world/src/precomp.hpp index 263095700d..4d88e8c219 100644 --- a/modules/world/src/precomp.hpp +++ b/modules/world/src/precomp.hpp @@ -43,9 +43,7 @@ #ifndef __OPENCV_PRECOMP_H__ #define __OPENCV_PRECOMP_H__ -#ifdef HAVE_CVCONFIG_H #include "cvconfig.h" -#endif #include "opencv2/opencv_modules.hpp" #ifdef HAVE_OPENCV_VIDEO diff --git a/platforms/scripts/camera_build.conf b/platforms/scripts/camera_build.conf index e72fddddbd..7392f91d48 100644 --- a/platforms/scripts/camera_build.conf +++ b/platforms/scripts/camera_build.conf @@ -21,3 +21,7 @@ native_camera_r4.2.0; armeabi-v7a; 14; /home/alexander/Projects/AndroidSource/4. native_camera_r4.2.0; armeabi; 14; /home/alexander/Projects/AndroidSource/4.2 native_camera_r4.2.0; x86; 14; /home/alexander/Projects/AndroidSource/4.2 native_camera_r4.2.0; mips; 14; /home/alexander/Projects/AndroidSource/4.2 +native_camera_r4.3.0; armeabi; 14; /home/alexander/Projects/AndroidSource/4.3 +native_camera_r4.3.0; armeabi-v7a; 14; /home/alexander/Projects/AndroidSource/4.3 +native_camera_r4.3.0; x86; 14; /home/alexander/Projects/AndroidSource/4.3 +native_camera_r4.3.0; mips; 14; /home/alexander/Projects/AndroidSource/4.3 diff --git a/samples/android/CMakeLists.txt b/samples/android/CMakeLists.txt index c0b626d9b1..0dc4a3cd69 100644 --- a/samples/android/CMakeLists.txt +++ b/samples/android/CMakeLists.txt @@ -9,6 +9,7 @@ ocv_warnings_disable(CMAKE_CXX_FLAGS -Wmissing-declarations) add_subdirectory(15-puzzle) add_subdirectory(face-detection) add_subdirectory(image-manipulations) +add_subdirectory(camera-calibration) add_subdirectory(color-blob-detection) add_subdirectory(tutorial-1-camerapreview) add_subdirectory(tutorial-2-mixedprocessing) diff --git a/samples/android/camera-calibration/.classpath b/samples/android/camera-calibration/.classpath new file mode 100644 index 0000000000..46c3d46963 --- /dev/null +++ b/samples/android/camera-calibration/.classpath @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/samples/android/camera-calibration/.project b/samples/android/camera-calibration/.project new file mode 100644 index 0000000000..eae413e1ae --- /dev/null +++ b/samples/android/camera-calibration/.project @@ -0,0 +1,33 @@ + + + OpenCV Sample - camera-calibration + + + + + + com.android.ide.eclipse.adt.ResourceManagerBuilder + + + + + com.android.ide.eclipse.adt.PreCompilerBuilder + + + + + org.eclipse.jdt.core.javabuilder + + + + + com.android.ide.eclipse.adt.ApkBuilder + + + + + + com.android.ide.eclipse.adt.AndroidNature + org.eclipse.jdt.core.javanature + + diff --git a/samples/android/camera-calibration/.settings/org.eclipse.jdt.core.prefs b/samples/android/camera-calibration/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..48ab4c6b11 --- /dev/null +++ b/samples/android/camera-calibration/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,4 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/samples/android/camera-calibration/AndroidManifest.xml b/samples/android/camera-calibration/AndroidManifest.xml new file mode 100644 index 0000000000..5f2dad73c4 --- /dev/null +++ b/samples/android/camera-calibration/AndroidManifest.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/android/camera-calibration/CMakeLists.txt b/samples/android/camera-calibration/CMakeLists.txt new file mode 100644 index 0000000000..83b11b3647 --- /dev/null +++ b/samples/android/camera-calibration/CMakeLists.txt @@ -0,0 +1,6 @@ +set(sample example-camera-calibration) + +add_android_project(${sample} "${CMAKE_CURRENT_SOURCE_DIR}" LIBRARY_DEPS ${OpenCV_BINARY_DIR} SDK_TARGET 11 ${ANDROID_SDK_TARGET}) +if(TARGET ${sample}) + add_dependencies(opencv_android_examples ${sample}) +endif() diff --git a/samples/android/camera-calibration/res/drawable/icon.png b/samples/android/camera-calibration/res/drawable/icon.png new file mode 100644 index 0000000000..79ad948452 Binary files /dev/null and b/samples/android/camera-calibration/res/drawable/icon.png differ diff --git a/samples/android/camera-calibration/res/layout/camera_calibration_surface_view.xml b/samples/android/camera-calibration/res/layout/camera_calibration_surface_view.xml new file mode 100644 index 0000000000..0feccde3a1 --- /dev/null +++ b/samples/android/camera-calibration/res/layout/camera_calibration_surface_view.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/samples/android/camera-calibration/res/menu/calibration.xml b/samples/android/camera-calibration/res/menu/calibration.xml new file mode 100644 index 0000000000..9c90f127c1 --- /dev/null +++ b/samples/android/camera-calibration/res/menu/calibration.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + diff --git a/samples/android/camera-calibration/res/values/strings.xml b/samples/android/camera-calibration/res/values/strings.xml new file mode 100644 index 0000000000..e1ce932a14 --- /dev/null +++ b/samples/android/camera-calibration/res/values/strings.xml @@ -0,0 +1,18 @@ + + + + OCV Camera Calibration + Calibrate + Calibration + Undistortion + Comparison + Preview mode + Successfully calibrated!\nAvg. re-projection error: + Unsuccessful calibration.\nTry again + Please, capture more samples + Calibrating... + Please, wait + Original + Undistorted + + diff --git a/samples/android/camera-calibration/src/org/opencv/samples/cameracalibration/CalibrationResult.java b/samples/android/camera-calibration/src/org/opencv/samples/cameracalibration/CalibrationResult.java new file mode 100644 index 0000000000..4b03d5967a --- /dev/null +++ b/samples/android/camera-calibration/src/org/opencv/samples/cameracalibration/CalibrationResult.java @@ -0,0 +1,69 @@ +package org.opencv.samples.cameracalibration; + +import org.opencv.core.Mat; + +import android.app.Activity; +import android.content.Context; +import android.content.SharedPreferences; +import android.util.Log; + +public abstract class CalibrationResult { + private static final String TAG = "OCVSample::CalibrationResult"; + + private static final int CAMERA_MATRIX_ROWS = 3; + private static final int CAMERA_MATRIX_COLS = 3; + private static final int DISTORTION_COEFFICIENTS_SIZE = 5; + + public static void save(Activity activity, Mat cameraMatrix, Mat distortionCoefficients) { + SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE); + SharedPreferences.Editor editor = sharedPref.edit(); + + double[] cameraMatrixArray = new double[CAMERA_MATRIX_ROWS * CAMERA_MATRIX_COLS]; + cameraMatrix.get(0, 0, cameraMatrixArray); + for (int i = 0; i < CAMERA_MATRIX_ROWS; i++) { + for (int j = 0; j < CAMERA_MATRIX_COLS; j++) { + Integer id = i * CAMERA_MATRIX_ROWS + j; + editor.putFloat(id.toString(), (float)cameraMatrixArray[id]); + } + } + + double[] distortionCoefficientsArray = new double[DISTORTION_COEFFICIENTS_SIZE]; + distortionCoefficients.get(0, 0, distortionCoefficientsArray); + int shift = CAMERA_MATRIX_ROWS * CAMERA_MATRIX_COLS; + for (Integer i = shift; i < DISTORTION_COEFFICIENTS_SIZE + shift; i++) { + editor.putFloat(i.toString(), (float)distortionCoefficientsArray[i-shift]); + } + + editor.commit(); + Log.i(TAG, "Saved camera matrix: " + cameraMatrix.dump()); + Log.i(TAG, "Saved distortion coefficients: " + distortionCoefficients.dump()); + } + + public static boolean tryLoad(Activity activity, Mat cameraMatrix, Mat distortionCoefficients) { + SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE); + if (sharedPref.getFloat("0", -1) == -1) { + Log.i(TAG, "No previous calibration results found"); + return false; + } + + double[] cameraMatrixArray = new double[CAMERA_MATRIX_ROWS * CAMERA_MATRIX_COLS]; + for (int i = 0; i < CAMERA_MATRIX_ROWS; i++) { + for (int j = 0; j < CAMERA_MATRIX_COLS; j++) { + Integer id = i * CAMERA_MATRIX_ROWS + j; + cameraMatrixArray[id] = sharedPref.getFloat(id.toString(), -1); + } + } + cameraMatrix.put(0, 0, cameraMatrixArray); + Log.i(TAG, "Loaded camera matrix: " + cameraMatrix.dump()); + + double[] distortionCoefficientsArray = new double[DISTORTION_COEFFICIENTS_SIZE]; + int shift = CAMERA_MATRIX_ROWS * CAMERA_MATRIX_COLS; + for (Integer i = shift; i < DISTORTION_COEFFICIENTS_SIZE + shift; i++) { + distortionCoefficientsArray[i - shift] = sharedPref.getFloat(i.toString(), -1); + } + distortionCoefficients.put(0, 0, distortionCoefficientsArray); + Log.i(TAG, "Loaded distortion coefficients: " + distortionCoefficients.dump()); + + return true; + } +} diff --git a/samples/android/camera-calibration/src/org/opencv/samples/cameracalibration/CameraCalibrationActivity.java b/samples/android/camera-calibration/src/org/opencv/samples/cameracalibration/CameraCalibrationActivity.java new file mode 100644 index 0000000000..33c9bbbf46 --- /dev/null +++ b/samples/android/camera-calibration/src/org/opencv/samples/cameracalibration/CameraCalibrationActivity.java @@ -0,0 +1,216 @@ +// This sample is based on "Camera calibration With OpenCV" tutorial: +// http://docs.opencv.org/doc/tutorials/calib3d/camera_calibration/camera_calibration.html +// +// It uses standard OpenCV asymmetric circles grid pattern 11x4: +// https://github.com/Itseez/opencv/blob/2.4/doc/acircles_pattern.png. +// The results are the camera matrix and 5 distortion coefficients. +// +// Tap on highlighted pattern to capture pattern corners for calibration. +// Move pattern along the whole screen and capture data. +// +// When you've captured necessary amount of pattern corners (usually ~20 are enough), +// press "Calibrate" button for performing camera calibration. + +package org.opencv.samples.cameracalibration; + +import org.opencv.android.BaseLoaderCallback; +import org.opencv.android.CameraBridgeViewBase; +import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame; +import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2; +import org.opencv.android.LoaderCallbackInterface; +import org.opencv.android.OpenCVLoader; +import org.opencv.core.Mat; + +import android.app.Activity; +import android.app.ProgressDialog; +import android.content.res.Resources; +import android.os.AsyncTask; +import android.os.Bundle; +import android.util.Log; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MotionEvent; +import android.view.SurfaceView; +import android.view.View; +import android.view.View.OnTouchListener; +import android.view.WindowManager; +import android.widget.Toast; + +public class CameraCalibrationActivity extends Activity implements CvCameraViewListener2, OnTouchListener { + private static final String TAG = "OCVSample::Activity"; + + private CameraBridgeViewBase mOpenCvCameraView; + private CameraCalibrator mCalibrator; + private OnCameraFrameRender mOnCameraFrameRender; + private int mWidth; + private int mHeight; + + private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) { + @Override + public void onManagerConnected(int status) { + switch (status) { + case LoaderCallbackInterface.SUCCESS: + { + Log.i(TAG, "OpenCV loaded successfully"); + mOpenCvCameraView.enableView(); + mOpenCvCameraView.setOnTouchListener(CameraCalibrationActivity.this); + } break; + default: + { + super.onManagerConnected(status); + } break; + } + } + }; + + public CameraCalibrationActivity() { + Log.i(TAG, "Instantiated new " + this.getClass()); + } + + @Override + public void onCreate(Bundle savedInstanceState) { + Log.i(TAG, "called onCreate"); + super.onCreate(savedInstanceState); + getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + + setContentView(R.layout.camera_calibration_surface_view); + + mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.camera_calibration_java_surface_view); + mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE); + mOpenCvCameraView.setCvCameraViewListener(this); + } + + @Override + public void onPause() + { + super.onPause(); + if (mOpenCvCameraView != null) + mOpenCvCameraView.disableView(); + } + + @Override + public void onResume() + { + super.onResume(); + OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_2, this, mLoaderCallback); + } + + public void onDestroy() { + super.onDestroy(); + if (mOpenCvCameraView != null) + mOpenCvCameraView.disableView(); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + super.onCreateOptionsMenu(menu); + getMenuInflater().inflate(R.menu.calibration, menu); + + return true; + } + + @Override + public boolean onPrepareOptionsMenu (Menu menu) { + super.onPrepareOptionsMenu(menu); + menu.findItem(R.id.preview_mode).setEnabled(true); + if (!mCalibrator.isCalibrated()) + menu.findItem(R.id.preview_mode).setEnabled(false); + + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.calibration: + mOnCameraFrameRender = + new OnCameraFrameRender(new CalibrationFrameRender(mCalibrator)); + item.setChecked(true); + return true; + case R.id.undistortion: + mOnCameraFrameRender = + new OnCameraFrameRender(new UndistortionFrameRender(mCalibrator)); + item.setChecked(true); + return true; + case R.id.comparison: + mOnCameraFrameRender = + new OnCameraFrameRender(new ComparisonFrameRender(mCalibrator, mWidth, mHeight, getResources())); + item.setChecked(true); + return true; + case R.id.calibrate: + final Resources res = getResources(); + if (mCalibrator.getCornersBufferSize() < 2) { + (Toast.makeText(this, res.getString(R.string.more_samples), Toast.LENGTH_SHORT)).show(); + return true; + } + + mOnCameraFrameRender = new OnCameraFrameRender(new PreviewFrameRender()); + new AsyncTask() { + private ProgressDialog calibrationProgress; + + @Override + protected void onPreExecute() { + calibrationProgress = new ProgressDialog(CameraCalibrationActivity.this); + calibrationProgress.setTitle(res.getString(R.string.calibrating)); + calibrationProgress.setMessage(res.getString(R.string.please_wait)); + calibrationProgress.setCancelable(false); + calibrationProgress.setIndeterminate(true); + calibrationProgress.show(); + } + + @Override + protected Void doInBackground(Void... arg0) { + mCalibrator.calibrate(); + return null; + } + + @Override + protected void onPostExecute(Void result) { + calibrationProgress.dismiss(); + mCalibrator.clearCorners(); + mOnCameraFrameRender = new OnCameraFrameRender(new CalibrationFrameRender(mCalibrator)); + String resultMessage = (mCalibrator.isCalibrated()) ? + res.getString(R.string.calibration_successful) + " " + mCalibrator.getAvgReprojectionError() : + res.getString(R.string.calibration_unsuccessful); + (Toast.makeText(CameraCalibrationActivity.this, resultMessage, Toast.LENGTH_SHORT)).show(); + + if (mCalibrator.isCalibrated()) { + CalibrationResult.save(CameraCalibrationActivity.this, + mCalibrator.getCameraMatrix(), mCalibrator.getDistortionCoefficients()); + } + } + }.execute(); + return true; + default: + return super.onOptionsItemSelected(item); + } + } + + public void onCameraViewStarted(int width, int height) { + if (mWidth != width || mHeight != height) { + mWidth = width; + mHeight = height; + mCalibrator = new CameraCalibrator(mWidth, mHeight); + if (CalibrationResult.tryLoad(this, mCalibrator.getCameraMatrix(), mCalibrator.getDistortionCoefficients())) { + mCalibrator.setCalibrated(); + } + + mOnCameraFrameRender = new OnCameraFrameRender(new CalibrationFrameRender(mCalibrator)); + } + } + + public void onCameraViewStopped() { + } + + public Mat onCameraFrame(CvCameraViewFrame inputFrame) { + return mOnCameraFrameRender.render(inputFrame); + } + + @Override + public boolean onTouch(View v, MotionEvent event) { + Log.d(TAG, "onTouch invoked"); + + mCalibrator.addCorners(); + return false; + } +} diff --git a/samples/android/camera-calibration/src/org/opencv/samples/cameracalibration/CameraCalibrator.java b/samples/android/camera-calibration/src/org/opencv/samples/cameracalibration/CameraCalibrator.java new file mode 100644 index 0000000000..f0cd230a82 --- /dev/null +++ b/samples/android/camera-calibration/src/org/opencv/samples/cameracalibration/CameraCalibrator.java @@ -0,0 +1,169 @@ +package org.opencv.samples.cameracalibration; + +import java.util.ArrayList; +import java.util.List; + +import org.opencv.calib3d.Calib3d; +import org.opencv.core.Core; +import org.opencv.core.CvType; +import org.opencv.core.Mat; +import org.opencv.core.MatOfDouble; +import org.opencv.core.MatOfPoint2f; +import org.opencv.core.MatOfPoint3f; +import org.opencv.core.Point; +import org.opencv.core.Scalar; +import org.opencv.core.Size; + +import android.util.Log; + +public class CameraCalibrator { + private static final String TAG = "OCVSample::CameraCalibrator"; + + private final Size mPatternSize = new Size(4, 11); + private final int mCornersSize = (int)(mPatternSize.width * mPatternSize.height); + private boolean mPatternWasFound = false; + private MatOfPoint2f mCorners = new MatOfPoint2f(); + private List mCornersBuffer = new ArrayList(); + private boolean mIsCalibrated = false; + + private Mat mCameraMatrix = new Mat(); + private Mat mDistortionCoefficients = new Mat(); + private int mFlags; + private double mRms; + private double mSquareSize = 0.0181; + private Size mImageSize; + + public CameraCalibrator(int width, int height) { + mImageSize = new Size(width, height); + mFlags = Calib3d.CALIB_FIX_PRINCIPAL_POINT + + Calib3d.CALIB_ZERO_TANGENT_DIST + + Calib3d.CALIB_FIX_ASPECT_RATIO + + Calib3d.CALIB_FIX_K4 + + Calib3d.CALIB_FIX_K5; + Mat.eye(3, 3, CvType.CV_64FC1).copyTo(mCameraMatrix); + mCameraMatrix.put(0, 0, 1.0); + Mat.zeros(5, 1, CvType.CV_64FC1).copyTo(mDistortionCoefficients); + Log.i(TAG, "Instantiated new " + this.getClass()); + } + + public void processFrame(Mat grayFrame, Mat rgbaFrame) { + findPattern(grayFrame); + renderFrame(rgbaFrame); + } + + public void calibrate() { + ArrayList rvecs = new ArrayList(); + ArrayList tvecs = new ArrayList(); + Mat reprojectionErrors = new Mat(); + ArrayList objectPoints = new ArrayList(); + objectPoints.add(Mat.zeros(mCornersSize, 1, CvType.CV_32FC3)); + calcBoardCornerPositions(objectPoints.get(0)); + for (int i = 1; i < mCornersBuffer.size(); i++) { + objectPoints.add(objectPoints.get(0)); + } + + Calib3d.calibrateCamera(objectPoints, mCornersBuffer, mImageSize, + mCameraMatrix, mDistortionCoefficients, rvecs, tvecs, mFlags); + + mIsCalibrated = Core.checkRange(mCameraMatrix) + && Core.checkRange(mDistortionCoefficients); + + mRms = computeReprojectionErrors(objectPoints, rvecs, tvecs, reprojectionErrors); + Log.i(TAG, String.format("Average re-projection error: %f", mRms)); + Log.i(TAG, "Camera matrix: " + mCameraMatrix.dump()); + Log.i(TAG, "Distortion coefficients: " + mDistortionCoefficients.dump()); + } + + public void clearCorners() { + mCornersBuffer.clear(); + } + + private void calcBoardCornerPositions(Mat corners) { + final int cn = 3; + float positions[] = new float[mCornersSize * cn]; + + for (int i = 0; i < mPatternSize.height; i++) { + for (int j = 0; j < mPatternSize.width * cn; j += cn) { + positions[(int) (i * mPatternSize.width * cn + j + 0)] = + (2 * (j / cn) + i % 2) * (float) mSquareSize; + positions[(int) (i * mPatternSize.width * cn + j + 1)] = + i * (float) mSquareSize; + positions[(int) (i * mPatternSize.width * cn + j + 2)] = 0; + } + } + corners.create(mCornersSize, 1, CvType.CV_32FC3); + corners.put(0, 0, positions); + } + + private double computeReprojectionErrors(List objectPoints, + List rvecs, List tvecs, Mat perViewErrors) { + MatOfPoint2f cornersProjected = new MatOfPoint2f(); + double totalError = 0; + double error; + float viewErrors[] = new float[objectPoints.size()]; + + MatOfDouble distortionCoefficients = new MatOfDouble(mDistortionCoefficients); + int totalPoints = 0; + for (int i = 0; i < objectPoints.size(); i++) { + MatOfPoint3f points = new MatOfPoint3f(objectPoints.get(i)); + Calib3d.projectPoints(points, rvecs.get(i), tvecs.get(i), + mCameraMatrix, distortionCoefficients, cornersProjected); + error = Core.norm(mCornersBuffer.get(i), cornersProjected, Core.NORM_L2); + + int n = objectPoints.get(i).rows(); + viewErrors[i] = (float) Math.sqrt(error * error / n); + totalError += error * error; + totalPoints += n; + } + perViewErrors.create(objectPoints.size(), 1, CvType.CV_32FC1); + perViewErrors.put(0, 0, viewErrors); + + return Math.sqrt(totalError / totalPoints); + } + + private void findPattern(Mat grayFrame) { + mPatternWasFound = Calib3d.findCirclesGridDefault(grayFrame, mPatternSize, + mCorners, Calib3d.CALIB_CB_ASYMMETRIC_GRID); + } + + public void addCorners() { + if (mPatternWasFound) { + mCornersBuffer.add(mCorners.clone()); + } + } + + private void drawPoints(Mat rgbaFrame) { + Calib3d.drawChessboardCorners(rgbaFrame, mPatternSize, mCorners, mPatternWasFound); + } + + private void renderFrame(Mat rgbaFrame) { + drawPoints(rgbaFrame); + + Core.putText(rgbaFrame, "Captured: " + mCornersBuffer.size(), new Point(rgbaFrame.cols() / 3 * 2, rgbaFrame.rows() * 0.1), + Core.FONT_HERSHEY_SIMPLEX, 1.0, new Scalar(255, 255, 0)); + } + + public Mat getCameraMatrix() { + return mCameraMatrix; + } + + public Mat getDistortionCoefficients() { + return mDistortionCoefficients; + } + + public int getCornersBufferSize() { + return mCornersBuffer.size(); + } + + public double getAvgReprojectionError() { + return mRms; + } + + public boolean isCalibrated() { + return mIsCalibrated; + } + + public void setCalibrated() { + mIsCalibrated = true; + } +} diff --git a/samples/android/camera-calibration/src/org/opencv/samples/cameracalibration/OnCameraFrameRender.java b/samples/android/camera-calibration/src/org/opencv/samples/cameracalibration/OnCameraFrameRender.java new file mode 100644 index 0000000000..3f155c2bfc --- /dev/null +++ b/samples/android/camera-calibration/src/org/opencv/samples/cameracalibration/OnCameraFrameRender.java @@ -0,0 +1,102 @@ +package org.opencv.samples.cameracalibration; + +import java.util.ArrayList; +import java.util.List; + +import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame; +import org.opencv.core.Core; +import org.opencv.core.Mat; +import org.opencv.core.MatOfPoint; +import org.opencv.core.Point; +import org.opencv.core.Range; +import org.opencv.core.Scalar; +import org.opencv.imgproc.Imgproc; + +import android.content.res.Resources; + +abstract class FrameRender { + protected CameraCalibrator mCalibrator; + + public abstract Mat render(CvCameraViewFrame inputFrame); +} + +class PreviewFrameRender extends FrameRender { + @Override + public Mat render(CvCameraViewFrame inputFrame) { + return inputFrame.rgba(); + } +} + +class CalibrationFrameRender extends FrameRender { + public CalibrationFrameRender(CameraCalibrator calibrator) { + mCalibrator = calibrator; + } + + @Override + public Mat render(CvCameraViewFrame inputFrame) { + Mat rgbaFrame = inputFrame.rgba(); + Mat grayFrame = inputFrame.gray(); + mCalibrator.processFrame(grayFrame, rgbaFrame); + + return rgbaFrame; + } +} + +class UndistortionFrameRender extends FrameRender { + public UndistortionFrameRender(CameraCalibrator calibrator) { + mCalibrator = calibrator; + } + + @Override + public Mat render(CvCameraViewFrame inputFrame) { + Mat renderedFrame = new Mat(inputFrame.rgba().size(), inputFrame.rgba().type()); + Imgproc.undistort(inputFrame.rgba(), renderedFrame, + mCalibrator.getCameraMatrix(), mCalibrator.getDistortionCoefficients()); + + return renderedFrame; + } +} + +class ComparisonFrameRender extends FrameRender { + private int mWidth; + private int mHeight; + private Resources mResources; + public ComparisonFrameRender(CameraCalibrator calibrator, int width, int height, Resources resources) { + mCalibrator = calibrator; + mWidth = width; + mHeight = height; + mResources = resources; + } + + @Override + public Mat render(CvCameraViewFrame inputFrame) { + Mat undistortedFrame = new Mat(inputFrame.rgba().size(), inputFrame.rgba().type()); + Imgproc.undistort(inputFrame.rgba(), undistortedFrame, + mCalibrator.getCameraMatrix(), mCalibrator.getDistortionCoefficients()); + + Mat comparisonFrame = inputFrame.rgba(); + undistortedFrame.colRange(new Range(0, mWidth / 2)).copyTo(comparisonFrame.colRange(new Range(mWidth / 2, mWidth))); + List border = new ArrayList(); + final int shift = (int)(mWidth * 0.005); + border.add(new MatOfPoint(new Point(mWidth / 2 - shift, 0), new Point(mWidth / 2 + shift, 0), + new Point(mWidth / 2 + shift, mHeight), new Point(mWidth / 2 - shift, mHeight))); + Core.fillPoly(comparisonFrame, border, new Scalar(255, 255, 255)); + + Core.putText(comparisonFrame, mResources.getString(R.string.original), new Point(mWidth * 0.1, mHeight * 0.1), + Core.FONT_HERSHEY_SIMPLEX, 1.0, new Scalar(255, 255, 0)); + Core.putText(comparisonFrame, mResources.getString(R.string.undistorted), new Point(mWidth * 0.6, mHeight * 0.1), + Core.FONT_HERSHEY_SIMPLEX, 1.0, new Scalar(255, 255, 0)); + + return comparisonFrame; + } +} + +class OnCameraFrameRender { + private FrameRender mFrameRender; + public OnCameraFrameRender(FrameRender frameRender) { + mFrameRender = frameRender; + } + public Mat render(CvCameraViewFrame inputFrame) { + return mFrameRender.render(inputFrame); + } +}