1
0
mirror of https://github.com/opencv/opencv.git synced 2026-07-25 13:23:02 +04:00

Compare commits

...

50 Commits

Author SHA1 Message Date
Alexander Alekhin 01b2c5a77c release: OpenCV 4.3.0 2020-04-03 11:45:28 +00:00
Alexander Alekhin 3a45a65625 Merge remote-tracking branch 'upstream/3.4' into merge-3.4 2020-04-03 11:44:22 +00:00
Alexander Alekhin 0812207db7 Merge tag '3.4.10' 2020-04-03 11:24:31 +00:00
Alexander Alekhin cf2a3c8e74 Merge remote-tracking branch 'upstream/3.4' into merge-3.4 2020-04-02 21:52:32 +00:00
Alexander Alekhin 1cc1e6fa56 release: OpenCV 3.4.10 2020-04-02 19:59:58 +00:00
Maxim Pashchenkov 277f0d270f Merge pull request #16745 from Volskig:mp/ocv-gapi-standalone-size
G-API: Unification of own:: structures with cv:: (Size, Point, Rect)

* deowned Size Rect Point

* Deownded Size Rect Point

* With Scalar
2020-04-02 18:19:45 +00:00
Alexander Alekhin 6216bf9221 Merge pull request #16959 from alalek:winpack_dldt_update 2020-04-02 18:13:58 +00:00
Alexander Alekhin 388a7ce86e Merge pull request #16956 from alalek:ocl_control_buffer_mapping 2020-04-02 17:56:50 +00:00
Alexander Alekhin 5d95a500ad winpack_dldt: readme update 2020-04-02 16:52:46 +00:00
Alexander Alekhin 95341c2b1b Merge pull request #16953 from mshabunin:fix-msmf-writer-fps 2020-04-02 13:06:34 +00:00
Alexander Alekhin 54063c40de core(ocl): options to control buffer access flags
- control using of clEnqueueMapBuffer or clEnqueueReadBuffer[Rect]
- added benchmarks with OpenCL buffer access use cases
2020-04-02 11:11:06 +00:00
Maksim Shabunin 585593e9fc videoio: fixed MSMF writer fps handling 2020-04-02 12:52:38 +03:00
Alexander Alekhin f15e885baf Merge pull request #16950 from alalek:fix_16945 2020-04-02 09:26:09 +00:00
Alexander Alekhin 9109cb1ec6 Merge pull request #16948 from alalek:warning_16739 2020-04-02 09:25:47 +00:00
Alexander Alekhin dc9ee53ff5 stitching: fix range check in DpSeamFinder::computeCosts 2020-04-02 03:51:17 +00:00
Alexander Alekhin 1485968fc4 Merge pull request #16947 from mshabunin:fix-msmf-convert-format 2020-04-01 18:50:12 +00:00
Maxim Pashchenkov 557ac3dbaf Merge pull request #16805 from Volskig:mp/ocv-gapi-standalone-scalar
G-API: Unification of own:: Scalar with cv:: Scalar

* cvdefs.hpp

* Small changes

* Deowned Scalar. Does't work

* Something

* Removed to_ocv for Scalar

* Clear code

* Deleted whitespaces

* Added include<..own/scalar.hpp in cvdefs.hpp.

* Long string split on two now

* Comment about scalar

* Comment about crutch

* Removed second varible in scalar_wrapper

* Changed wrapper for scalar, alignment

* Alignment

* Whitespaces

* Removed scalar_wrapper
2020-04-01 18:40:38 +00:00
Alexander Alekhin 09134ac881 core: emit warning ONCE on ambiguous MatExpr processing 2020-04-01 18:34:20 +00:00
Maksim Shabunin 433c5199fd videoio: fixed conversion in MSMF backend 2020-04-01 14:40:11 +03:00
Alexander Alekhin d448a636f8 Merge pull request #16943 from alalek:winpack_samples_update_master 2020-04-01 01:46:26 +03:00
Alexander Alekhin 396f43d674 Merge pull request #16938 from alalek:winpack_samples_update 2020-04-01 01:46:13 +03:00
Alexander Alekhin 3c5fec6746 build: updates for winpack dldt 2020-03-31 22:18:21 +00:00
Alexander Alekhin e12b1c2209 build: updates for winpack dldt 2020-03-31 20:29:11 +00:00
Alexander Alekhin f6b2b49e4a Merge pull request #16932 from alalek:imgproc_resize_nn_cleanup 2020-03-30 15:38:40 +00:00
Alexander Alekhin e1322cf503 Merge pull request #16928 from alalek:fix_15075 2020-03-30 13:07:35 +00:00
Alexander Alekhin 67dfdee33f Merge pull request #16922 from alalek:imgcodecs_test_io_grayscale 2020-03-29 16:36:06 +00:00
Alexander Alekhin 61c4cfd896 imgproc(resize): drop unused 'pix_size4' 2020-03-29 02:41:50 +00:00
Alexander Alekhin be17f532e1 imgproc(resize): fix resizeNNInvoker handling of generic pixel size 2020-03-29 02:41:41 +00:00
Alexander Alekhin 6d85fa3fd2 imgcodecs(test): rework common I/O test, added grayscale mode 2020-03-27 21:34:51 +00:00
Alexander Alekhin 95a07ca11c Merge remote-tracking branch 'upstream/3.4' into merge-3.4 2020-03-27 16:49:59 +00:00
Alexander Alekhin 222a48577f Merge pull request #16919 from alalek:backport_16860 2020-03-27 16:44:05 +00:00
Alexander Alekhin 353273579b Merge pull request #16918 from alalek:build_warnings_3.4 2020-03-27 16:43:23 +00:00
Alexander Alekhin 72c5ac37de Merge pull request #16915 from alalek:build_warnings 2020-03-27 16:42:53 +00:00
Alexander Alekhin 1eba7f60c2 Merge pull request #16913 from alalek:gapi_simd_initialization 2020-03-27 16:42:14 +00:00
Alexander Alekhin 7373ef0983 Merge pull request #16847 from alalek:build_opencv_winpack_dldt 2020-03-27 16:06:19 +00:00
Moritz Fischer-Gundlach 2740901378 -calib3d updates documentation
backporting commit 99436bb8cf
2020-03-27 16:02:29 +00:00
Alexander Alekhin 0c00d082cf Merge pull request #16860 from FischerGundlach:rework_docu 2020-03-27 16:00:48 +00:00
Alexander Alekhin e661ad2a67 eliminate build warnings 2020-03-27 11:39:07 +00:00
Alexander Alekhin 3a4b79173b Merge pull request #16916 from cyyever:fix_freebsd_build 2020-03-27 11:38:57 +00:00
cyy bdc29cccb6 fix freebsd build 2020-03-27 18:12:10 +08:00
StefanBruens 8d78400052 Merge pull request #16494 from StefanBruens:jpeg2000_openjpeg_port
Jpeg2000 OpenJPEG port

* OpenJPEG based JPEG2000 decoder implementation

Currently, the following input color spaces and depth conversions are
supported:

- 8 bit -> 8 bit
- 16 bit -> 16 bit (IMREAD_UNCHANGED, IMREAD_ANYDEPTH)

- RGB(a) -> BGR
- RGBA -> BGRA (IMREAD_UNCHANGED)
- Y(a) -> Y(a) (IMREAD_ANYCOLOR, IMREAD_GRAY, IMREAD_UNCHANGED))
- YCC -> Y (IMREAD_GRAY)

* Check for OpenJPEG availability

This enables OpenJPEG based JPEG2000 imread support by default, which
can be disabled by -DWITH_OPENJPEG=OFF. In case OpenJPEG is enabled
and found, any checks for Jasper are skipped.

* Implement precision downscaling for precision > 8 without IMREAD_UNCHANGED

With IMREAD_UNCHANGED, values are kept from the input image, without it
components are downscaled to CV_8U range.

* Enable Jpeg2K tests when OpenJPEG is available

* Add support for some more color conversions

Support IMREAD_GRAY when input color space is RGB or unspecified.
Support YUV input color space for BGR output.

* fix: problems with unmanaged memory

* fix: CMake warning - HAVE_OPENJPEG is undefined

Removed trailing whitespaces

* fix: CMake find_package OpenJPEG add minimal version

* Basic JPEG2K encoder

Images with depth CV_8U and CV_16U are supported, with 1 to 4 channels.

* feature: Improved code for OpenJPEG2000 encoder/decoder

 - Removed code duplication
 - Added error handlers
 - Extracted functions

* feature: Update conversion openjpeg array from/to Mat

* feature: Extend ChannelsIterator to fulfill RandomAccessIterator named requirements

 - Removed channels split in copyFromMatImpl. With ChannelsIterator no allocations are performed.
 - Split whole loop into 2 parts in copyToMat -> where std::copy and std::transforms are called.

* fix: Applied review comments.

 - Changed `nullptr` in CV_LOG* functions to `NULL`
 - Added `falls through` comment in decoder color space `switch`
 - Added warning about unsupported parameters for the encoder

* feature: Added decode from in-memory buffers.

Co-authored-by: Vadim Levin <vadim.levin@xperience.ai>
2020-03-27 07:18:58 +00:00
Alexander Alekhin b4b4d21212 eliminate build warnings 2020-03-26 19:18:09 +00:00
Alexander Alekhin 99502e99cc gapi(simd): initialize accumulator values 2020-03-26 16:48:21 +00:00
Moritz Fischer-Gundlach 99436bb8cf -calib3d updates documentation 2020-03-26 15:22:39 +01:00
Alexander Alekhin 7465125f67 build: add winpack_dldt build scripts 2020-03-25 21:26:41 +00:00
Alexander Alekhin 340df65fb4 Merge pull request #16903 from alalek:fix_16823_3.4 2020-03-25 15:53:08 +00:00
Alexander Alekhin 9a463b74dc Merge pull request #16901 from alalek:cmake_ie_find_extra_libs 2020-03-25 15:52:15 +00:00
Anatoliy Talamanov c303aaa94d Merge pull request #16841 from TolyaTalamanov:at/warp-perspective
G-API: Implement WarpPerspective

* Implement WarpPerspective kernel

* Fix comment to review
2020-03-25 11:23:32 +00:00
Alexander Alekhin c920b45fb8 core(persistence): fix resource leaks - force closing files
backporting commit 673eb2b006
2020-03-25 10:49:16 +00:00
Alexander Alekhin 2a9a2fff66 cmake: fix find process for InferenceEngine extra libraries 2020-03-25 02:43:42 +00:00
94 changed files with 3068 additions and 674 deletions
+12 -5
View File
@@ -285,9 +285,12 @@ OCV_OPTION(WITH_INF_ENGINE "Include Intel Inference Engine support" OFF
OCV_OPTION(WITH_NGRAPH "Include nGraph support" WITH_INF_ENGINE
VISIBLE_IF TRUE
VERIFY TARGET ngraph::ngraph)
OCV_OPTION(WITH_JASPER "Include JPEG2K support" ON
OCV_OPTION(WITH_JASPER "Include JPEG2K support (Jasper)" ON
VISIBLE_IF NOT IOS
VERIFY HAVE_JASPER)
OCV_OPTION(WITH_OPENJPEG "Include JPEG2K support (OpenJPEG)" ON
VISIBLE_IF NOT IOS
VERIFY HAVE_OPENJPEG)
OCV_OPTION(WITH_JPEG "Include JPEG support" ON
VISIBLE_IF TRUE
VERIFY HAVE_JPEG)
@@ -943,11 +946,11 @@ endif()
# for UNIX it does not make sense as LICENSE and readme will be part of the package automatically
if(ANDROID OR NOT UNIX)
install(FILES ${OPENCV_LICENSE_FILE}
PERMISSIONS OWNER_READ GROUP_READ WORLD_READ
PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ
DESTINATION ./ COMPONENT libs)
if(OPENCV_README_FILE)
install(FILES ${OPENCV_README_FILE}
PERMISSIONS OWNER_READ GROUP_READ WORLD_READ
PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ
DESTINATION ./ COMPONENT libs)
endif()
endif()
@@ -1249,8 +1252,12 @@ if(WITH_TIFF OR HAVE_TIFF)
status(" TIFF:" TIFF_FOUND THEN "${TIFF_LIBRARY} (ver ${TIFF_VERSION} / ${TIFF_VERSION_STRING})" ELSE "build (ver ${TIFF_VERSION} - ${TIFF_VERSION_STRING})")
endif()
if(WITH_JASPER OR HAVE_JASPER)
status(" JPEG 2000:" JASPER_FOUND THEN "${JASPER_LIBRARY} (ver ${JASPER_VERSION_STRING})" ELSE "build (ver ${JASPER_VERSION_STRING})")
if(HAVE_OPENJPEG)
status(" JPEG 2000:" "OpenJPEG (ver ${OPENJPEG_MAJOR_VERSION}.${OPENJPEG_MINOR_VERSION}.${OPENJPEG_BUILD_VERSION})")
elseif(HAVE_JASPER)
status(" JPEG 2000:" JASPER_FOUND THEN "${JASPER_LIBRARY} (ver ${JASPER_VERSION_STRING})" ELSE "build Jasper (ver ${JASPER_VERSION_STRING})")
elseif(WITH_OPENJPEG OR WITH_JASPER)
status(" JPEG 2000:" "NO")
endif()
if(WITH_OPENEXR OR HAVE_OPENEXR)
+47 -10
View File
@@ -17,10 +17,34 @@
# INF_ENGINE_TARGET - set to name of imported library target representing InferenceEngine
#
macro(ocv_ie_find_extra_libraries find_prefix find_suffix)
file(GLOB libraries "${INF_ENGINE_LIB_DIRS}/${find_prefix}inference_engine*${find_suffix}")
foreach(full_path IN LISTS libraries)
get_filename_component(library "${full_path}" NAME_WE)
string(REPLACE "${find_prefix}" "" library "${library}")
if(library STREQUAL "inference_engine" OR library STREQUAL "inference_engined")
# skip
else()
add_library(${library} UNKNOWN IMPORTED)
set_target_properties(${library} PROPERTIES
IMPORTED_LOCATION "${full_path}")
list(APPEND custom_libraries ${library})
endif()
endforeach()
endmacro()
function(add_custom_ie_build _inc _lib _lib_rel _lib_dbg _msg)
if(NOT _inc OR NOT (_lib OR _lib_rel OR _lib_dbg))
return()
endif()
if(NOT _lib)
if(_lib_rel)
set(_lib "${_lib_rel}")
else()
set(_lib "${_lib_dbg}")
endif()
endif()
add_library(inference_engine UNKNOWN IMPORTED)
set_target_properties(inference_engine PROPERTIES
IMPORTED_LOCATION "${_lib}"
@@ -30,24 +54,31 @@ function(add_custom_ie_build _inc _lib _lib_rel _lib_dbg _msg)
)
set(custom_libraries "")
file(GLOB libraries "${INF_ENGINE_LIB_DIRS}/${CMAKE_SHARED_LIBRARY_PREFIX}inference_engine_*${CMAKE_SHARED_LIBRARY_SUFFIX}")
foreach(full_path IN LISTS libraries)
get_filename_component(library "${full_path}" NAME_WE)
string(REPLACE "${CMAKE_SHARED_LIBRARY_PREFIX}" "" library "${library}")
add_library(${library} UNKNOWN IMPORTED)
set_target_properties(${library} PROPERTIES
IMPORTED_LOCATION "${full_path}")
list(APPEND custom_libraries ${library})
set(__prefixes "${CMAKE_FIND_LIBRARY_PREFIXES}")
if(NOT __prefixes)
set(__prefixes "_empty_")
endif()
foreach(find_prefix ${__prefixes})
if(find_prefix STREQUAL "_empty_") # foreach doesn't iterate over empty elements
set(find_prefix "")
endif()
foreach(find_suffix ${CMAKE_FIND_LIBRARY_SUFFIXES})
ocv_ie_find_extra_libraries("${find_prefix}" "${find_suffix}")
endforeach()
if(NOT CMAKE_FIND_LIBRARY_SUFFIXES)
ocv_ie_find_extra_libraries("${find_prefix}" "")
endif()
endforeach()
if(NOT INF_ENGINE_RELEASE VERSION_GREATER "2018050000")
find_library(INF_ENGINE_OMP_LIBRARY iomp5 PATHS "${INF_ENGINE_OMP_DIR}" NO_DEFAULT_PATH)
if(NOT INF_ENGINE_OMP_LIBRARY)
message(WARNING "OpenMP for IE have not been found. Set INF_ENGINE_OMP_DIR variable if you experience build errors.")
else()
set_target_properties(inference_engine PROPERTIES IMPORTED_LINK_INTERFACE_LIBRARIES "${INF_ENGINE_OMP_LIBRARY}")
endif()
endif()
if(EXISTS "${INF_ENGINE_OMP_LIBRARY}")
set_target_properties(inference_engine PROPERTIES IMPORTED_LINK_INTERFACE_LIBRARIES "${INF_ENGINE_OMP_LIBRARY}")
endif()
set(INF_ENGINE_VERSION "Unknown" CACHE STRING "")
set(INF_ENGINE_TARGET "inference_engine;${custom_libraries}" PARENT_SCOPE)
message(STATUS "Detected InferenceEngine: ${_msg}")
@@ -64,6 +95,9 @@ endif()
if(NOT INF_ENGINE_TARGET AND INF_ENGINE_LIB_DIRS AND INF_ENGINE_INCLUDE_DIRS)
find_path(ie_custom_inc "inference_engine.hpp" PATHS "${INF_ENGINE_INCLUDE_DIRS}" NO_DEFAULT_PATH)
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
find_library(ie_custom_lib_dbg "inference_engined" PATHS "${INF_ENGINE_LIB_DIRS}" NO_DEFAULT_PATH) # Win32 and MacOSX
endif()
find_library(ie_custom_lib "inference_engine" PATHS "${INF_ENGINE_LIB_DIRS}" NO_DEFAULT_PATH)
find_library(ie_custom_lib_rel "inference_engine" PATHS "${INF_ENGINE_LIB_DIRS}/Release" NO_DEFAULT_PATH)
find_library(ie_custom_lib_dbg "inference_engine" PATHS "${INF_ENGINE_LIB_DIRS}/Debug" NO_DEFAULT_PATH)
@@ -82,6 +116,9 @@ if(NOT INF_ENGINE_TARGET AND _loc)
endif()
set(INF_ENGINE_PLATFORM "${INF_ENGINE_PLATFORM_DEFAULT}" CACHE STRING "InferenceEngine platform (library dir)")
find_path(ie_custom_env_inc "inference_engine.hpp" PATHS "${_loc}/deployment_tools/inference_engine/include" NO_DEFAULT_PATH)
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
find_library(ie_custom_env_lib_dbg "inference_engined" PATHS "${_loc}/deployment_tools/inference_engine/lib/${INF_ENGINE_PLATFORM}/intel64" NO_DEFAULT_PATH)
endif()
find_library(ie_custom_env_lib "inference_engine" PATHS "${_loc}/deployment_tools/inference_engine/lib/${INF_ENGINE_PLATFORM}/intel64" NO_DEFAULT_PATH)
find_library(ie_custom_env_lib_rel "inference_engine" PATHS "${_loc}/deployment_tools/inference_engine/lib/intel64/Release" NO_DEFAULT_PATH)
find_library(ie_custom_env_lib_dbg "inference_engine" PATHS "${_loc}/deployment_tools/inference_engine/lib/intel64/Debug" NO_DEFAULT_PATH)
+17 -2
View File
@@ -153,8 +153,23 @@ if(NOT WEBP_VERSION AND WEBP_INCLUDE_DIR)
endif()
endif()
# --- libopenjp2 (optional, check before libjasper) ---
if(WITH_OPENJPEG)
find_package(OpenJPEG QUIET)
if(NOT OpenJPEG_FOUND OR OPENJPEG_MAJOR_VERSION LESS 2)
set(HAVE_OPENJPEG NO)
ocv_clear_vars(OPENJPEG_MAJOR_VERSION OPENJPEG_MINOR_VERSION OPENJPEG_BUILD_VERSION OPENJPEG_LIBRARIES OPENJPEG_INCLUDE_DIRS)
message(STATUS "Could NOT find OpenJPEG (minimal suitable version: 2.0, recommended version >= 2.3.1)")
else()
set(HAVE_OPENJPEG YES)
message(STATUS "Found OpenJPEG: ${OPENJPEG_LIBRARIES} "
"(found version \"${OPENJPEG_MAJOR_VERSION}.${OPENJPEG_MINOR_VERSION}.${OPENJPEG_BUILD_VERSION}\")")
endif()
endif()
# --- libjasper (optional, should be searched after libjpeg) ---
if(WITH_JASPER)
if(WITH_JASPER AND NOT HAVE_OPENJPEG)
if(BUILD_JASPER)
ocv_clear_vars(JASPER_FOUND)
else()
@@ -273,4 +288,4 @@ if(WITH_IMGCODEC_PFM)
set(HAVE_IMGCODEC_PFM ON)
elseif(DEFINED WITH_IMGCODEC_PFM)
set(HAVE_IMGCODEC_PFM OFF)
endif()
endif()
+23 -2
View File
@@ -1087,6 +1087,17 @@ macro(ocv_check_dependencies)
endforeach()
endmacro()
################################################################################
# OpenCV tests
################################################################################
if(DEFINED OPENCV_BUILD_TEST_MODULES_LIST)
string(REPLACE "," ";" OPENCV_BUILD_TEST_MODULES_LIST "${OPENCV_BUILD_TEST_MODULES_LIST}") # support comma-separated list (,) too
endif()
if(DEFINED OPENCV_BUILD_PERF_TEST_MODULES_LIST)
string(REPLACE "," ";" OPENCV_BUILD_PERF_TEST_MODULES_LIST "${OPENCV_BUILD_PERF_TEST_MODULES_LIST}") # support comma-separated list (,) too
endif()
# auxiliary macro to parse arguments of ocv_add_accuracy_tests and ocv_add_perf_tests commands
macro(__ocv_parse_test_sources tests_type)
set(OPENCV_${tests_type}_${the_module}_SOURCES "")
@@ -1127,7 +1138,12 @@ function(ocv_add_perf_tests)
endif()
set(perf_path "${CMAKE_CURRENT_LIST_DIR}/perf")
if(BUILD_PERF_TESTS AND EXISTS "${perf_path}")
if(BUILD_PERF_TESTS AND EXISTS "${perf_path}"
AND (NOT DEFINED OPENCV_BUILD_PERF_TEST_MODULES_LIST
OR OPENCV_BUILD_PERF_TEST_MODULES_LIST STREQUAL "all"
OR ";${OPENCV_BUILD_PERF_TEST_MODULES_LIST};" MATCHES ";${name};"
)
)
__ocv_parse_test_sources(PERF ${ARGN})
# opencv_imgcodecs is required for imread/imwrite
@@ -1212,7 +1228,12 @@ function(ocv_add_accuracy_tests)
ocv_debug_message("ocv_add_accuracy_tests(" ${ARGN} ")")
set(test_path "${CMAKE_CURRENT_LIST_DIR}/test")
if(BUILD_TESTS AND EXISTS "${test_path}")
if(BUILD_TESTS AND EXISTS "${test_path}"
AND (NOT DEFINED OPENCV_BUILD_TEST_MODULES_LIST
OR OPENCV_BUILD_TEST_MODULES_LIST STREQUAL "all"
OR ";${OPENCV_BUILD_TEST_MODULES_LIST};" MATCHES ";${name};"
)
)
__ocv_parse_test_sources(TEST ${ARGN})
# opencv_imgcodecs is required for imread/imwrite
+1
View File
@@ -81,6 +81,7 @@
#cmakedefine HAVE_IPP_IW_LL
/* JPEG-2000 codec */
#cmakedefine HAVE_OPENJPEG
#cmakedefine HAVE_JASPER
/* IJG JPEG codec */
File diff suppressed because it is too large Load Diff
-9
View File
@@ -797,15 +797,6 @@ Ellipse::Ellipse(const cv::Point2f &_center, const cv::Size2f &_axes, float _ang
{
}
Ellipse::Ellipse(const Ellipse &other)
{
center = other.center;
axes= other.axes;
angle= other.angle;
cosf = other.cosf;
sinf = other.sinf;
}
const cv::Size2f &Ellipse::getAxes()const
{
return axes;
-2
View File
@@ -111,8 +111,6 @@ class Ellipse
public:
Ellipse();
Ellipse(const cv::Point2f &center, const cv::Size2f &axes, float angle);
Ellipse(const Ellipse &other);
void draw(cv::InputOutputArray img,const cv::Scalar &color = cv::Scalar::all(120))const;
bool contains(const cv::Point2f &pt)const;
@@ -8,7 +8,7 @@
#define CV_VERSION_MAJOR 4
#define CV_VERSION_MINOR 3
#define CV_VERSION_REVISION 0
#define CV_VERSION_STATUS "-pre"
#define CV_VERSION_STATUS ""
#define CVAUX_STR_EXP(__A) #__A
#define CVAUX_STR(__A) CVAUX_STR_EXP(__A)
+135
View File
@@ -146,6 +146,141 @@ OCL_PERF_TEST_P(CopyToFixture, CopyToWithMaskUninit,
SANITY_CHECK(dst);
}
enum ROIType {
ROI_FULL,
ROI_2_RECT,
ROI_2_TOP, // contiguous memory block
ROI_2_LEFT,
ROI_4,
ROI_16,
};
static Rect getROI(enum ROIType t, const Size& sz)
{
switch (t)
{
case ROI_FULL: return Rect(0, 0, sz.width, sz.height);
case ROI_2_RECT: return Rect(0, 0, sz.width * 71 / 100, sz.height * 71 / 100); // 71 = sqrt(1/2) * 100
case ROI_2_TOP: return Rect(0, 0, sz.width, sz.height / 2); // 71 = sqrt(1/2) * 100
case ROI_2_LEFT: return Rect(0, 0, sz.width / 2, sz.height); // 71 = sqrt(1/2) * 100
case ROI_4: return Rect(0, 0, sz.width / 2, sz.height / 2);
case ROI_16: return Rect(0, 0, sz.width / 4, sz.height / 4);
}
CV_Assert(false);
}
typedef TestBaseWithParam< tuple<cv::Size, MatType, ROIType> > OpenCLBuffer;
static inline void PrintTo(const tuple<cv::Size, MatType, enum ROIType>& v, std::ostream* os)
{
*os << "(" << get<0>(v) << ", " << typeToString(get<1>(v)) << ", ";
enum ROIType roiType = get<2>(v);
if (roiType == ROI_FULL)
*os << "ROI_100_FULL";
else if (roiType == ROI_2_RECT)
*os << "ROI_050_RECT_HALF";
else if (roiType == ROI_2_TOP)
*os << "ROI_050_TOP_HALF";
else if (roiType == ROI_2_LEFT)
*os << "ROI_050_LEFT_HALF";
else if (roiType == ROI_4)
*os << "ROI_025_1/4";
else
*os << "ROI_012_1/16";
*os << ")";
}
PERF_TEST_P_(OpenCLBuffer, cpu_write)
{
const Size srcSize = get<0>(GetParam());
const int type = get<1>(GetParam());
const Rect roi = getROI(get<2>(GetParam()), srcSize);
checkDeviceMaxMemoryAllocSize(srcSize, type);
UMat src(srcSize, type);
declare.in(src(roi), WARMUP_NONE);
OCL_TEST_CYCLE()
{
Mat m = src(roi).getMat(ACCESS_WRITE);
m.setTo(Scalar(1, 2, 3, 4));
}
SANITY_CHECK_NOTHING();
}
PERF_TEST_P_(OpenCLBuffer, cpu_read)
{
const Size srcSize = get<0>(GetParam());
const int type = get<1>(GetParam());
const Rect roi = getROI(get<2>(GetParam()), srcSize);
checkDeviceMaxMemoryAllocSize(srcSize, type);
UMat src(srcSize, type, Scalar(1, 2, 3, 4));
declare.in(src(roi), WARMUP_NONE);
OCL_TEST_CYCLE()
{
unsigned counter = 0;
Mat m = src(roi).getMat(ACCESS_READ);
for (int y = 0; y < m.rows; y++)
{
uchar* ptr = m.ptr(y);
size_t width_bytes = m.cols * m.elemSize();
for (size_t x_bytes = 0; x_bytes < width_bytes; x_bytes++)
counter += (unsigned)(ptr[x_bytes]);
}
}
SANITY_CHECK_NOTHING();
}
PERF_TEST_P_(OpenCLBuffer, cpu_update)
{
const Size srcSize = get<0>(GetParam());
const int type = get<1>(GetParam());
const Rect roi = getROI(get<2>(GetParam()), srcSize);
checkDeviceMaxMemoryAllocSize(srcSize, type);
UMat src(srcSize, type, Scalar(1, 2, 3, 4));
declare.in(src(roi), WARMUP_NONE);
OCL_TEST_CYCLE()
{
Mat m = src(roi).getMat(ACCESS_READ | ACCESS_WRITE);
for (int y = 0; y < m.rows; y++)
{
uchar* ptr = m.ptr(y);
size_t width_bytes = m.cols * m.elemSize();
for (size_t x_bytes = 0; x_bytes < width_bytes; x_bytes++)
ptr[x_bytes] += 1;
}
}
SANITY_CHECK_NOTHING();
}
INSTANTIATE_TEST_CASE_P(/*FULL*/, OpenCLBuffer,
testing::Combine(
testing::Values(szVGA, sz720p, sz1080p, sz2160p),
testing::Values(CV_8UC1, CV_8UC2, CV_8UC3, CV_8UC4),
testing::Values(ROI_FULL)
)
);
INSTANTIATE_TEST_CASE_P(ROI, OpenCLBuffer,
testing::Combine(
testing::Values(sz1080p, sz2160p),
testing::Values(CV_8UC1),
testing::Values(ROI_16, ROI_4, ROI_2_RECT, ROI_2_LEFT, ROI_2_TOP, ROI_FULL)
)
);
} } // namespace opencv_test::ocl
#endif // HAVE_OPENCL
+9
View File
@@ -10,6 +10,7 @@
// */
#include "precomp.hpp"
#include <opencv2/core/utils/logger.hpp>
namespace cv
{
@@ -1319,10 +1320,18 @@ void MatOp_AddEx::assign(const MatExpr& e, Mat& m, int _type) const
cv::add(dst, e.s, dst);
}
else
{
if (e.a.channels() > 1)
CV_LOG_ONCE_WARNING(NULL, "OpenCV/MatExpr: processing of multi-channel arrays might be changed in the future: "
"https://github.com/opencv/opencv/issues/16739");
cv::addWeighted(e.a, e.alpha, e.b, e.beta, e.s[0], dst);
}
}
else if( e.s.isReal() && (dst.data != m.data || fabs(e.alpha) != 1))
{
if (e.a.channels() > 1)
CV_LOG_ONCE_WARNING(NULL, "OpenCV/MatExpr: processing of multi-channel arrays might be changed in the future: "
"https://github.com/opencv/opencv/issues/16739");
e.a.convertTo(m, _type, e.alpha, e.s[0]);
return;
}
+20 -1
View File
@@ -4602,6 +4602,17 @@ public:
return u;
}
static bool isOpenCLMapForced() // force clEnqueueMapBuffer / clEnqueueUnmapMemObject OpenCL API
{
static bool value = cv::utils::getConfigurationParameterBool("OPENCV_OPENCL_BUFFER_FORCE_MAPPING", false);
return value;
}
static bool isOpenCLCopyingForced() // force clEnqueueReadBuffer[Rect] / clEnqueueWriteBuffer[Rect] OpenCL API
{
static bool value = cv::utils::getConfigurationParameterBool("OPENCV_OPENCL_BUFFER_FORCE_COPYING", false);
return value;
}
void getBestFlags(const Context& ctx, AccessFlag /*flags*/, UMatUsageFlags usageFlags, int& createFlags, UMatData::MemoryFlag& flags0) const
{
const Device& dev = ctx.device(0);
@@ -4609,7 +4620,15 @@ public:
if ((usageFlags & USAGE_ALLOCATE_HOST_MEMORY) != 0)
createFlags |= CL_MEM_ALLOC_HOST_PTR;
if( dev.hostUnifiedMemory() )
if (!isOpenCLCopyingForced() &&
(isOpenCLMapForced() ||
(dev.hostUnifiedMemory()
#ifndef __APPLE__
|| dev.isIntel()
#endif
)
)
)
flags0 = static_cast<UMatData::MemoryFlag>(0);
else
flags0 = UMatData::COPY_ON_MAP;
+4 -1
View File
@@ -54,7 +54,7 @@
#endif
#if defined __linux__ || defined __APPLE__ || defined __GLIBC__ \
|| defined __HAIKU__ || defined __EMSCRIPTEN__
|| defined __HAIKU__ || defined __EMSCRIPTEN__ || defined __FreeBSD__
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
@@ -95,6 +95,9 @@
*/
#if defined HAVE_TBB
#ifndef TBB_SUPPRESS_DEPRECATED_MESSAGES // supress warning
#define TBB_SUPPRESS_DEPRECATED_MESSAGES 1
#endif
#include "tbb/tbb.h"
#include "tbb/task.h"
#include "tbb/tbb_stddef.h"
+1
View File
@@ -122,6 +122,7 @@ endif()
ocv_module_include_directories(${include_dirs})
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
ocv_append_source_files_cxx_compiler_options(fw_srcs "-Wno-suggest-override") # GCC
ocv_append_source_files_cxx_compiler_options(fw_srcs "-Wno-array-bounds") # GCC 9.3.0 (Ubuntu 20.04)
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
ocv_append_source_files_cxx_compiler_options(fw_srcs "-Wno-inconsistent-missing-override") # Clang
endif()
+33 -1
View File
@@ -486,10 +486,18 @@ namespace core {
}
};
G_TYPED_KERNEL(GWarpPerspective, <GMat(GMat, const Mat&, Size, int, int, const cv::Scalar&)>, "org.opencv.core.warpPerspective") {
static GMatDesc outMeta(GMatDesc in, const Mat&, Size dsize, int, int borderMode, const cv::Scalar&) {
GAPI_Assert((borderMode == cv::BORDER_CONSTANT || borderMode == cv::BORDER_REPLICATE) &&
"cv::gapi::warpPerspective supports only cv::BORDER_CONSTANT and cv::BORDER_REPLICATE border modes");
return in.withType(in.depth, in.chan).withSize(dsize);
}
};
G_TYPED_KERNEL(GWarpAffine, <GMat(GMat, const Mat&, Size, int, int, const cv::Scalar&)>, "org.opencv.core.warpAffine") {
static GMatDesc outMeta(GMatDesc in, const Mat&, Size dsize, int, int border_mode, const cv::Scalar&) {
GAPI_Assert(border_mode != cv::BORDER_TRANSPARENT &&
"cv::BORDER_TRANSPARENT mode isn't support in G-API");
"cv::BORDER_TRANSPARENT mode is not supported in cv::gapi::warpAffine");
return in.withType(in.depth, in.chan).withSize(dsize);
}
};
@@ -1662,6 +1670,30 @@ number of channels as src and the depth =ddepth.
GAPI_EXPORTS GMat normalize(const GMat& src, double alpha, double beta,
int norm_type, int ddepth = -1);
/** @brief Applies a perspective transformation to an image.
The function warpPerspective transforms the source image using the specified matrix:
\f[\texttt{dst} (x,y) = \texttt{src} \left ( \frac{M_{11} x + M_{12} y + M_{13}}{M_{31} x + M_{32} y + M_{33}} ,
\frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )\f]
when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with invert
and then put in the formula above instead of M. The function cannot operate in-place.
@param src input image.
@param M \f$3\times 3\f$ transformation matrix.
@param dsize size of the output image.
@param flags combination of interpolation methods (#INTER_LINEAR or #INTER_NEAREST) and the
optional flag #WARP_INVERSE_MAP, that sets M as the inverse transformation (
\f$\texttt{dst}\rightarrow\texttt{src}\f$ ).
@param borderMode pixel extrapolation method (#BORDER_CONSTANT or #BORDER_REPLICATE).
@param borderValue value used in case of a constant border; by default, it equals 0.
@sa warpAffine, resize, remap, getRectSubPix, perspectiveTransform
*/
GAPI_EXPORTS GMat warpPerspective(const GMat& src, const Mat& M, const Size& dsize, int flags = cv::INTER_LINEAR,
int borderMode = cv::BORDER_CONSTANT, const Scalar& borderValue = Scalar());
/** @brief Applies an affine transformation to an image.
The function warpAffine transforms the source image using the specified matrix:
@@ -99,8 +99,8 @@ public:
const cv::gapi::own::Mat& inMat(int input);
cv::gapi::own::Mat& outMatR(int output); // FIXME: Avoid cv::gapi::own::Mat m = ctx.outMatR()
const cv::gapi::own::Scalar& inVal(int input);
cv::gapi::own::Scalar& outValR(int output); // FIXME: Avoid cv::gapi::own::Scalar s = ctx.outValR()
const cv::Scalar& inVal(int input);
cv::Scalar& outValR(int output); // FIXME: Avoid cv::Scalar s = ctx.outValR()
template<typename T> std::vector<T>& outVecR(int output) // FIXME: the same issue
{
return outVecRef(output).wref<T>();
@@ -155,7 +155,7 @@ template<> struct get_in<cv::GMatP>
};
template<> struct get_in<cv::GScalar>
{
static cv::Scalar get(GCPUContext &ctx, int idx) { return to_ocv(ctx.inVal(idx)); }
static cv::Scalar get(GCPUContext &ctx, int idx) { return ctx.inVal(idx); }
};
template<typename U> struct get_in<cv::GArray<U> >
{
@@ -208,23 +208,12 @@ struct tracked_cv_mat{
}
};
struct scalar_wrapper
{
scalar_wrapper(cv::gapi::own::Scalar& s) : m_s{cv::gapi::own::to_ocv(s)}, m_org_s(s) {};
operator cv::Scalar& () { return m_s; }
void writeBack() const { m_org_s = to_own(m_s); }
cv::Scalar m_s;
cv::gapi::own::Scalar& m_org_s;
};
template<typename... Outputs>
void postprocess(Outputs&... outs)
{
struct
{
void operator()(tracked_cv_mat* bm) { bm->validate(); }
void operator()(scalar_wrapper* sw) { sw->writeBack(); }
void operator()(...) { }
} validate;
@@ -251,10 +240,9 @@ template<> struct get_out<cv::GMatP>
};
template<> struct get_out<cv::GScalar>
{
static scalar_wrapper get(GCPUContext &ctx, int idx)
static cv::Scalar& get(GCPUContext &ctx, int idx)
{
auto& s = ctx.outValR(idx);
return {s};
return ctx.outValR(idx);
}
};
template<typename U> struct get_out<cv::GArray<U>>
@@ -18,7 +18,6 @@
#include <opencv2/gapi/gmat.hpp>
#include <opencv2/gapi/util/optional.hpp>
#include <opencv2/gapi/own/scalar.hpp>
#include <opencv2/gapi/own/mat.hpp>
namespace cv {
@@ -27,13 +26,11 @@ namespace fluid {
struct Border
{
#if !defined(GAPI_STANDALONE)
// This constructor is required to support existing kernels which are part of G-API
Border(int _type, cv::Scalar _val) : type(_type), value(to_own(_val)) {};
#endif // !defined(GAPI_STANDALONE)
Border(int _type, cv::gapi::own::Scalar _val) : type(_type), value(_val) {};
Border(int _type, cv::Scalar _val) : type(_type), value(_val) {};
int type;
cv::gapi::own::Scalar value;
cv::Scalar value;
};
using BorderOpt = util::optional<Border>;
@@ -17,7 +17,6 @@
#include <opencv2/gapi/gcommon.hpp>
#include <opencv2/gapi/gkernel.hpp>
#include <opencv2/gapi/garg.hpp>
#include <opencv2/gapi/own/types.hpp>
#include <opencv2/gapi/fluid/gfluidbuffer.hpp>
@@ -109,7 +108,7 @@ public:
*/
struct GFluidOutputRois
{
std::vector<cv::gapi::own::Rect> rois;
std::vector<cv::Rect> rois;
};
/**
@@ -179,17 +178,10 @@ template<> struct fluid_get_in<cv::GMat>
template<> struct fluid_get_in<cv::GScalar>
{
// FIXME: change to return by reference when moved to own::Scalar
#if !defined(GAPI_STANDALONE)
static const cv::Scalar get(const cv::GArgs &in_args, int idx)
{
return cv::gapi::own::to_ocv(in_args[idx].unsafe_get<cv::gapi::own::Scalar>());
return in_args[idx].unsafe_get<cv::Scalar>();
}
#else
static const cv::gapi::own::Scalar get(const cv::GArgs &in_args, int idx)
{
return in_args[idx].get<cv::gapi::own::Scalar>();
}
#endif // !defined(GAPI_STANDALONE)
};
template<typename U> struct fluid_get_in<cv::GArray<U>>
+2 -5
View File
@@ -23,7 +23,6 @@
#include <opencv2/gapi/gopaque.hpp>
#include <opencv2/gapi/gtype_traits.hpp>
#include <opencv2/gapi/gmetaarg.hpp>
#include <opencv2/gapi/own/scalar.hpp>
#include <opencv2/gapi/streaming/source.hpp>
namespace cv {
@@ -91,12 +90,11 @@ using GArgs = std::vector<GArg>;
using GRunArg = util::variant<
#if !defined(GAPI_STANDALONE)
cv::Mat,
cv::Scalar,
cv::UMat,
#endif // !defined(GAPI_STANDALONE)
cv::gapi::wip::IStreamSource::Ptr,
cv::gapi::own::Mat,
cv::gapi::own::Scalar,
cv::Scalar,
cv::detail::VectorRef,
cv::detail::OpaqueRef
>;
@@ -125,11 +123,10 @@ struct Data: public GRunArg
using GRunArgP = util::variant<
#if !defined(GAPI_STANDALONE)
cv::Mat*,
cv::Scalar*,
cv::UMat*,
#endif // !defined(GAPI_STANDALONE)
cv::gapi::own::Mat*,
cv::gapi::own::Scalar*,
cv::Scalar*,
cv::detail::VectorRef,
cv::detail::OpaqueRef
>;
+5 -17
View File
@@ -14,8 +14,6 @@
#include <opencv2/gapi/opencv_includes.hpp>
#include <opencv2/gapi/gcommon.hpp> // GShape
#include <opencv2/gapi/own/types.hpp> // cv::gapi::own::Size
#include <opencv2/gapi/own/convert.hpp> // to_own
#include <opencv2/gapi/own/assert.hpp>
// TODO GAPI_EXPORTS or so
@@ -82,11 +80,11 @@ struct GAPI_EXPORTS GMatDesc
// FIXME: Default initializers in C++14
int depth;
int chan;
cv::gapi::own::Size size; // NB.: no multi-dimensional cases covered yet
cv::Size size; // NB.: no multi-dimensional cases covered yet
bool planar;
std::vector<int> dims; // FIXME: Maybe it's real questionable to have it here
GMatDesc(int d, int c, cv::gapi::own::Size s, bool p = false)
GMatDesc(int d, int c, cv::Size s, bool p = false)
: depth(d), chan(c), size(s), planar(p) {}
GMatDesc(int d, const std::vector<int> &dd)
@@ -122,23 +120,13 @@ struct GAPI_EXPORTS GMatDesc
// Meta combinator: return a new GMatDesc which differs in size by delta
// (all other fields are taken unchanged from this GMatDesc)
// FIXME: a better name?
GMatDesc withSizeDelta(cv::gapi::own::Size delta) const
GMatDesc withSizeDelta(cv::Size delta) const
{
GMatDesc desc(*this);
desc.size += delta;
return desc;
}
#if !defined(GAPI_STANDALONE)
GMatDesc withSizeDelta(cv::Size delta) const
{
return withSizeDelta(to_own(delta));
}
GMatDesc withSize(cv::Size sz) const
{
return withSize(to_own(sz));
}
bool canDescribe(const cv::Mat& mat) const;
#endif // !defined(GAPI_STANDALONE)
// Meta combinator: return a new GMatDesc which differs in size by delta
@@ -147,10 +135,10 @@ struct GAPI_EXPORTS GMatDesc
// This is an overload.
GMatDesc withSizeDelta(int dx, int dy) const
{
return withSizeDelta(cv::gapi::own::Size{dx,dy});
return withSizeDelta(cv::Size{dx,dy});
}
GMatDesc withSize(cv::gapi::own::Size sz) const
GMatDesc withSize(cv::Size sz) const
{
GMatDesc desc(*this);
desc.size = sz;
+3 -11
View File
@@ -14,7 +14,6 @@
#include <opencv2/gapi/opencv_includes.hpp>
#include <opencv2/gapi/gcommon.hpp> // GShape
#include <opencv2/gapi/util/optional.hpp>
#include <opencv2/gapi/own/scalar.hpp>
namespace cv
{
@@ -31,11 +30,9 @@ class GAPI_EXPORTS GScalar
{
public:
GScalar(); // Empty constructor
explicit GScalar(const cv::gapi::own::Scalar& s); // Constant value constructor from cv::gapi::own::Scalar
explicit GScalar(cv::gapi::own::Scalar&& s); // Constant value move-constructor from cv::gapi::own::Scalar
#if !defined(GAPI_STANDALONE)
explicit GScalar(const cv::Scalar& s); // Constant value constructor from cv::Scalar
#endif // !defined(GAPI_STANDALONE)
explicit GScalar(const cv::Scalar& s); // Constant value constructor from cv::Scalar
explicit GScalar(cv::Scalar&& s); // Constant value move-constructor from cv::Scalar
GScalar(double v0); // Constant value constructor from double
GScalar(const GNode &n, std::size_t out); // Operation result constructor
@@ -69,12 +66,7 @@ struct GScalarDesc
static inline GScalarDesc empty_scalar_desc() { return GScalarDesc(); }
#if !defined(GAPI_STANDALONE)
GAPI_EXPORTS GScalarDesc descr_of(const cv::Scalar &scalar);
#endif // !defined(GAPI_STANDALONE)
/** @} */
GAPI_EXPORTS GScalarDesc descr_of(const cv::gapi::own::Scalar &scalar);
std::ostream& operator<<(std::ostream& os, const cv::GScalarDesc &desc);
@@ -107,10 +107,9 @@ namespace detail
#if !defined(GAPI_STANDALONE)
template<> struct GTypeOf<cv::Mat> { using type = cv::GMat; };
template<> struct GTypeOf<cv::UMat> { using type = cv::GMat; };
template<> struct GTypeOf<cv::Scalar> { using type = cv::GScalar; };
#endif // !defined(GAPI_STANDALONE)
template<> struct GTypeOf<cv::gapi::own::Mat> { using type = cv::GMat; };
template<> struct GTypeOf<cv::gapi::own::Scalar> { using type = cv::GScalar; };
template<> struct GTypeOf<cv::Scalar> { using type = cv::GScalar; };
template<typename U> struct GTypeOf<std::vector<U> > { using type = cv::GArray<U>; };
template<typename U> struct GTypeOf { using type = cv::GOpaque<U>;};
// FIXME: This is not quite correct since IStreamSource may produce not only Mat but also Scalar
@@ -62,8 +62,8 @@ public:
const cv::UMat& inMat(int input);
cv::UMat& outMatR(int output); // FIXME: Avoid cv::Mat m = ctx.outMatR()
const cv::gapi::own::Scalar& inVal(int input);
cv::gapi::own::Scalar& outValR(int output); // FIXME: Avoid cv::gapi::own::Scalar s = ctx.outValR()
const cv::Scalar& inVal(int input);
cv::Scalar& outValR(int output); // FIXME: Avoid cv::Scalar s = ctx.outValR()
template<typename T> std::vector<T>& outVecR(int output) // FIXME: the same issue
{
return outVecRef(output).wref<T>();
@@ -110,7 +110,7 @@ template<> struct ocl_get_in<cv::GMat>
};
template<> struct ocl_get_in<cv::GScalar>
{
static cv::Scalar get(GOCLContext &ctx, int idx) { return to_ocv(ctx.inVal(idx)); }
static cv::Scalar get(GOCLContext &ctx, int idx) { return ctx.inVal(idx); }
};
template<typename U> struct ocl_get_in<cv::GArray<U> >
{
@@ -146,24 +146,12 @@ struct tracked_cv_umat{
}
};
struct scalar_wrapper_ocl
{
//FIXME reuse CPU (OpenCV) plugin code
scalar_wrapper_ocl(cv::gapi::own::Scalar& s) : m_s{cv::gapi::own::to_ocv(s)}, m_org_s(s) {};
operator cv::Scalar& () { return m_s; }
void writeBack() const { m_org_s = to_own(m_s); }
cv::Scalar m_s;
cv::gapi::own::Scalar& m_org_s;
};
template<typename... Outputs>
void postprocess_ocl(Outputs&... outs)
{
struct
{
void operator()(tracked_cv_umat* bm) { bm->validate(); }
void operator()(scalar_wrapper_ocl* sw) { sw->writeBack(); }
void operator()(...) { }
} validate;
@@ -183,10 +171,9 @@ template<> struct ocl_get_out<cv::GMat>
};
template<> struct ocl_get_out<cv::GScalar>
{
static scalar_wrapper_ocl get(GOCLContext &ctx, int idx)
static cv::Scalar& get(GOCLContext &ctx, int idx)
{
auto& s = ctx.outValR(idx);
return{ s };
return ctx.outValR(idx);
}
};
template<typename U> struct ocl_get_out<cv::GArray<U> >
@@ -11,9 +11,7 @@
#if !defined(GAPI_STANDALONE)
#include <opencv2/gapi/opencv_includes.hpp>
#include <opencv2/gapi/own/types.hpp>
#include <opencv2/gapi/own/mat.hpp>
#include <opencv2/gapi/own/scalar.hpp>
namespace cv
{
@@ -34,15 +32,6 @@ namespace cv
? cv::gapi::own::Mat{m.rows, m.cols, m.type(), m.data, m.step}
: cv::gapi::own::Mat{to_own<int>(m.size), m.type(), m.data};
};
inline cv::gapi::own::Scalar to_own(const cv::Scalar& s) { return {s[0], s[1], s[2], s[3]}; };
inline cv::gapi::own::Size to_own (const Size& s) { return {s.width, s.height}; };
inline cv::gapi::own::Rect to_own (const Rect& r) { return {r.x, r.y, r.width, r.height}; };
namespace gapi
{
namespace own
@@ -53,13 +42,6 @@ namespace own
: cv::Mat{m.dims, m.type(), m.data};
}
cv::Mat to_ocv(Mat&&) = delete;
inline cv::Scalar to_ocv(const Scalar& s) { return {s[0], s[1], s[2], s[3]}; };
inline cv::Size to_ocv (const Size& s) { return cv::Size(s.width, s.height); };
inline cv::Rect to_ocv (const Rect& r) { return cv::Rect(r.x, r.y, r.width, r.height); };
} // namespace own
} // namespace gapi
} // namespace cv
@@ -9,6 +9,8 @@
#define OPENCV_GAPI_CV_DEFS_HPP
#if defined(GAPI_STANDALONE)
#include <opencv2/gapi/own/types.hpp> // cv::gapi::own::Rect/Size/Point
#include <opencv2/gapi/own/scalar.hpp> // cv::gapi::own::Scalar
// Simulate OpenCV definitions taken from various
// OpenCV interface headers if G-API is built in a
@@ -137,6 +139,11 @@ enum InterpolationFlags{
INTER_LINEAR_EXACT = 5,
INTER_MAX = 7,
};
// replacement of cv's structures:
using Rect = gapi::own::Rect;
using Size = gapi::own::Size;
using Point = gapi::own::Point;
using Scalar = gapi::own::Scalar;
} // namespace cv
static inline int cvFloor( double value )
@@ -17,7 +17,6 @@
#include <opencv2/gapi/opencv_includes.hpp>
#include <opencv2/gapi/util/variant.hpp>
#include <opencv2/gapi/own/exports.hpp>
#include <opencv2/gapi/own/scalar.hpp>
/** \defgroup gapi_draw G-API Drawing and composition functionality
+13 -22
View File
@@ -152,14 +152,11 @@ void bindInArg(Mag& mag, const RcDesc &rc, const GRunArg &arg, bool is_umat)
case GShape::GSCALAR:
{
auto& mag_scalar = mag.template slot<cv::gapi::own::Scalar>()[rc.id];
auto& mag_scalar = mag.template slot<cv::Scalar>()[rc.id];
switch (arg.index())
{
case GRunArg::index_of<cv::gapi::own::Scalar>() : mag_scalar = util::get<cv::gapi::own::Scalar>(arg); break;
#if !defined(GAPI_STANDALONE)
case GRunArg::index_of<cv::Scalar>() : mag_scalar = to_own(util::get<cv::Scalar>(arg)); break;
#endif // !defined(GAPI_STANDALONE)
default: util::throw_error(std::logic_error("content type of the runtime argument does not match to resource description ?"));
case GRunArg::index_of<cv::Scalar>() : mag_scalar = util::get<cv::Scalar>(arg); break;
default: util::throw_error(std::logic_error("content type of the runtime argument does not match to resource description ?"));
}
break;
}
@@ -222,14 +219,11 @@ void bindOutArg(Mag& mag, const RcDesc &rc, const GRunArgP &arg, bool is_umat)
case GShape::GSCALAR:
{
auto& mag_scalar = mag.template slot<cv::gapi::own::Scalar>()[rc.id];
auto& mag_scalar = mag.template slot<cv::Scalar>()[rc.id];
switch (arg.index())
{
case GRunArgP::index_of<cv::gapi::own::Scalar*>() : mag_scalar = *util::get<cv::gapi::own::Scalar*>(arg); break;
#if !defined(GAPI_STANDALONE)
case GRunArgP::index_of<cv::Scalar*>() : mag_scalar = to_own(*util::get<cv::Scalar*>(arg)); break;
#endif // !defined(GAPI_STANDALONE)
default: util::throw_error(std::logic_error("content type of the runtime argument does not match to resource description ?"));
case GRunArgP::index_of<cv::Scalar*>() : mag_scalar = *util::get<cv::Scalar*>(arg); break;
default: util::throw_error(std::logic_error("content type of the runtime argument does not match to resource description ?"));
}
break;
}
@@ -265,7 +259,7 @@ void resetInternalData(Mag& mag, const Data &d)
break;
case GShape::GSCALAR:
mag.template slot<cv::gapi::own::Scalar>()[d.rc] = cv::gapi::own::Scalar();
mag.template slot<cv::Scalar>()[d.rc] = cv::Scalar();
break;
case GShape::GMAT:
@@ -284,7 +278,7 @@ cv::GRunArg getArg(const Mag& mag, const RcDesc &ref)
switch (ref.shape)
{
case GShape::GMAT: return GRunArg(mag.template slot<cv::gapi::own::Mat>().at(ref.id));
case GShape::GSCALAR: return GRunArg(mag.template slot<cv::gapi::own::Scalar>().at(ref.id));
case GShape::GSCALAR: return GRunArg(mag.template slot<cv::Scalar>().at(ref.id));
// Note: .at() is intentional for GArray and GOpaque as objects MUST be already there
// (and constructed by either bindIn/Out or resetInternal)
case GShape::GARRAY: return GRunArg(mag.template slot<cv::detail::VectorRef>().at(ref.id));
@@ -310,7 +304,7 @@ cv::GRunArgP getObjPtr(Mag& mag, const RcDesc &rc, bool is_umat)
}
else
return GRunArgP(&mag.template slot<cv::gapi::own::Mat>()[rc.id]);
case GShape::GSCALAR: return GRunArgP(&mag.template slot<cv::gapi::own::Scalar>()[rc.id]);
case GShape::GSCALAR: return GRunArgP(&mag.template slot<cv::Scalar>()[rc.id]);
// Note: .at() is intentional for GArray and GOpaque as objects MUST be already there
// (and constructor by either bindIn/Out or resetInternal)
case GShape::GARRAY:
@@ -381,11 +375,8 @@ void writeBack(const Mag& mag, const RcDesc &rc, GRunArgP &g_arg, bool is_umat)
{
switch (g_arg.index())
{
case GRunArgP::index_of<cv::gapi::own::Scalar*>() : *util::get<cv::gapi::own::Scalar*>(g_arg) = mag.template slot<cv::gapi::own::Scalar>().at(rc.id); break;
#if !defined(GAPI_STANDALONE)
case GRunArgP::index_of<cv::Scalar*>() : *util::get<cv::Scalar*>(g_arg) = cv::gapi::own::to_ocv(mag.template slot<cv::gapi::own::Scalar>().at(rc.id)); break;
#endif // !defined(GAPI_STANDALONE)
default: util::throw_error(std::logic_error("content type of the runtime argument does not match to resource description ?"));
case GRunArgP::index_of<cv::Scalar*>() : *util::get<cv::Scalar*>(g_arg) = mag.template slot<cv::Scalar>().at(rc.id); break;
default: util::throw_error(std::logic_error("content type of the runtime argument does not match to resource description ?"));
}
break;
}
@@ -404,7 +395,7 @@ void createMat(const cv::GMatDesc &desc, cv::gapi::own::Mat& mat)
if (desc.dims.empty())
{
const auto type = desc.planar ? desc.depth : CV_MAKETYPE(desc.depth, desc.chan);
const auto size = desc.planar ? cv::gapi::own::Size{desc.size.width, desc.size.height*desc.chan}
const auto size = desc.planar ? cv::Size{desc.size.width, desc.size.height*desc.chan}
: desc.size;
mat.create(size, type);
}
@@ -423,7 +414,7 @@ void createMat(const cv::GMatDesc &desc, cv::Mat& mat)
{
const auto type = desc.planar ? desc.depth : CV_MAKETYPE(desc.depth, desc.chan);
const auto size = desc.planar ? cv::Size{desc.size.width, desc.size.height*desc.chan}
: cv::gapi::own::to_ocv(desc.size);
: desc.size;
mat.create(size, type);
}
else
-1
View File
@@ -10,7 +10,6 @@
#include <ade/util/iota_range.hpp>
#include <ade/util/algorithm.hpp>
#include <opencv2/gapi/opencv_includes.hpp>
#include <opencv2/gapi/own/mat.hpp> //gapi::own::Mat
#include <opencv2/gapi/gmat.hpp>
+8 -13
View File
@@ -74,7 +74,7 @@ cv::GRunArg cv::value_of(const cv::GOrigin &origin)
{
switch (origin.shape)
{
case GShape::GSCALAR: return GRunArg(util::get<cv::gapi::own::Scalar>(origin.value));
case GShape::GSCALAR: return GRunArg(util::get<cv::Scalar>(origin.value));
default: util::throw_error(std::logic_error("Unsupported shape for constant"));
}
}
@@ -102,15 +102,13 @@ cv::GMetaArg cv::descr_of(const cv::GRunArg &arg)
case GRunArg::index_of<cv::Mat>():
return cv::GMetaArg(descr_of(util::get<cv::Mat>(arg)));
case GRunArg::index_of<cv::Scalar>():
return cv::GMetaArg(descr_of(util::get<cv::Scalar>(arg)));
#endif // !defined(GAPI_STANDALONE)
case GRunArg::index_of<cv::gapi::own::Mat>():
return cv::GMetaArg(descr_of(util::get<cv::gapi::own::Mat>(arg)));
case GRunArg::index_of<cv::gapi::own::Scalar>():
return cv::GMetaArg(descr_of(util::get<cv::gapi::own::Scalar>(arg)));
case GRunArg::index_of<cv::Scalar>():
return cv::GMetaArg(descr_of(util::get<cv::Scalar>(arg)));
case GRunArg::index_of<cv::detail::VectorRef>():
return cv::GMetaArg(util::get<cv::detail::VectorRef>(arg).descr_of());
@@ -139,12 +137,11 @@ cv::GMetaArg cv::descr_of(const cv::GRunArgP &argp)
#if !defined(GAPI_STANDALONE)
case GRunArgP::index_of<cv::Mat*>(): return GMetaArg(descr_of(*util::get<cv::Mat*>(argp)));
case GRunArgP::index_of<cv::UMat*>(): return GMetaArg(descr_of(*util::get<cv::UMat*>(argp)));
case GRunArgP::index_of<cv::Scalar*>(): return GMetaArg(descr_of(*util::get<cv::Scalar*>(argp)));
#endif // !defined(GAPI_STANDALONE)
case GRunArgP::index_of<cv::gapi::own::Mat*>(): return GMetaArg(descr_of(*util::get<cv::gapi::own::Mat*>(argp)));
case GRunArgP::index_of<cv::gapi::own::Scalar*>(): return GMetaArg(descr_of(*util::get<cv::gapi::own::Scalar*>(argp)));
case GRunArgP::index_of<cv::detail::VectorRef>(): return GMetaArg(util::get<cv::detail::VectorRef>(argp).descr_of());
case GRunArgP::index_of<cv::detail::OpaqueRef>(): return GMetaArg(util::get<cv::detail::OpaqueRef>(argp).descr_of());
case GRunArgP::index_of<cv::Scalar*>(): return GMetaArg(descr_of(*util::get<cv::Scalar*>(argp)));
case GRunArgP::index_of<cv::detail::VectorRef>(): return GMetaArg(util::get<cv::detail::VectorRef>(argp).descr_of());
case GRunArgP::index_of<cv::detail::OpaqueRef>(): return GMetaArg(util::get<cv::detail::OpaqueRef>(argp).descr_of());
default: util::throw_error(std::logic_error("Unsupported GRunArgP type"));
}
}
@@ -157,11 +154,10 @@ bool cv::can_describe(const GMetaArg& meta, const GRunArgP& argp)
case GRunArgP::index_of<cv::Mat*>(): return util::holds_alternative<GMatDesc>(meta) &&
util::get<GMatDesc>(meta).canDescribe(*util::get<cv::Mat*>(argp));
case GRunArgP::index_of<cv::UMat*>(): return meta == GMetaArg(descr_of(*util::get<cv::UMat*>(argp)));
case GRunArgP::index_of<cv::Scalar*>(): return meta == GMetaArg(descr_of(*util::get<cv::Scalar*>(argp)));
#endif // !defined(GAPI_STANDALONE)
case GRunArgP::index_of<cv::gapi::own::Mat*>(): return util::holds_alternative<GMatDesc>(meta) &&
util::get<GMatDesc>(meta).canDescribe(*util::get<cv::gapi::own::Mat*>(argp));
case GRunArgP::index_of<cv::gapi::own::Scalar*>(): return meta == GMetaArg(descr_of(*util::get<cv::gapi::own::Scalar*>(argp)));
case GRunArgP::index_of<cv::Scalar*>(): return meta == GMetaArg(descr_of(*util::get<cv::Scalar*>(argp)));
case GRunArgP::index_of<cv::detail::VectorRef>(): return meta == GMetaArg(util::get<cv::detail::VectorRef>(argp).descr_of());
case GRunArgP::index_of<cv::detail::OpaqueRef>(): return meta == GMetaArg(util::get<cv::detail::OpaqueRef>(argp).descr_of());
default: util::throw_error(std::logic_error("Unsupported GRunArgP type"));
@@ -176,11 +172,10 @@ bool cv::can_describe(const GMetaArg& meta, const GRunArg& arg)
case GRunArg::index_of<cv::Mat>(): return util::holds_alternative<GMatDesc>(meta) &&
util::get<GMatDesc>(meta).canDescribe(util::get<cv::Mat>(arg));
case GRunArg::index_of<cv::UMat>(): return meta == cv::GMetaArg(descr_of(util::get<cv::UMat>(arg)));
case GRunArg::index_of<cv::Scalar>(): return meta == cv::GMetaArg(descr_of(util::get<cv::Scalar>(arg)));
#endif // !defined(GAPI_STANDALONE)
case GRunArg::index_of<cv::gapi::own::Mat>(): return util::holds_alternative<GMatDesc>(meta) &&
util::get<GMatDesc>(meta).canDescribe(util::get<cv::gapi::own::Mat>(arg));
case GRunArg::index_of<cv::gapi::own::Scalar>(): return meta == cv::GMetaArg(descr_of(util::get<cv::gapi::own::Scalar>(arg)));
case GRunArg::index_of<cv::Scalar>(): return meta == cv::GMetaArg(descr_of(util::get<cv::Scalar>(arg)));
case GRunArg::index_of<cv::detail::VectorRef>(): return meta == cv::GMetaArg(util::get<cv::detail::VectorRef>(arg).descr_of());
case GRunArg::index_of<cv::detail::OpaqueRef>(): return meta == cv::GMetaArg(util::get<cv::detail::OpaqueRef>(arg).descr_of());
case GRunArg::index_of<cv::gapi::wip::IStreamSource::Ptr>(): return util::holds_alternative<GMatDesc>(meta); // FIXME(?) may be not the best option
+4 -16
View File
@@ -22,18 +22,18 @@ cv::GScalar::GScalar(const GNode &n, std::size_t out)
{
}
cv::GScalar::GScalar(const cv::gapi::own::Scalar& s)
cv::GScalar::GScalar(const cv::Scalar& s)
: m_priv(new GOrigin(GShape::GSCALAR, cv::gimpl::ConstVal(s)))
{
}
cv::GScalar::GScalar(cv::gapi::own::Scalar&& s)
cv::GScalar::GScalar(cv::Scalar&& s)
: m_priv(new GOrigin(GShape::GSCALAR, cv::gimpl::ConstVal(std::move(s))))
{
}
cv::GScalar::GScalar(double v0)
: m_priv(new GOrigin(GShape::GSCALAR, cv::gimpl::ConstVal(cv::gapi::own::Scalar(v0))))
: m_priv(new GOrigin(GShape::GSCALAR, cv::gimpl::ConstVal(cv::Scalar(v0))))
{
}
@@ -47,23 +47,11 @@ const cv::GOrigin& cv::GScalar::priv() const
return *m_priv;
}
cv::GScalarDesc cv::descr_of(const cv::gapi::own::Scalar &)
cv::GScalarDesc cv::descr_of(const cv::Scalar &)
{
return empty_scalar_desc();
}
#if !defined(GAPI_STANDALONE)
cv::GScalar::GScalar(const cv::Scalar& s)
: m_priv(new GOrigin(GShape::GSCALAR, cv::gimpl::ConstVal(to_own(s))))
{
}
cv::GScalarDesc cv::descr_of(const cv::Scalar& s)
{
return cv::descr_of(to_own(s));
}
#endif // !defined(GAPI_STANDALONE)
namespace cv {
std::ostream& operator<<(std::ostream& os, const cv::GScalarDesc &)
{
+6
View File
@@ -371,6 +371,12 @@ GMat normalize(const GMat& _src, double a, double b,
return core::GNormalize::on(_src, a, b, norm_type, ddepth);
}
GMat warpPerspective(const GMat& src, const Mat& M, const Size& dsize, int flags,
int borderMode, const Scalar& borderValue)
{
return core::GWarpPerspective::on(src, M, dsize, flags, borderMode, borderValue);
}
GMat warpAffine(const GMat& src, const Mat& M, const Size& dsize, int flags,
int borderMode, const Scalar& borderValue)
{
@@ -17,7 +17,6 @@
#include "opencv2/gapi/own/mat.hpp"
#include "opencv2/gapi/util/optional.hpp"
#include "opencv2/gapi/own/scalar.hpp"
#include "compiler/gmodel.hpp"
@@ -46,9 +45,9 @@ namespace magazine {
} // namespace magazine
#if !defined(GAPI_STANDALONE)
using Mag = magazine::Class<cv::gapi::own::Mat, cv::UMat, cv::gapi::own::Scalar, cv::detail::VectorRef, cv::detail::OpaqueRef>;
using Mag = magazine::Class<cv::gapi::own::Mat, cv::UMat, cv::Scalar, cv::detail::VectorRef, cv::detail::OpaqueRef>;
#else
using Mag = magazine::Class<cv::gapi::own::Mat, cv::gapi::own::Scalar, cv::detail::VectorRef, cv::detail::OpaqueRef>;
using Mag = magazine::Class<cv::gapi::own::Mat, cv::Scalar, cv::detail::VectorRef, cv::detail::OpaqueRef>;
#endif
namespace magazine
@@ -129,7 +129,7 @@ cv::GArg cv::gimpl::GCPUExecutable::packArg(const GArg &arg)
switch (ref.shape)
{
case GShape::GMAT: return GArg(m_res.slot<cv::gapi::own::Mat>() [ref.id]);
case GShape::GSCALAR: return GArg(m_res.slot<cv::gapi::own::Scalar>()[ref.id]);
case GShape::GSCALAR: return GArg(m_res.slot<cv::Scalar>()[ref.id]);
// Note: .at() is intentional for GArray and GOpaque as objects MUST be already there
// (and constructed by either bindIn/Out or resetInternal)
case GShape::GARRAY: return GArg(m_res.slot<cv::detail::VectorRef>().at(ref.id));
@@ -558,6 +558,15 @@ GAPI_OCV_KERNEL(GCPUNormalize, cv::gapi::core::GNormalize)
}
};
GAPI_OCV_KERNEL(GCPUWarpPerspective, cv::gapi::core::GWarpPerspective)
{
static void run(const cv::Mat& src, const cv::Mat& M, const cv::Size& dsize,
int flags, int borderMode, const cv::Scalar& borderValue, cv::Mat& out)
{
cv::warpPerspective(src, out, M, dsize, flags, borderMode, borderValue);
}
};
GAPI_OCV_KERNEL(GCPUWarpAffine, cv::gapi::core::GWarpAffine)
{
static void run(const cv::Mat& src, const cv::Mat& M, const cv::Size& dsize,
@@ -636,6 +645,7 @@ cv::gapi::GKernelPackage cv::gapi::core::cpu::kernels()
, GCPUConvertTo
, GCPUSqrt
, GCPUNormalize
, GCPUWarpPerspective
, GCPUWarpAffine
>();
return pkg;
@@ -353,7 +353,7 @@ G_TYPED_KERNEL(GYUV2Gray, <cv::GMat(cv::GMat)>, "yuvtogray") {
* U V U V U V U V
*/
return {CV_8U, 1, cv::gapi::own::Size{in.size.width, in.size.height - (in.size.height / 3)}, false};
return {CV_8U, 1, cv::Size{in.size.width, in.size.height - (in.size.height / 3)}, false};
}
};
@@ -367,7 +367,7 @@ GAPI_OCV_KERNEL(GCPUYUV2Gray, GYUV2Gray)
G_TYPED_KERNEL(GConcatYUVPlanes, <cv::GMat(cv::GMat, cv::GMat)>, "concatyuvplanes") {
static cv::GMatDesc outMeta(cv::GMatDesc y, cv::GMatDesc uv) {
return {CV_8U, 1, cv::gapi::own::Size{y.size.width, y.size.height + uv.size.height}, false};
return {CV_8U, 1, cv::Size{y.size.width, y.size.height + uv.size.height}, false};
}
};
+4 -4
View File
@@ -21,14 +21,14 @@ cv::gapi::own::Mat& cv::GCPUContext::outMatR(int output)
return *util::get<cv::gapi::own::Mat*>(m_results.at(output));
}
const cv::gapi::own::Scalar& cv::GCPUContext::inVal(int input)
const cv::Scalar& cv::GCPUContext::inVal(int input)
{
return inArg<cv::gapi::own::Scalar>(input);
return inArg<cv::Scalar>(input);
}
cv::gapi::own::Scalar& cv::GCPUContext::outValR(int output)
cv::Scalar& cv::GCPUContext::outValR(int output)
{
return *util::get<cv::gapi::own::Scalar*>(m_results.at(output));
return *util::get<cv::Scalar*>(m_results.at(output));
}
cv::detail::VectorRef& cv::GCPUContext::outVecRef(int output)
@@ -554,8 +554,8 @@ void cv::gimpl::FluidAgent::debug(std::ostream &os)
// GCPUExcecutable implementation //////////////////////////////////////////////
void cv::gimpl::GFluidExecutable::initBufferRois(std::vector<int>& readStarts,
std::vector<cv::gapi::own::Rect>& rois,
const std::vector<cv::gapi::own::Rect>& out_rois)
std::vector<cv::Rect>& rois,
const std::vector<cv::Rect>& out_rois)
{
GConstFluidModel fg(m_g);
auto proto = m_gm.metadata().get<Protocol>();
@@ -592,9 +592,9 @@ void cv::gimpl::GFluidExecutable::initBufferRois(std::vector<int>& readStarts,
readStarts[id] = 0;
const auto& out_roi = out_rois[idx];
if (out_roi == gapi::own::Rect{})
if (out_roi == cv::Rect{})
{
rois[id] = gapi::own::Rect{ 0, 0, desc.size.width, desc.size.height };
rois[id] = cv::Rect{ 0, 0, desc.size.width, desc.size.height };
}
else
{
@@ -639,14 +639,14 @@ void cv::gimpl::GFluidExecutable::initBufferRois(std::vector<int>& readStarts,
const auto& in_meta = util::get<GMatDesc>(in_data.meta);
const auto& fd = fg.metadata(in_node).get<FluidData>();
auto adjFilterRoi = [](cv::gapi::own::Rect produced, int b, int max_height) {
auto adjFilterRoi = [](cv::Rect produced, int b, int max_height) {
// Extend with border roi which should be produced, crop to logical image size
cv::gapi::own::Rect roi = {produced.x, produced.y - b, produced.width, produced.height + 2*b};
cv::gapi::own::Rect fullImg{ 0, 0, produced.width, max_height };
cv::Rect roi = {produced.x, produced.y - b, produced.width, produced.height + 2*b};
cv::Rect fullImg{ 0, 0, produced.width, max_height };
return roi & fullImg;
};
auto adjResizeRoi = [](cv::gapi::own::Rect produced, cv::gapi::own::Size inSz, cv::gapi::own::Size outSz) {
auto adjResizeRoi = [](cv::Rect produced, cv::Size inSz, cv::Size outSz) {
auto map = [](int outCoord, int producedSz, int inSize, int outSize) {
double ratio = (double)inSize / outSize;
int w0 = 0, w1 = 0;
@@ -671,30 +671,30 @@ void cv::gimpl::GFluidExecutable::initBufferRois(std::vector<int>& readStarts,
auto x0 = mapX.first;
auto x1 = mapX.second;
cv::gapi::own::Rect roi = {x0, y0, x1 - x0, y1 - y0};
cv::Rect roi = {x0, y0, x1 - x0, y1 - y0};
return roi;
};
auto adj420Roi = [&](cv::gapi::own::Rect produced, std::size_t port) {
auto adj420Roi = [&](cv::Rect produced, std::size_t port) {
GAPI_Assert(produced.x % 2 == 0);
GAPI_Assert(produced.y % 2 == 0);
GAPI_Assert(produced.width % 2 == 0);
GAPI_Assert(produced.height % 2 == 0);
cv::gapi::own::Rect roi;
cv::Rect roi;
switch (port) {
case 0: roi = produced; break;
case 1:
case 2: roi = cv::gapi::own::Rect{ produced.x/2, produced.y/2, produced.width/2, produced.height/2 }; break;
case 2: roi = cv::Rect{ produced.x/2, produced.y/2, produced.width/2, produced.height/2 }; break;
default: GAPI_Assert(false);
}
return roi;
};
cv::gapi::own::Rect produced = rois[m_id_map.at(data.rc)];
cv::Rect produced = rois[m_id_map.at(data.rc)];
// Apply resize-specific roi transformations
cv::gapi::own::Rect resized;
cv::Rect resized;
switch (fg.metadata(oh).get<FluidUnit>().k.m_kind)
{
case GFluidKernel::Kind::Filter: resized = produced; break;
@@ -727,7 +727,7 @@ void cv::gimpl::GFluidExecutable::initBufferRois(std::vector<int>& readStarts,
auto roi = adjFilterRoi(resized, fd.border_size, in_meta.size.height);
auto in_id = m_id_map.at(in_data.rc);
if (rois[in_id] == cv::gapi::own::Rect{})
if (rois[in_id] == cv::Rect{})
{
readStarts[in_id] = readStart;
rois[in_id] = roi;
@@ -828,7 +828,7 @@ cv::gimpl::FluidGraphInputData cv::gimpl::fluidExtractInputDataFromGraph(const a
cv::gimpl::GFluidExecutable::GFluidExecutable(const ade::Graph &g,
const cv::gimpl::FluidGraphInputData &traverse_res,
const std::vector<cv::gapi::own::Rect> &outputRois)
const std::vector<cv::Rect> &outputRois)
: m_g(g), m_gm(m_g),
m_num_int_buffers (traverse_res.m_mat_count),
m_scratch_users (traverse_res.m_scratch_users),
@@ -1146,13 +1146,13 @@ namespace
}
}
void cv::gimpl::GFluidExecutable::makeReshape(const std::vector<gapi::own::Rect> &out_rois)
void cv::gimpl::GFluidExecutable::makeReshape(const std::vector<cv::Rect> &out_rois)
{
GConstFluidModel fg(m_g);
// Calculate rois for each fluid buffer
std::vector<int> readStarts(m_num_int_buffers);
std::vector<cv::gapi::own::Rect> rois(m_num_int_buffers);
std::vector<cv::Rect> rois(m_num_int_buffers);
initBufferRois(readStarts, rois, out_rois);
// NB: Allocate ALL buffer object at once, and avoid any further reallocations
@@ -1248,7 +1248,7 @@ void cv::gimpl::GFluidExecutable::bindInArg(const cv::gimpl::RcDesc &rc, const G
switch (rc.shape)
{
case GShape::GMAT: m_buffers[m_id_map.at(rc.id)].priv().bindTo(util::get<cv::gapi::own::Mat>(arg), true); break;
case GShape::GSCALAR: m_res.slot<cv::gapi::own::Scalar>()[rc.id] = util::get<cv::gapi::own::Scalar>(arg); break;
case GShape::GSCALAR: m_res.slot<cv::Scalar>()[rc.id] = util::get<cv::Scalar>(arg); break;
case GShape::GARRAY: m_res.slot<cv::detail::VectorRef>()[rc.id] = util::get<cv::detail::VectorRef>(arg); break;
case GShape::GOPAQUE: m_res.slot<cv::detail::OpaqueRef>()[rc.id] = util::get<cv::detail::OpaqueRef>(arg); break;
}
@@ -1301,7 +1301,7 @@ void cv::gimpl::GFluidExecutable::packArg(cv::GArg &in_arg, const cv::GArg &op_a
const cv::gimpl::RcDesc &ref = op_arg.get<cv::gimpl::RcDesc>();
if (ref.shape == GShape::GSCALAR)
{
in_arg = GArg(m_res.slot<cv::gapi::own::Scalar>()[ref.id]);
in_arg = GArg(m_res.slot<cv::Scalar>()[ref.id]);
}
else if (ref.shape == GShape::GARRAY)
{
@@ -129,7 +129,7 @@ class GFluidExecutable final: public GIslandExecutable
std::vector<FluidAgent*> m_script;
using Magazine = detail::magazine<cv::gapi::own::Scalar, cv::detail::VectorRef, cv::detail::OpaqueRef>;
using Magazine = detail::magazine<cv::Scalar, cv::detail::VectorRef, cv::detail::OpaqueRef>;
Magazine m_res;
std::size_t m_num_int_buffers; // internal buffers counter (m_buffers - num_scratch)
@@ -142,8 +142,8 @@ class GFluidExecutable final: public GIslandExecutable
void bindOutArg(const RcDesc &rc, const GRunArgP &arg);
void packArg (GArg &in_arg, const GArg &op_arg);
void initBufferRois(std::vector<int>& readStarts, std::vector<cv::gapi::own::Rect>& rois, const std::vector<gapi::own::Rect> &out_rois);
void makeReshape(const std::vector<cv::gapi::own::Rect>& out_rois);
void initBufferRois(std::vector<int>& readStarts, std::vector<cv::Rect>& rois, const std::vector<cv::Rect> &out_rois);
void makeReshape(const std::vector<cv::Rect>& out_rois);
std::size_t total_buffers_size() const;
public:
@@ -159,7 +159,7 @@ public:
GFluidExecutable(const ade::Graph &g,
const FluidGraphInputData &graph_data,
const std::vector<cv::gapi::own::Rect> &outputRois);
const std::vector<cv::Rect> &outputRois);
};
@@ -9,9 +9,6 @@
#include <iomanip> // hex, dec (debug)
#include <opencv2/gapi/own/convert.hpp>
#include <opencv2/gapi/own/types.hpp>
#include <opencv2/gapi/fluid/gfluidbuffer.hpp>
#include "backends/fluid/gfluidbuffer_priv.hpp"
#include <opencv2/gapi/opencv_includes.hpp>
@@ -64,7 +61,7 @@ void fillBorderReflectRow(uint8_t* row, int length, int chan, int borderSize)
}
template<typename T>
void fillConstBorderRow(uint8_t* row, int length, int chan, int borderSize, cv::gapi::own::Scalar borderValue)
void fillConstBorderRow(uint8_t* row, int length, int chan, int borderSize, cv::Scalar borderValue)
{
GAPI_DbgAssert(chan > 0 && chan <= 4);
@@ -81,7 +78,7 @@ void fillConstBorderRow(uint8_t* row, int length, int chan, int borderSize, cv::
}
// Fills const border pixels in the whole mat
void fillBorderConstant(int borderSize, cv::gapi::own::Scalar borderValue, cv::gapi::own::Mat& mat)
void fillBorderConstant(int borderSize, cv::Scalar borderValue, cv::gapi::own::Mat& mat)
{
// cv::Scalar can contain maximum 4 chan
GAPI_Assert(mat.channels() > 0 && mat.channels() <= 4);
@@ -169,7 +166,7 @@ const uint8_t* fluid::BorderHandlerT<BorderType>::inLineB(int log_idx, const Buf
return data.ptr(idx);
}
fluid::BorderHandlerT<cv::BORDER_CONSTANT>::BorderHandlerT(int border_size, cv::gapi::own::Scalar border_value)
fluid::BorderHandlerT<cv::BORDER_CONSTANT>::BorderHandlerT(int border_size, cv::Scalar border_value)
: BorderHandler(border_size), m_border_value(border_value)
{ /* nothing */ }
@@ -181,7 +178,9 @@ const uint8_t* fluid::BorderHandlerT<cv::BORDER_CONSTANT>::inLineB(int /*log_idx
void fluid::BorderHandlerT<cv::BORDER_CONSTANT>::fillCompileTimeBorder(BufferStorageWithBorder& data)
{
m_const_border.create(1, data.cols(), data.data().type());
m_const_border = m_border_value;
// FIXME: remove this crutch in deowned Mat
m_const_border = {m_border_value[0], m_border_value[1],
m_border_value[2], m_border_value[3]};
cv::gapi::fillBorderConstant(m_border_size, m_border_value, data.data());
}
@@ -269,8 +268,8 @@ const uint8_t* fluid::BufferStorageWithBorder::inLineB(int log_idx, int desc_hei
static void copyWithoutBorder(const cv::gapi::own::Mat& src, int src_border_size, cv::gapi::own::Mat& dst, int dst_border_size, int startSrcLine, int startDstLine, int lpi)
{
auto subSrc = src(cv::gapi::own::Rect{src_border_size, startSrcLine, src.cols - 2*src_border_size, lpi});
auto subDst = dst(cv::gapi::own::Rect{dst_border_size, startDstLine, dst.cols - 2*dst_border_size, lpi});
auto subSrc = src(cv::Rect{src_border_size, startSrcLine, src.cols - 2*src_border_size, lpi});
auto subDst = dst(cv::Rect{dst_border_size, startDstLine, dst.cols - 2*dst_border_size, lpi});
subSrc.copyTo(subDst);
}
@@ -363,8 +362,8 @@ std::unique_ptr<fluid::BufferStorage> createStorage(int capacity, int desc_width
#endif
}
std::unique_ptr<BufferStorage> createStorage(const cv::gapi::own::Mat& data, cv::gapi::own::Rect roi);
std::unique_ptr<BufferStorage> createStorage(const cv::gapi::own::Mat& data, cv::gapi::own::Rect roi)
std::unique_ptr<BufferStorage> createStorage(const cv::gapi::own::Mat& data, cv::Rect roi);
std::unique_ptr<BufferStorage> createStorage(const cv::gapi::own::Mat& data, cv::Rect roi)
{
std::unique_ptr<BufferStorageWithoutBorder> storage(new BufferStorageWithoutBorder);
storage->attach(data, roi);
@@ -502,7 +501,7 @@ void fluid::View::Priv::initCache(int lineConsumption)
// Fluid Buffer implementation /////////////////////////////////////////////////
fluid::Buffer::Priv::Priv(int read_start, cv::gapi::own::Rect roi)
fluid::Buffer::Priv::Priv(int read_start, cv::Rect roi)
: m_readStart(read_start)
, m_roi(roi)
{}
@@ -510,12 +509,12 @@ fluid::Buffer::Priv::Priv(int read_start, cv::gapi::own::Rect roi)
void fluid::Buffer::Priv::init(const cv::GMatDesc &desc,
int writer_lpi,
int readStartPos,
cv::gapi::own::Rect roi)
cv::Rect roi)
{
m_writer_lpi = writer_lpi;
m_desc = desc;
m_readStart = readStartPos;
m_roi = roi == own::Rect{} ? own::Rect{ 0, 0, desc.size.width, desc.size.height }
m_roi = roi == cv::Rect{} ? cv::Rect{ 0, 0, desc.size.width, desc.size.height }
: roi;
m_cache.m_linePtrs.resize(writer_lpi);
m_cache.m_desc = desc;
@@ -650,7 +649,7 @@ fluid::Buffer::Buffer(const cv::GMatDesc &desc)
{
int lineConsumption = 1;
int border = 0, skew = 0, wlpi = 1, readStart = 0;
cv::gapi::own::Rect roi = {0, 0, desc.size.width, desc.size.height};
cv::Rect roi = {0, 0, desc.size.width, desc.size.height};
m_priv->init(desc, wlpi, readStart, roi);
m_priv->allocate({}, border, lineConsumption, skew);
}
@@ -665,7 +664,7 @@ fluid::Buffer::Buffer(const cv::GMatDesc &desc,
, m_cache(&m_priv->cache())
{
int readStart = 0;
cv::gapi::own::Rect roi = {0, 0, desc.size.width, desc.size.height};
cv::Rect roi = {0, 0, desc.size.width, desc.size.height};
m_priv->init(desc, wlpi, readStart, roi);
m_priv->allocate(border, border_size, max_line_consumption, skew);
}
@@ -675,7 +674,7 @@ fluid::Buffer::Buffer(const cv::gapi::own::Mat &data, bool is_input)
, m_cache(&m_priv->cache())
{
int wlpi = 1, readStart = 0;
cv::gapi::own::Rect roi{0, 0, data.cols, data.rows};
cv::Rect roi{0, 0, data.cols, data.rows};
m_priv->init(descr_of(data), wlpi, readStart, roi);
m_priv->bindTo(data, is_input);
}
@@ -52,11 +52,11 @@ public:
template<>
class BorderHandlerT<cv::BORDER_CONSTANT> : public BorderHandler
{
cv::gapi::own::Scalar m_border_value;
cv::Scalar m_border_value;
cv::gapi::own::Mat m_const_border;
public:
BorderHandlerT(int border_size, cv::gapi::own::Scalar border_value);
BorderHandlerT(int border_size, cv::Scalar border_value);
virtual const uint8_t* inLineB(int log_idx, const BufferStorageWithBorder &data, int desc_height) const override;
virtual void fillCompileTimeBorder(BufferStorageWithBorder &) override;
virtual std::size_t size() const override;
@@ -101,23 +101,23 @@ public:
class BufferStorageWithoutBorder final : public BufferStorage
{
bool m_is_virtual = true;
cv::gapi::own::Rect m_roi;
cv::Rect m_roi;
public:
virtual void copyTo(BufferStorageWithBorder &dst, int startLine, int nLines) const override;
inline virtual const uint8_t* ptr(int idx) const override
{
GAPI_DbgAssert((m_is_virtual && m_roi == cv::gapi::own::Rect{}) || (!m_is_virtual && m_roi != cv::gapi::own::Rect{}));
GAPI_DbgAssert((m_is_virtual && m_roi == cv::Rect{}) || (!m_is_virtual && m_roi != cv::Rect{}));
return m_data.ptr(physIdx(idx), 0);
}
inline virtual uint8_t* ptr(int idx) override
{
GAPI_DbgAssert((m_is_virtual && m_roi == cv::gapi::own::Rect{}) || (!m_is_virtual && m_roi != cv::gapi::own::Rect{}));
GAPI_DbgAssert((m_is_virtual && m_roi == cv::Rect{}) || (!m_is_virtual && m_roi != cv::Rect{}));
return m_data.ptr(physIdx(idx), 0);
}
inline void attach(const cv::gapi::own::Mat& _data, cv::gapi::own::Rect _roi)
inline void attach(const cv::gapi::own::Mat& _data, cv::Rect _roi)
{
m_data = _data(_roi);
m_roi = _roi;
@@ -246,13 +246,13 @@ class GAPI_EXPORTS Buffer::Priv
// Coordinate starting from which this buffer is assumed
// to be read (with border not being taken into account)
int m_readStart;
cv::gapi::own::Rect m_roi;
cv::Rect m_roi;
friend void debugBufferPriv(const Buffer& p, std::ostream &os);
public:
Priv() = default;
Priv(int read_start, cv::gapi::own::Rect roi);
Priv(int read_start, cv::Rect roi);
inline const BufferStorage& storage() const { return *m_storage.get(); }
@@ -260,7 +260,7 @@ public:
void init(const cv::GMatDesc &desc,
int writer_lpi,
int readStart,
cv::gapi::own::Rect roi);
cv::Rect roi);
void allocate(BorderOpt border, int border_size, int line_consumption, int skew);
void bindTo(const cv::gapi::own::Mat &data, bool is_input);
@@ -2040,7 +2040,7 @@ GAPI_FLUID_KERNEL(GFluidResize, cv::gapi::core::GResize, true)
cv::GMatDesc desc;
desc.chan = 1;
desc.depth = CV_8UC1;
desc.size = to_own(scratch_size);
desc.size = scratch_size;
cv::gapi::fluid::Buffer buffer(desc);
scratch = std::move(buffer);
@@ -15,8 +15,6 @@
#include <opencv2/gapi/core.hpp>
#include <opencv2/gapi/imgproc.hpp>
#include <opencv2/gapi/own/types.hpp>
#include <opencv2/gapi/fluid/gfluidbuffer.hpp>
#include <opencv2/gapi/fluid/gfluidkernel.hpp>
#include <opencv2/gapi/fluid/imgproc.hpp>
@@ -451,7 +449,7 @@ GAPI_FLUID_KERNEL(GFluidBlur, cv::gapi::imgproc::GBlur, true)
int buflen = width * chan * Window; // work buffers
cv::gapi::own::Size bufsize(buflen, 1);
cv::Size bufsize(buflen, 1);
GMatDesc bufdesc = {CV_32F, 1, bufsize};
Buffer buffer(bufdesc);
scratch = std::move(buffer);
@@ -526,7 +524,7 @@ GAPI_FLUID_KERNEL(GFluidBoxFilter, cv::gapi::imgproc::GBoxFilter, true)
int buflen = width * chan * Window; // work buffers
cv::gapi::own::Size bufsize(buflen, 1);
cv::Size bufsize(buflen, 1);
GMatDesc bufdesc = {CV_32F, 1, bufsize};
Buffer buffer(bufdesc);
scratch = std::move(buffer);
@@ -748,7 +746,7 @@ GAPI_FLUID_KERNEL(GFluidSepFilter, cv::gapi::imgproc::GSepFilter, true)
int buflen = kxLen + kyLen + // x, y kernels
width * chan * Window; // work buffers
cv::gapi::own::Size bufsize(buflen, 1);
cv::Size bufsize(buflen, 1);
GMatDesc bufdesc = {CV_32F, 1, bufsize};
Buffer buffer(bufdesc);
scratch = std::move(buffer);
@@ -851,7 +849,7 @@ GAPI_FLUID_KERNEL(GFluidGaussBlur, cv::gapi::imgproc::GGaussBlur, true)
int buflen = kxsize + kysize + // x, y kernels
width * chan * ksize.height; // work buffers
cv::gapi::own::Size bufsize(buflen, 1);
cv::Size bufsize(buflen, 1);
GMatDesc bufdesc = {CV_32F, 1, bufsize};
Buffer buffer(bufdesc);
scratch = std::move(buffer);
@@ -1016,7 +1014,7 @@ GAPI_FLUID_KERNEL(GFluidSobel, cv::gapi::imgproc::GSobel, true)
int buflen = ksz + ksz // kernels: kx, ky
+ ksz * width * chan; // working buffers
cv::gapi::own::Size bufsize(buflen, 1);
cv::Size bufsize(buflen, 1);
GMatDesc bufdesc = {CV_32F, 1, bufsize};
Buffer buffer(bufdesc);
scratch = std::move(buffer);
@@ -1171,7 +1169,7 @@ GAPI_FLUID_KERNEL(GFluidSobelXY, cv::gapi::imgproc::GSobelXY, true)
int chan = in.chan;
int buflen = BufHelper::length(ksz, width, chan);
cv::gapi::own::Size bufsize(buflen, 1);
cv::Size bufsize(buflen, 1);
GMatDesc bufdesc = {CV_32F, 1, bufsize};
Buffer buffer(bufdesc);
scratch = std::move(buffer);
@@ -1319,7 +1317,7 @@ GAPI_FLUID_KERNEL(GFluidFilter2D, cv::gapi::imgproc::GFilter2D, true)
int buflen = krows * kcols; // kernel size
cv::gapi::own::Size bufsize(buflen, 1);
cv::Size bufsize(buflen, 1);
GMatDesc bufdesc = {CV_32F, 1, bufsize};
Buffer buffer(bufdesc);
scratch = std::move(buffer);
@@ -1496,7 +1494,7 @@ GAPI_FLUID_KERNEL(GFluidErode, cv::gapi::imgproc::GErode, true)
int k_cols = kernel.cols;
int k_size = k_rows * k_cols;
cv::gapi::own::Size bufsize(k_size + 1, 1);
cv::Size bufsize(k_size + 1, 1);
GMatDesc bufdesc = {CV_8U, 1, bufsize};
Buffer buffer(bufdesc);
scratch = std::move(buffer);
@@ -1525,7 +1523,7 @@ GAPI_FLUID_KERNEL(GFluidErode, cv::gapi::imgproc::GErode, true)
#if 1
// TODO: saturate borderValue to image type in general case (not only maximal border)
GAPI_Assert(borderType == cv::BORDER_CONSTANT && borderValue[0] == DBL_MAX);
return { borderType, cv::gapi::own::Scalar::all(INT_MAX) };
return { borderType, cv::Scalar::all(INT_MAX) };
#else
return { borderType, borderValue };
#endif
@@ -1582,7 +1580,7 @@ GAPI_FLUID_KERNEL(GFluidDilate, cv::gapi::imgproc::GDilate, true)
int k_cols = kernel.cols;
int k_size = k_rows * k_cols;
cv::gapi::own::Size bufsize(k_size + 1, 1);
cv::Size bufsize(k_size + 1, 1);
GMatDesc bufdesc = {CV_8U, 1, bufsize};
Buffer buffer(bufdesc);
scratch = std::move(buffer);
@@ -1611,7 +1609,7 @@ GAPI_FLUID_KERNEL(GFluidDilate, cv::gapi::imgproc::GDilate, true)
#if 1
// TODO: fix borderValue for Dilate in general case (not only minimal border)
GAPI_Assert(borderType == cv::BORDER_CONSTANT && borderValue[0] == DBL_MAX);
return { borderType, cv::gapi::own::Scalar::all(INT_MIN) };
return { borderType, cv::Scalar::all(INT_MIN) };
#else
return { borderType, borderValue };
#endif
@@ -1749,7 +1747,7 @@ GAPI_FLUID_KERNEL(GFluidRGB2HSV, cv::gapi::imgproc::GRGB2HSV, true)
cv::GMatDesc desc;
desc.chan = 1;
desc.depth = CV_32S;
desc.size = cv::gapi::own::Size(512, 1);
desc.size = cv::Size(512, 1);
cv::gapi::fluid::Buffer buffer(desc);
scratch = std::move(buffer);
@@ -1831,7 +1831,7 @@ static void run_sepfilter5x5_char2short(short out[], const uchar *in[], int widt
for (; l <= length - nlanes; l += nlanes)
{
v_uint16 t[kxLen];
v_int16 sum;
v_int16 sum = vx_setzero_s16();
for (int i = 0; i < kxLen; ++i)
{
@@ -1862,7 +1862,7 @@ static void run_sepfilter5x5_char2short(short out[], const uchar *in[], int widt
for (; l <= length - nlanes; l += nlanes)
{
v_int16 s[buffSize];
v_int16 sum;
v_int16 sum = vx_setzero_s16();
for (int i = 0; i < kyLen; ++i)
{
@@ -129,7 +129,7 @@ cv::GArg cv::gimpl::GOCLExecutable::packArg(const GArg &arg)
switch (ref.shape)
{
case GShape::GMAT: return GArg(m_res.slot<cv::UMat>()[ref.id]);
case GShape::GSCALAR: return GArg(m_res.slot<cv::gapi::own::Scalar>()[ref.id]);
case GShape::GSCALAR: return GArg(m_res.slot<cv::Scalar>()[ref.id]);
// Note: .at() is intentional for GArray as object MUST be already there
// (and constructed by either bindIn/Out or resetInternal)
case GShape::GARRAY: return GArg(m_res.slot<cv::detail::VectorRef>().at(ref.id));
+4 -4
View File
@@ -19,14 +19,14 @@ cv::UMat& cv::GOCLContext::outMatR(int output)
return (*(util::get<cv::UMat*>(m_results.at(output))));
}
const cv::gapi::own::Scalar& cv::GOCLContext::inVal(int input)
const cv::Scalar& cv::GOCLContext::inVal(int input)
{
return inArg<cv::gapi::own::Scalar>(input);
return inArg<cv::Scalar>(input);
}
cv::gapi::own::Scalar& cv::GOCLContext::outValR(int output)
cv::Scalar& cv::GOCLContext::outValR(int output)
{
return *util::get<cv::gapi::own::Scalar*>(m_results.at(output));
return *util::get<cv::Scalar*>(m_results.at(output));
}
cv::detail::VectorRef& cv::GOCLContext::outVecRef(int output)
+1 -1
View File
@@ -28,7 +28,7 @@ namespace gimpl
using ConstVal = util::variant
< util::monostate
, cv::gapi::own::Scalar
, cv::Scalar
>;
struct RcDesc
@@ -112,15 +112,12 @@ void sync_data(cv::GRunArgs &results, cv::GRunArgsP &outputs)
case T::index_of<cv::Mat*>():
*cv::util::get<cv::Mat*>(out_obj) = std::move(cv::util::get<cv::Mat>(res_obj));
break;
case T::index_of<cv::Scalar*>():
*cv::util::get<cv::Scalar*>(out_obj) = std::move(cv::util::get<cv::Scalar>(res_obj));
break;
#endif // !GAPI_STANDALONE
case T::index_of<own::Mat*>():
*cv::util::get<own::Mat*>(out_obj) = std::move(cv::util::get<own::Mat>(res_obj));
break;
case T::index_of<own::Scalar*>():
*cv::util::get<own::Scalar*>(out_obj) = std::move(cv::util::get<own::Scalar>(res_obj));
case T::index_of<cv::Scalar*>():
*cv::util::get<cv::Scalar*>(out_obj) = std::move(cv::util::get<cv::Scalar>(res_obj));
break;
case T::index_of<cv::detail::VectorRef>():
cv::util::get<cv::detail::VectorRef>(out_obj).mov(cv::util::get<cv::detail::VectorRef>(res_obj));
@@ -418,7 +415,7 @@ void islandActorThread(std::vector<cv::gimpl::RcDesc> in_rcs, //
isl_input.second = cv::GRunArg{cv::to_own(cv::util::get<cv::Mat>(in_arg))};
break;
case cv::GRunArg::index_of<cv::Scalar>():
isl_input.second = cv::GRunArg{cv::to_own(cv::util::get<cv::Scalar>(in_arg))};
isl_input.second = cv::GRunArg{cv::util::get<cv::Scalar>(in_arg)};
break;
default:
isl_input.second = in_arg;
@@ -443,7 +440,7 @@ void islandActorThread(std::vector<cv::gimpl::RcDesc> in_rcs, //
using SclType = cv::Scalar;
#else
using MatType = cv::gapi::own::Mat;
using SclType = cv::gapi::own::Scalar;
using SclType = cv::Scalar;
#endif // GAPI_STANDALONE
switch (r.shape) {
+7 -2
View File
@@ -142,8 +142,13 @@ struct BackendOutputAllocationTest : TestWithParamBase<>
struct BackendOutputAllocationLargeSizeWithCorrectSubmatrixTest : BackendOutputAllocationTest {};
GAPI_TEST_FIXTURE(ReInitOutTest, initNothing, <cv::Size>, 1, out_sz)
GAPI_TEST_FIXTURE(WarpAffineTest, initMatrixRandU, FIXTURE_API(CompareMats, double , double, int, int, cv::Scalar), 6,
cmpF, angle, scale, flags, border_mode, border_value)
GAPI_TEST_FIXTURE(WarpPerspectiveTest, initMatrixRandU,
FIXTURE_API(CompareMats, double , double, int, int, cv::Scalar),
6, cmpF, angle, scale, flags, border_mode, border_value)
GAPI_TEST_FIXTURE(WarpAffineTest, initMatrixRandU,
FIXTURE_API(CompareMats, double , double, int, int, cv::Scalar),
6, cmpF, angle, scale, flags, border_mode, border_value)
} // opencv_test
#endif //OPENCV_GAPI_CORE_TESTS_HPP
@@ -1266,6 +1266,30 @@ TEST_P(SqrtTest, AccuracyTest)
}
}
TEST_P(WarpPerspectiveTest, AccuracyTest)
{
cv::Point center{in_mat1.size() / 2};
cv::Mat xy = cv::getRotationMatrix2D(center, angle, scale);
cv::Matx13d z (0, 0, 1);
cv::Mat transform_mat;
cv::vconcat(xy, z, transform_mat);
// G-API code //////////////////////////////////////////////////////////////
cv::GMat in;
auto out = cv::gapi::warpPerspective(in, transform_mat, in_mat1.size(), flags, border_mode, border_value);
cv::GComputation c(in, out);
c.apply(in_mat1, out_mat_gapi, getCompileArgs());
// OpenCV code /////////////////////////////////////////////////////////////
cv::warpPerspective(in_mat1, out_mat_ocv, cv::Mat(transform_mat), in_mat1.size(), flags, border_mode, border_value);
// Comparison //////////////////////////////////////////////////////////////
{
EXPECT_TRUE(cmpF(out_mat_gapi, out_mat_ocv));
}
}
TEST_P(WarpAffineTest, AccuracyTest)
{
cv::Point center{in_mat1.size() / 2};
@@ -435,6 +435,19 @@ INSTANTIATE_TEST_CASE_P(ConcatHorVecTestCPU, ConcatHorVecTest,
Values(-1),
Values(CORE_CPU)));
INSTANTIATE_TEST_CASE_P(WarpPerspectiveTestCPU, WarpPerspectiveTest,
Combine(Values(CV_8UC1, CV_8UC3),
Values(cv::Size(1280, 720),
cv::Size(640, 480)),
Values(-1),
Values(CORE_CPU),
Values(AbsExact().to_compare_obj()),
Values(-50.0, 90.0),
Values(0.6),
Values(cv::INTER_LINEAR),
Values(cv::BORDER_CONSTANT),
Values(cv::Scalar())));
INSTANTIATE_TEST_CASE_P(WarpAffineTestCPU, WarpAffineTest,
Combine(Values(CV_8UC1, CV_8UC3),
Values(cv::Size(1280, 720),
+3 -5
View File
@@ -388,11 +388,10 @@ namespace {
switch (arg.index()){
#if !defined(GAPI_STANDALONE)
case GRunArgP::index_of<cv::Mat*>() : result.emplace_back(*util::get<cv::Mat*>(arg)); break;
case GRunArgP::index_of<cv::Scalar*>() : result.emplace_back(*util::get<cv::Scalar*>(arg)); break;
case GRunArgP::index_of<cv::UMat*>() : result.emplace_back(*util::get<cv::UMat*>(arg)); break;
#endif // !defined(GAPI_STANDALONE)
case GRunArgP::index_of<cv::gapi::own::Mat*>() : result.emplace_back(*util::get<cv::gapi::own::Mat*> (arg)); break;
case GRunArgP::index_of<cv::gapi::own::Scalar*>() : result.emplace_back(*util::get<cv::gapi::own::Scalar*>(arg)); break;
case GRunArgP::index_of<cv::Scalar*>() : result.emplace_back(*util::get<cv::Scalar*> (arg)); break;
case GRunArgP::index_of<cv::detail::VectorRef>() : result.emplace_back(util::get<cv::detail::VectorRef> (arg)); break;
default : ;
}
@@ -406,12 +405,11 @@ namespace {
switch (arg.index()){
#if !defined(GAPI_STANDALONE)
case GRunArg::index_of<cv::Mat>() : result.emplace_back(&util::get<cv::Mat>(arg)); break;
case GRunArg::index_of<cv::Scalar>() : result.emplace_back(&util::get<cv::Scalar>(arg)); break;
case GRunArg::index_of<cv::UMat>() : result.emplace_back(&util::get<cv::UMat>(arg)); break;
#endif // !defined(GAPI_STANDALONE)
case GRunArg::index_of<cv::gapi::own::Mat>() : result.emplace_back(&util::get<cv::gapi::own::Mat> (arg)); break;
case GRunArg::index_of<cv::gapi::own::Scalar>() : result.emplace_back(&util::get<cv::gapi::own::Scalar>(arg)); break;
case GRunArg::index_of<cv::detail::VectorRef>() : result.emplace_back(util::get<cv::detail::VectorRef> (arg)); break;
case GRunArg::index_of<cv::Scalar>() : result.emplace_back(&util::get<cv::Scalar> (arg)); break;
case GRunArg::index_of<cv::detail::VectorRef>() : result.emplace_back(util::get<cv::detail::VectorRef> (arg)); break;
default : ;
}
}
@@ -22,7 +22,7 @@ namespace {
cv::GFluidParallelOutputRois asGFluidParallelOutputRois(const std::vector<cv::Rect>& rois){
cv::GFluidParallelOutputRois parallel_rois;
for (auto const& roi : rois) {
parallel_rois.parallel_rois.emplace_back(GFluidOutputRois{{to_own(roi)}});
parallel_rois.parallel_rois.emplace_back(GFluidOutputRois{{roi}});
}
return parallel_rois;
}
+2 -2
View File
@@ -744,7 +744,7 @@ TEST_P(NV12PlusResizeTest, Test)
auto pkg = cv::gapi::combine(fluidTestPackage, cv::gapi::core::fluid::kernels());
c.apply(cv::gin(y_mat, uv_mat), cv::gout(out_mat)
,cv::compile_args(pkg, cv::GFluidOutputRois{{to_own(roi)}}));
,cv::compile_args(pkg, cv::GFluidOutputRois{{roi}}));
cv::Mat rgb_mat;
cv::cvtColor(in_mat, rgb_mat, cv::COLOR_YUV2RGB_NV12);
@@ -823,7 +823,7 @@ TEST_P(Preproc4lpiTest, Test)
fluidResizeTestPackage(interp, in_sz, out_sz, 4));
c.apply(cv::gin(y_mat, uv_mat), cv::gout(out_mat)
,cv::compile_args(pkg, cv::GFluidOutputRois{{to_own(roi)}}));
,cv::compile_args(pkg, cv::GFluidOutputRois{{roi}}));
cv::Mat rgb_mat;
cv::cvtColor(in_mat, rgb_mat, cv::COLOR_YUV2RGB_NV12);
+3 -3
View File
@@ -38,7 +38,7 @@ TEST_P(PartialComputation, Test)
cv::Mat out_mat_ocv = cv::Mat::zeros(sz, CV_8UC1);
// Run G-API
auto cc = c.compile(cv::descr_of(in_mat), cv::compile_args(fluidTestPackage, GFluidOutputRois{{to_own(roi)}}));
auto cc = c.compile(cv::descr_of(in_mat), cv::compile_args(fluidTestPackage, GFluidOutputRois{{roi}}));
cc(cv::gin(in_mat), cv::gout(out_mat_gapi));
// Check with OpenCV
@@ -72,7 +72,7 @@ TEST_P(PartialComputationAddC, Test)
cv::Mat out_mat_ocv = cv::Mat::zeros(sz, CV_8UC1);
// Run G-API
auto cc = c.compile(cv::descr_of(in_mat), cv::compile_args(fluidTestPackage, GFluidOutputRois{{to_own(roi)}}));
auto cc = c.compile(cv::descr_of(in_mat), cv::compile_args(fluidTestPackage, GFluidOutputRois{{roi}}));
cc(cv::gin(in_mat), cv::gout(out_mat_gapi));
// Check with OpenCV
@@ -110,7 +110,7 @@ TEST_P(SequenceOfBlursRoiTest, Test)
Mat out_mat_gapi = Mat::zeros(sz_in, CV_8UC1);
GComputation c(GIn(in), GOut(out));
auto cc = c.compile(descr_of(in_mat), cv::compile_args(fluidTestPackage, GFluidOutputRois{{to_own(roi)}}));
auto cc = c.compile(descr_of(in_mat), cv::compile_args(fluidTestPackage, GFluidOutputRois{{roi}}));
cc(gin(in_mat), gout(out_mat_gapi));
cv::Mat mid_mat_ocv = Mat::zeros(sz_in, CV_8UC1);
+3 -3
View File
@@ -75,7 +75,7 @@ TEST(FluidBuffer, CircularTest)
const cv::Size buffer_size = {8,16};
cv::gapi::fluid::Buffer buffer(cv::GMatDesc{CV_8U,1,buffer_size}, 3, 1, 0, 1,
util::make_optional(cv::gapi::fluid::Border{cv::BORDER_CONSTANT, cv::gapi::own::Scalar(255)}));
util::make_optional(cv::gapi::fluid::Border{cv::BORDER_CONSTANT, cv::Scalar(255)}));
cv::gapi::fluid::View view = buffer.mkView(1, {});
view.priv().reset(3);
view.priv().allocate(3, {});
@@ -754,7 +754,7 @@ TEST_P(NV12RoiTest, Test)
auto rgb = cv::gapi::NV12toRGB(y, uv);
cv::GComputation c(cv::GIn(y, uv), cv::GOut(rgb));
c.apply(cv::gin(y_mat, uv_mat), cv::gout(out_mat), cv::compile_args(fluidTestPackage, cv::GFluidOutputRois{{to_own(roi)}}));
c.apply(cv::gin(y_mat, uv_mat), cv::gout(out_mat), cv::compile_args(fluidTestPackage, cv::GFluidOutputRois{{roi}}));
cv::cvtColor(in_mat, out_mat_ocv, cv::COLOR_YUV2RGB_NV12);
@@ -835,7 +835,7 @@ TEST(Fluid, InvalidROIs)
};
const auto compile_args = [] (cv::Rect roi) {
return cv::compile_args(cv::gapi::core::fluid::kernels(), GFluidOutputRois{{to_own(roi)}});
return cv::compile_args(cv::gapi::core::fluid::kernels(), GFluidOutputRois{{roi}});
};
for (const auto& roi : invalid_rois)
@@ -184,7 +184,7 @@ GAPI_FLUID_KERNEL(FBlur3x3, TBlur3x3, false)
static cv::gapi::fluid::Border getBorder(const cv::GMatDesc &/*src*/, int borderType, cv::Scalar borderValue)
{
return { borderType, to_own(borderValue)};
return { borderType, borderValue};
}
};
@@ -200,7 +200,7 @@ GAPI_FLUID_KERNEL(FBlur5x5, TBlur5x5, false)
static cv::gapi::fluid::Border getBorder(const cv::GMatDesc &/*src*/, int borderType, cv::Scalar borderValue)
{
return { borderType, to_own(borderValue)};
return { borderType, borderValue};
}
};
@@ -217,7 +217,7 @@ GAPI_FLUID_KERNEL(FBlur3x3_2lpi, TBlur3x3_2lpi, false)
static cv::gapi::fluid::Border getBorder(const cv::GMatDesc &/*src*/, int borderType, cv::Scalar borderValue)
{
return { borderType, to_own(borderValue)};
return { borderType, borderValue};
}
};
@@ -234,7 +234,7 @@ GAPI_FLUID_KERNEL(FBlur5x5_2lpi, TBlur5x5_2lpi, false)
static cv::gapi::fluid::Border getBorder(const cv::GMatDesc &/*src*/, int borderType, cv::Scalar borderValue)
{
return { borderType, to_own(borderValue )};
return { borderType, borderValue};
}
};
@@ -261,7 +261,7 @@ GAPI_FLUID_KERNEL(FIdentity, TId, false)
static gapi::fluid::Border getBorder(const cv::GMatDesc &)
{
return { cv::BORDER_REPLICATE, cv::gapi::own::Scalar{} };
return { cv::BORDER_REPLICATE, cv::Scalar{} };
}
};
@@ -308,7 +308,7 @@ GAPI_FLUID_KERNEL(FId7x7, TId7x7, false)
static cv::gapi::fluid::Border getBorder(const cv::GMatDesc&/* src*/)
{
return { cv::BORDER_REPLICATE, cv::gapi::own::Scalar{} };
return { cv::BORDER_REPLICATE, cv::Scalar{} };
}
};
+3 -3
View File
@@ -61,7 +61,7 @@ TEST_F(GCompiledValidateMetaTyped, ValidMeta)
TEST_F(GCompiledValidateMetaTyped, InvalidMeta)
{
auto f = m_cc.compile(cv::GMatDesc{CV_8U,1,cv::gapi::own::Size(64,32)},
auto f = m_cc.compile(cv::GMatDesc{CV_8U,1,cv::Size(64,32)},
cv::empty_scalar_desc());
cv::Scalar sc(33);
@@ -106,7 +106,7 @@ TEST_F(GCompiledValidateMetaUntyped, ValidMeta)
TEST_F(GCompiledValidateMetaUntyped, InvalidMetaValues)
{
auto f = m_ucc.compile(cv::GMatDesc{CV_8U,1,cv::gapi::own::Size(64,32)},
auto f = m_ucc.compile(cv::GMatDesc{CV_8U,1,cv::Size(64,32)},
cv::empty_scalar_desc());
cv::Scalar sc(33);
@@ -131,7 +131,7 @@ TEST_F(GCompiledValidateMetaUntyped, InvalidMetaValues)
TEST_F(GCompiledValidateMetaUntyped, InvalidMetaShape)
{
auto f = m_ucc.compile(cv::GMatDesc{CV_8U,1,cv::gapi::own::Size(64,32)},
auto f = m_ucc.compile(cv::GMatDesc{CV_8U,1,cv::Size(64,32)},
cv::empty_scalar_desc());
cv::Mat in1 = cv::Mat::eye(cv::Size(64,32), CV_8UC1);
@@ -19,13 +19,13 @@ namespace opencv_test
static cv::GMatDesc outMeta(cv::GMatDesc in, cv::Size sz, double fx, double fy, int) {
if (sz.width != 0 && sz.height != 0)
{
return in.withSize(to_own(sz));
return in.withSize(sz);
}
else
{
GAPI_Assert(fx != 0. && fy != 0.);
return in.withSize
(cv::gapi::own::Size(static_cast<int>(std::round(in.size.width * fx)),
(cv::Size(static_cast<int>(std::round(in.size.width * fx)),
static_cast<int>(std::round(in.size.height * fy))));
}
}
-1
View File
@@ -6,7 +6,6 @@
#include "test_precomp.hpp"
#include <opencv2/gapi/cpu/gcpukernel.hpp>
#include "gapi_mock_kernels.hpp"
#include <opencv2/gapi/cpu/gcpukernel.hpp> // cpu::backend
@@ -141,7 +141,7 @@ TEST(GMetaArg, Can_Describe_RunArg)
constexpr int w = 3, h = 3, c = 3;
uchar data[w*h*c];
cv::gapi::own::Mat om(h, w, CV_8UC3, data);
cv::gapi::own::Scalar os;
cv::Scalar os;
std::vector<int> v;
GMetaArgs metas = {GMetaArg(descr_of(m)),
@@ -181,7 +181,7 @@ TEST(GMetaArg, Can_Describe_RunArgP)
constexpr int w = 3, h = 3, c = 3;
uchar data[w*h*c];
cv::gapi::own::Mat om(h, w, CV_8UC3, data);
cv::gapi::own::Scalar os;
cv::Scalar os;
std::vector<int> v;
GMetaArgs metas = {GMetaArg(descr_of(m)),
@@ -166,8 +166,8 @@ TEST(GModelBuilder, Constant_GScalar)
EXPECT_EQ(9u, static_cast<std::size_t>(g.nodes().size())); // 6 data nodes (1 -input, 1 output, 2 constant, 2 temp) and 3 op nodes
EXPECT_EQ(2u, static_cast<std::size_t>(addC_nh->inNodes().size())); // in and 3
EXPECT_EQ(2u, static_cast<std::size_t>(mulC_nh->inNodes().size())); // addC output and c_s
EXPECT_EQ(3, (util::get<cv::gapi::own::Scalar>(gm.metadata(s_3).get<cv::gimpl::ConstValue>().arg))[0]);
EXPECT_EQ(5, (util::get<cv::gapi::own::Scalar>(gm.metadata(s_5).get<cv::gimpl::ConstValue>().arg))[0]);
EXPECT_EQ(3, (util::get<cv::Scalar>(gm.metadata(s_3).get<cv::gimpl::ConstValue>().arg))[0]);
EXPECT_EQ(5, (util::get<cv::Scalar>(gm.metadata(s_5).get<cv::gimpl::ConstValue>().arg))[0]);
}
TEST(GModelBuilder, Check_Multiple_Outputs)
@@ -34,7 +34,7 @@ TEST(IslandFusion, TwoOps_OneIsland)
cv::GComputation cc(in, out);
// Prepare compilation parameters manually
const auto in_meta = cv::GMetaArg(cv::GMatDesc{CV_8U,1,cv::gapi::own::Size(32,32)});
const auto in_meta = cv::GMetaArg(cv::GMatDesc{CV_8U,1,cv::Size(32,32)});
const auto pkg = cv::gapi::kernels<J::Foo>();
// Directly instantiate G-API graph compiler and run partial compilation
@@ -77,7 +77,7 @@ TEST(IslandFusion, TwoOps_TwoIslands)
cv::GComputation cc(in, out);
// Prepare compilation parameters manually
const auto in_meta = cv::GMetaArg(cv::GMatDesc{CV_8U,1,cv::gapi::own::Size(32,32)});
const auto in_meta = cv::GMetaArg(cv::GMatDesc{CV_8U,1,cv::Size(32,32)});
const auto pkg = cv::gapi::kernels<J::Foo, S::Bar>();
// Directly instantiate G-API graph compiler and run partial compilation
@@ -142,8 +142,8 @@ TEST(IslandFusion, ConsumerHasTwoInputs)
cv::GComputation cc(cv::GIn(in[0], in[1]), cv::GOut(out));
// Prepare compilation parameters manually
cv::GMetaArgs in_metas = {GMetaArg(cv::GMatDesc{CV_8U,1,cv::gapi::own::Size(32,32)}),
GMetaArg(cv::GMatDesc{CV_8U,1,cv::gapi::own::Size(32,32)})};
cv::GMetaArgs in_metas = {GMetaArg(cv::GMatDesc{CV_8U,1,cv::Size(32,32)}),
GMetaArg(cv::GMatDesc{CV_8U,1,cv::Size(32,32)})};
const auto pkg = cv::gapi::kernels<J::Foo, J::Bar>();
// Directly instantiate G-API graph compiler and run partial compilation
@@ -211,7 +211,7 @@ TEST(IslandFusion, DataNodeUsedDifferentBackend)
cv::GComputation cc(cv::GIn(in), cv::GOut(out0, out1));
// Prepare compilation parameters manually
const auto in_meta = cv::GMetaArg(cv::GMatDesc{CV_8U,1,cv::gapi::own::Size(32,32)});
const auto in_meta = cv::GMetaArg(cv::GMatDesc{CV_8U,1,cv::Size(32,32)});
const auto pkg = cv::gapi::kernels<J::Foo, S::Baz>();
// Directly instantiate G-API graph compiler and run partial compilation
@@ -272,7 +272,7 @@ TEST(IslandFusion, LoopBetweenDifferentBackends)
cv::GComputation cc(cv::GIn(in), cv::GOut(out1, out0));
// Prepare compilation parameters manually
const auto in_meta = cv::GMetaArg(cv::GMatDesc{CV_8U,1,cv::gapi::own::Size(32,32)});
const auto in_meta = cv::GMetaArg(cv::GMatDesc{CV_8U,1,cv::Size(32,32)});
const auto pkg = cv::gapi::kernels<J::Baz, J::Quux, S::Foo, S::Qux>();
// Directly instantiate G-API graph compiler and run partial compilation
@@ -334,8 +334,8 @@ TEST(IslandsFusion, PartionOverlapUserIsland)
cv::GComputation cc(cv::GIn(in[0], in[1]), cv::GOut(out));
// Prepare compilation parameters manually
cv::GMetaArgs in_metas = {GMetaArg(cv::GMatDesc{CV_8U,1,cv::gapi::own::Size(32,32)}),
GMetaArg(cv::GMatDesc{CV_8U,1,cv::gapi::own::Size(32,32)})};
cv::GMetaArgs in_metas = {GMetaArg(cv::GMatDesc{CV_8U,1,cv::Size(32,32)}),
GMetaArg(cv::GMatDesc{CV_8U,1,cv::Size(32,32)})};
const auto pkg = cv::gapi::kernels<J::Foo, J::Bar>();
// Directly instantiate G-API graph compiler and run partial compilation
@@ -391,8 +391,8 @@ TEST(IslandsFusion, DISABLED_IslandContainsDifferentBackends)
cv::GComputation cc(cv::GIn(in[0], in[1]), cv::GOut(out));
// Prepare compilation parameters manually
cv::GMetaArgs in_metas = {GMetaArg(cv::GMatDesc{CV_8U,1,cv::gapi::own::Size(32,32)}),
GMetaArg(cv::GMatDesc{CV_8U,1,cv::gapi::own::Size(32,32)})};
cv::GMetaArgs in_metas = {GMetaArg(cv::GMatDesc{CV_8U,1,cv::Size(32,32)}),
GMetaArg(cv::GMatDesc{CV_8U,1,cv::Size(32,32)})};
const auto pkg = cv::gapi::kernels<J::Foo, S::Bar>();
// Directly instantiate G-API graph compiler and run partial compilation
@@ -424,7 +424,7 @@ TEST(IslandFusion, WithLoop)
cv::GComputation cc(in, out);
// Prepare compilation parameters manually
const auto in_meta = cv::GMetaArg(cv::GMatDesc{CV_8U,1,cv::gapi::own::Size(32,32)});
const auto in_meta = cv::GMetaArg(cv::GMatDesc{CV_8U,1,cv::Size(32,32)});
const auto pkg = cv::gapi::kernels<J::Foo, J::Baz, J::Qux>();
// Directly instantiate G-API graph compiler and run partial compilation
@@ -216,7 +216,7 @@ TEST(GComputationCompile, ReshapeRois)
int roiH = szOut.height / niter;
cv::Rect roi{x, y, roiW, roiH};
cc.apply(in_mat, out_mat, cv::compile_args(cv::GFluidOutputRois{{to_own(roi)}}));
cc.apply(in_mat, out_mat, cv::compile_args(cv::GFluidOutputRois{{roi}}));
auto comp = cc.priv().m_lastCompiled;
EXPECT_EQ(&first_comp.priv(), &comp.priv());
+5
View File
@@ -45,6 +45,11 @@ if(HAVE_TIFF)
list(APPEND GRFMT_LIBS ${TIFF_LIBRARIES})
endif()
if(HAVE_OPENJPEG)
ocv_include_directories(${OPENJPEG_INCLUDE_DIRS})
list(APPEND GRFMT_LIBS ${OPENJPEG_LIBRARIES})
endif()
if(HAVE_JASPER)
ocv_include_directories(${JASPER_INCLUDE_DIR})
list(APPEND GRFMT_LIBS ${JASPER_LIBRARIES})
@@ -0,0 +1,762 @@
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Copyright (C) 2020, Stefan Brüns <stefan.bruens@rwth-aachen.de>
#include "precomp.hpp"
#ifdef HAVE_OPENJPEG
#include "grfmt_jpeg2000_openjpeg.hpp"
#include "opencv2/core/utils/logger.hpp"
namespace cv {
namespace {
String colorspaceName(COLOR_SPACE colorspace)
{
switch (colorspace)
{
case OPJ_CLRSPC_CMYK:
return "CMYK";
case OPJ_CLRSPC_SRGB:
return "sRGB";
case OPJ_CLRSPC_EYCC:
return "e-YCC";
case OPJ_CLRSPC_GRAY:
return "grayscale";
case OPJ_CLRSPC_SYCC:
return "YUV";
case OPJ_CLRSPC_UNKNOWN:
return "unknown";
case OPJ_CLRSPC_UNSPECIFIED:
return "unspecified";
default:
CV_Assert(!"Invalid colorspace");
}
}
template <class T>
struct ConstItTraits {
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = const T*;
using reference = const T&;
};
template <class T>
struct NonConstItTraits {
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = T*;
using reference = T&;
};
/**
* Iterator over the channel in continuous chunk of the memory e.g. in the one row of a Mat
* No bounds checks are preformed due to keeping this class as simple as possible while
* fulfilling RandomAccessIterator naming requirements.
*
* @tparam Traits holds information about value type and constness of the defined types
*/
template <class Traits>
class ChannelsIterator
{
public:
using difference_type = typename Traits::difference_type;
using value_type = typename Traits::value_type;
using pointer = typename Traits::pointer;
using reference = typename Traits::reference;
using iterator_category = std::random_access_iterator_tag;
ChannelsIterator(pointer ptr, std::size_t channel, std::size_t channels_count)
: ptr_ { ptr + channel }, step_ { channels_count }
{
}
/* Element Access */
reference operator*() const
{
return *ptr_;
}
pointer operator->() const
{
return &(operator*());
}
reference operator[](difference_type n) const
{
return *(*this + n);
}
/* Iterator movement */
ChannelsIterator<Traits>& operator++()
{
ptr_ += step_;
return *this;
}
ChannelsIterator<Traits> operator++(int)
{
ChannelsIterator ret(*this);
++(*this);
return ret;
}
ChannelsIterator<Traits>& operator--()
{
ptr_ -= step_;
return *this;
}
ChannelsIterator<Traits> operator--(int)
{
ChannelsIterator ret(*this);
--(*this);
return ret;
}
ChannelsIterator<Traits>& operator-=(difference_type n)
{
ptr_ -= n * step_;
return *this;
}
ChannelsIterator<Traits>& operator+=(difference_type n)
{
ptr_ += n * step_;
return *this;
}
ChannelsIterator<Traits> operator-(difference_type n) const
{
return ChannelsIterator<Traits>(*this) -= n;
}
ChannelsIterator<Traits> operator+(difference_type n) const
{
return ChannelsIterator<Traits>(*this) += n;
}
difference_type operator-(const ChannelsIterator<Traits>& other)
{
return (ptr_ - other.ptr_) / step_;
}
/* Comparision */
bool operator==(const ChannelsIterator<Traits>& other) const CV_NOEXCEPT
{
return ptr_ == other.ptr_;
}
bool operator!=(const ChannelsIterator<Traits>& other) const CV_NOEXCEPT
{
return !(*this == other);
}
bool operator<(const ChannelsIterator<Traits>& other) const CV_NOEXCEPT
{
return ptr_ < other.ptr_;
}
bool operator>(const ChannelsIterator<Traits>& other) const CV_NOEXCEPT
{
return other < *this;
}
bool operator>=(const ChannelsIterator<Traits>& other) const CV_NOEXCEPT
{
return !(*this < other);
}
bool operator<=(const ChannelsIterator<Traits>& other) const CV_NOEXCEPT
{
return !(other < *this);
}
private:
pointer ptr_{nullptr};
std::size_t step_{1};
};
template <class Traits>
inline ChannelsIterator<Traits> operator+(typename Traits::difference_type n, const ChannelsIterator<Traits>& it)
{
return it + n;
}
template<typename OutT, typename InT>
void copyToMatImpl(std::vector<InT*>&& in, Mat& out, uint8_t shift)
{
using ChannelsIt = ChannelsIterator<NonConstItTraits<OutT>>;
Size size = out.size();
if (out.isContinuous())
{
size.width *= size.height;
size.height = 1;
}
const bool isShiftRequired = shift != 0;
const std::size_t channelsCount = in.size();
if (isShiftRequired)
{
for (int i = 0; i < size.height; ++i)
{
auto rowPtr = out.ptr<OutT>(i);
for (std::size_t c = 0; c < channelsCount; ++c)
{
const auto first = in[c];
const auto last = first + size.width;
auto dOut = ChannelsIt(rowPtr, c, channelsCount);
std::transform(first, last, dOut, [shift](InT val) -> OutT { return val >> shift; });
in[c] += size.width;
}
}
}
else
{
for (int i = 0; i < size.height; ++i)
{
auto rowPtr = out.ptr<OutT>(i);
for (std::size_t c = 0; c < channelsCount; ++c)
{
const auto first = in[c];
const auto last = first + size.width;
auto dOut = ChannelsIt(rowPtr, c, channelsCount);
std::copy(first, last, dOut);
in[c] += size.width;
}
}
}
}
template<typename InT>
void copyToMat(std::vector<const InT*>&& in, Mat& out, uint8_t shift)
{
switch (out.depth())
{
case CV_8U:
copyToMatImpl<uint8_t>(std::move(in), out, shift);
break;
case CV_16U:
copyToMatImpl<uint16_t>(std::move(in), out, shift);
break;
default:
CV_Error(Error::StsNotImplemented, "only depth CV_8U and CV16_U are supported");
}
}
template<typename InT, typename OutT>
void copyFromMatImpl(const Mat& in, std::vector<OutT*>&& out)
{
using ChannelsIt = ChannelsIterator<ConstItTraits<InT>>;
Size size = in.size();
if (in.isContinuous())
{
size.width *= size.height;
size.height = 1;
}
const std::size_t outChannelsCount = out.size();
for (int i = 0; i < size.height; ++i)
{
const InT* row = in.ptr<InT>(i);
for (std::size_t c = 0; c < outChannelsCount; ++c)
{
auto first = ChannelsIt(row, c, outChannelsCount);
auto last = first + size.width;
out[c] = std::copy(first, last, out[c]);
}
}
}
template<typename OutT>
void copyFromMat(const Mat& in, std::vector<OutT*>&& out)
{
switch (in.depth())
{
case CV_8U:
copyFromMatImpl<uint8_t>(in, std::move(out));
break;
case CV_16U:
copyFromMatImpl<uint16_t>(in, std::move(out));
break;
default:
CV_Error(Error::StsNotImplemented, "only depth CV_8U and CV16_U are supported");
}
}
void errorLogCallback(const char* msg, void* /* userData */)
{
CV_LOG_ERROR(NULL, cv::format("OpenJPEG2000: %s", msg));
}
void warningLogCallback(const char* msg, void* /* userData */)
{
CV_LOG_WARNING(NULL, cv::format("OpenJPEG2000: %s", msg));
}
void setupLogCallbacks(opj_codec_t* codec)
{
if (!opj_set_error_handler(codec, errorLogCallback, nullptr))
{
CV_LOG_WARNING(NULL, "OpenJPEG2000: can not set error log handler");
}
if (!opj_set_warning_handler(codec, warningLogCallback, nullptr))
{
CV_LOG_WARNING(NULL, "OpenJPEG2000: can not set warning log handler");
}
}
opj_dparameters setupDecoderParameters()
{
opj_dparameters parameters;
opj_set_default_decoder_parameters(&parameters);
return parameters;
}
opj_cparameters setupEncoderParameters(const std::vector<int>& params)
{
opj_cparameters parameters;
opj_set_default_encoder_parameters(&parameters);
for (size_t i = 0; i < params.size(); i += 2)
{
switch (params[i])
{
case cv::IMWRITE_JPEG2000_COMPRESSION_X1000:
parameters.tcp_rates[0] = 1000.f / std::min(std::max(params[i + 1], 1), 1000);
break;
default:
CV_LOG_WARNING(NULL, "OpenJPEG2000(encoder): skip unsupported parameter: " << params[i]);
break;
}
}
parameters.tcp_numlayers = 1;
parameters.cp_disto_alloc = 1;
return parameters;
}
bool decodeSRGBData(const opj_image_t& inImg, cv::Mat& outImg, uint8_t shift)
{
using ImageComponents = std::vector<const OPJ_INT32*>;
const int inChannels = inImg.numcomps;
const int outChannels = outImg.channels();
if (outChannels == 1)
{
// Assume gray (+ alpha) for 1 channels -> gray
if (inChannels <= 2)
{
copyToMat(ImageComponents { inImg.comps[0].data }, outImg, shift);
}
// Assume RGB for >= 3 channels -> gray
else
{
Mat tmp(outImg.size(), CV_MAKETYPE(outImg.depth(), 3));
copyToMat(ImageComponents { inImg.comps[2].data, inImg.comps[1].data, inImg.comps[0].data },
tmp, shift);
cvtColor(tmp, outImg, COLOR_BGR2GRAY);
}
return true;
}
if (inChannels >= 3)
{
// Assume RGB (+ alpha) for 3 channels -> BGR
ImageComponents incomps { inImg.comps[2].data, inImg.comps[1].data, inImg.comps[0].data };
// Assume RGBA for 4 channels -> BGRA
if (outChannels > 3)
{
incomps.push_back(inImg.comps[3].data);
}
copyToMat(std::move(incomps), outImg, shift);
return true;
}
CV_LOG_ERROR(NULL,
cv::format("OpenJPEG2000: unsupported conversion from %d components to %d for SRGB image decoding",
inChannels, outChannels));
return false;
}
bool decodeGrayscaleData(const opj_image_t& inImg, cv::Mat& outImg, uint8_t shift)
{
using ImageComponents = std::vector<const OPJ_INT32*>;
const int inChannels = inImg.numcomps;
const int outChannels = outImg.channels();
if (outChannels == 1 || outChannels == 3)
{
copyToMat(ImageComponents(outChannels, inImg.comps[0].data), outImg, shift);
return true;
}
CV_LOG_ERROR(NULL,
cv::format("OpenJPEG2000: unsupported conversion from %d components to %d for Grayscale image decoding",
inChannels, outChannels));
return false;
}
bool decodeSYCCData(const opj_image_t& inImg, cv::Mat& outImg, uint8_t shift)
{
using ImageComponents = std::vector<const OPJ_INT32*>;
const int inChannels = inImg.numcomps;
const int outChannels = outImg.channels();
if (outChannels == 1) {
copyToMat(ImageComponents { inImg.comps[0].data }, outImg, shift);
return true;
}
if (outChannels == 3 && inChannels >= 3) {
copyToMat(ImageComponents { inImg.comps[0].data, inImg.comps[1].data, inImg.comps[2].data },
outImg, shift);
cvtColor(outImg, outImg, COLOR_YUV2BGR);
return true;
}
CV_LOG_ERROR(NULL,
cv::format("OpenJPEG2000: unsupported conversion from %d components to %d for YUV image decoding",
inChannels, outChannels));
return false;
}
OPJ_SIZE_T opjReadFromBuffer(void* dist, OPJ_SIZE_T count, detail::OpjMemoryBuffer* buffer)
{
const OPJ_SIZE_T bytesToRead = std::min(buffer->availableBytes(), count);
if (bytesToRead > 0)
{
memcpy(dist, buffer->pos, bytesToRead);
buffer->pos += bytesToRead;
return bytesToRead;
}
else
{
return static_cast<OPJ_SIZE_T>(-1);
}
}
OPJ_SIZE_T opjSkipFromBuffer(OPJ_SIZE_T count, detail::OpjMemoryBuffer* buffer) {
const OPJ_SIZE_T bytesToSkip = std::min(buffer->availableBytes(), count);
if (bytesToSkip > 0)
{
buffer->pos += bytesToSkip;
return bytesToSkip;
}
else
{
return static_cast<OPJ_SIZE_T>(-1);
}
}
OPJ_BOOL opjSeekFromBuffer(OPJ_OFF_T count, detail::OpjMemoryBuffer* buffer)
{
// Count should stay positive to prevent unsigned overflow
CV_DbgAssert(count > 0);
// To provide proper comparison between OPJ_OFF_T and OPJ_SIZE_T, both should be
// casted to uint64_t (On 32-bit systems sizeof(size_t) might be 4)
CV_DbgAssert(static_cast<uint64_t>(count) < static_cast<uint64_t>(std::numeric_limits<OPJ_SIZE_T>::max()));
const OPJ_SIZE_T pos = std::min(buffer->length, static_cast<OPJ_SIZE_T>(count));
buffer->pos = buffer->begin + pos;
return OPJ_TRUE;
}
detail::StreamPtr opjCreateBufferInputStream(detail::OpjMemoryBuffer* buf)
{
detail::StreamPtr stream{ opj_stream_default_create(/* isInput */ true) };
if (stream)
{
opj_stream_set_user_data(stream.get(), static_cast<void*>(buf), nullptr);
opj_stream_set_user_data_length(stream.get(), buf->length);
opj_stream_set_read_function(stream.get(), (opj_stream_read_fn)(opjReadFromBuffer));
opj_stream_set_skip_function(stream.get(), (opj_stream_skip_fn)(opjSkipFromBuffer));
opj_stream_set_seek_function(stream.get(), (opj_stream_seek_fn)(opjSeekFromBuffer));
}
return stream;
}
} // namespace <anonymous>
/////////////////////// Jpeg2KOpjDecoder ///////////////////
Jpeg2KOpjDecoder::Jpeg2KOpjDecoder()
{
static const unsigned char signature[] = { 0, 0, 0, 0x0c, 'j', 'P', ' ', ' ', 13, 10, 0x87, 10 };
m_signature = String((const char*)(signature), sizeof(signature));
m_buf_supported = true;
}
ImageDecoder Jpeg2KOpjDecoder::newDecoder() const
{
return makePtr<Jpeg2KOpjDecoder>();
}
bool Jpeg2KOpjDecoder::readHeader()
{
if (!m_buf.empty()) {
opjBuf_ = detail::OpjMemoryBuffer(m_buf);
stream_ = opjCreateBufferInputStream(&opjBuf_);
}
else
{
stream_.reset(opj_stream_create_default_file_stream(m_filename.c_str(), OPJ_STREAM_READ));
}
if (!stream_)
return false;
codec_.reset(opj_create_decompress(OPJ_CODEC_JP2));
if (!codec_)
return false;
// Callbacks are cleared, when opj_destroy_codec is called,
// They can provide some additional information for the user, about what goes wrong
setupLogCallbacks(codec_.get());
opj_dparameters parameters = setupDecoderParameters();
if (!opj_setup_decoder(codec_.get(), &parameters))
return false;
{
opj_image_t* rawImage;
if (!opj_read_header(stream_.get(), codec_.get(), &rawImage))
return false;
image_.reset(rawImage);
}
m_width = image_->x1 - image_->x0;
m_height = image_->y1 - image_->y0;
/* Different components may have different precision,
* so check all.
*/
bool hasAlpha = false;
const int numcomps = image_->numcomps;
CV_Assert(numcomps >= 1);
for (int i = 0; i < numcomps; i++)
{
const opj_image_comp_t& comp = image_->comps[i];
if (comp.sgnd)
{
CV_Error(Error::StsNotImplemented, cv::format("OpenJPEG2000: Component %d/%d is signed", i, numcomps));
}
if (hasAlpha && comp.alpha)
{
CV_Error(Error::StsNotImplemented, cv::format("OpenJPEG2000: Component %d/%d is duplicate alpha channel", i, numcomps));
}
hasAlpha |= comp.alpha;
m_maxPrec = std::max(m_maxPrec, comp.prec);
}
if (m_maxPrec < 8) {
CV_Error(Error::StsNotImplemented, "OpenJPEG2000: Precision < 8 not supported");
} else if (m_maxPrec == 8) {
m_type = CV_MAKETYPE(CV_8U, numcomps);
} else if (m_maxPrec <= 16) {
m_type = CV_MAKETYPE(CV_16U, numcomps);
} else if (m_maxPrec <= 23) {
m_type = CV_MAKETYPE(CV_32F, numcomps);
} else {
m_type = CV_MAKETYPE(CV_64F, numcomps);
}
return true;
}
bool Jpeg2KOpjDecoder::readData( Mat& img )
{
using DecodeFunc = bool(*)(const opj_image_t&, cv::Mat&, uint8_t shift);
if (!opj_decode(codec_.get(), stream_.get(), image_.get()))
{
CV_Error(Error::StsError, "OpenJPEG2000: Decoding is failed");
}
if (img.channels() == 2)
{
CV_Error(Error::StsNotImplemented,
cv::format("OpenJPEG2000: Unsupported number of output channels. IN: %d OUT: 2", image_->numcomps));
}
DecodeFunc decode = nullptr;
switch (image_->color_space)
{
case OPJ_CLRSPC_UNKNOWN:
CV_LOG_WARNING(NULL, "OpenJPEG2000: Image has unknown color space, SRGB is assumed");
/* FALLTHRU */
case OPJ_CLRSPC_SRGB:
decode = decodeSRGBData;
break;
case OPJ_CLRSPC_GRAY:
decode = decodeGrayscaleData;
break;
case OPJ_CLRSPC_SYCC:
decode = decodeSYCCData;
break;
case OPJ_CLRSPC_UNSPECIFIED:
CV_Error(Error::StsNotImplemented, "OpenJPEG2000: Image has unspecified color space");
default:
CV_Error(Error::StsNotImplemented,
cv::format("OpenJPEG2000: Unsupported color space conversion: %s -> %s",
colorspaceName(image_->color_space).c_str(),
(img.channels() == 1) ? "gray" : "BGR"));
}
const int depth = img.depth();
const OPJ_UINT32 outPrec = [depth]() {
if (depth == CV_8U) return 8;
if (depth == CV_16U) return 16;
CV_Error(Error::StsNotImplemented,
cv::format("OpenJPEG2000: output precision > 16 not supported: target depth %d", depth));
}();
const uint8_t shift = outPrec > m_maxPrec ? 0 : m_maxPrec - outPrec;
return decode(*image_, img, shift);
}
/////////////////////// Jpeg2KOpjEncoder ///////////////////
Jpeg2KOpjEncoder::Jpeg2KOpjEncoder()
{
m_description = "JPEG-2000 files (*.jp2)";
}
ImageEncoder Jpeg2KOpjEncoder::newEncoder() const
{
return makePtr<Jpeg2KOpjEncoder>();
}
bool Jpeg2KOpjEncoder::isFormatSupported(int depth) const
{
return depth == CV_8U || depth == CV_16U;
}
bool Jpeg2KOpjEncoder::write(const Mat& img, const std::vector<int>& params)
{
CV_Assert(params.size() % 2 == 0);
const int channels = img.channels();
CV_DbgAssert(channels > 0); // passed matrix is not empty
if (channels > 4)
{
CV_Error(Error::StsNotImplemented, "OpenJPEG2000: only BGR(a) and gray (+ alpha) images supported");
}
const int depth = img.depth();
const OPJ_UINT32 outPrec = [depth]() {
if (depth == CV_8U) return 8;
if (depth == CV_16U) return 16;
CV_Error(Error::StsNotImplemented,
cv::format("OpenJPEG2000: image precision > 16 not supported. Got: %d", depth));
}();
opj_cparameters parameters = setupEncoderParameters(params);
std::vector<opj_image_cmptparm_t> compparams(channels);
for (int i = 0; i < channels; i++) {
compparams[i].prec = outPrec;
compparams[i].bpp = outPrec;
compparams[i].sgnd = 0; // unsigned for now
compparams[i].dx = parameters.subsampling_dx;
compparams[i].dy = parameters.subsampling_dy;
compparams[i].w = img.size().width;
compparams[i].h = img.size().height;
}
auto colorspace = (channels > 2) ? OPJ_CLRSPC_SRGB : OPJ_CLRSPC_GRAY;
detail::ImagePtr image(opj_image_create(channels, compparams.data(), colorspace));
if (!image)
{
CV_Error(Error::StsNotImplemented, "OpenJPEG2000: can not create image");
}
if (channels == 2 || channels == 4)
{
image->comps[channels - 1].alpha = 1;
}
// we want the full image
image->x0 = 0;
image->y0 = 0;
image->x1 = compparams[0].dx * compparams[0].w;
image->y1 = compparams[0].dy * compparams[0].h;
// fill the component data arrays
std::vector<OPJ_INT32*> outcomps(channels, nullptr);
if (channels == 1)
{
outcomps.assign({ image->comps[0].data });
}
else if (channels == 2)
{
outcomps.assign({ image->comps[0].data, image->comps[1].data });
}
// Reversed order for BGR -> RGB conversion
else if (channels == 3)
{
outcomps.assign({ image->comps[2].data, image->comps[1].data, image->comps[0].data });
}
else if (channels == 4)
{
outcomps.assign({ image->comps[2].data, image->comps[1].data, image->comps[0].data,
image->comps[3].data });
}
// outcomps holds pointers to the data, so the actual data will be modified but won't be freed
// The container is not needed after data was copied
copyFromMat(img, std::move(outcomps));
detail::CodecPtr codec(opj_create_compress(OPJ_CODEC_JP2));
if (!codec) {
CV_Error(Error::StsNotImplemented, "OpenJPEG2000: can not create compression codec");
}
setupLogCallbacks(codec.get());
if (!opj_setup_encoder(codec.get(), &parameters, image.get()))
{
CV_Error(Error::StsNotImplemented, "OpenJPEG2000: Can not setup encoder");
}
detail::StreamPtr stream(opj_stream_create_default_file_stream(m_filename.c_str(), OPJ_STREAM_WRITE));
if (!stream)
{
CV_Error(Error::StsNotImplemented, "OpenJPEG2000: Can not create stream");
}
if (!opj_start_compress(codec.get(), image.get(), stream.get()))
{
CV_Error(Error::StsNotImplemented, "OpenJPEG2000: Can not start compression");
}
if (!opj_encode(codec.get(), stream.get()))
{
CV_Error(Error::StsNotImplemented, "OpenJPEG2000: Encoding failed");
}
if (!opj_end_compress(codec.get(), stream.get()))
{
CV_Error(Error::StsNotImplemented, "OpenJPEG2000: Can not end compression");
}
return true;
}
} // namespace cv
#endif
@@ -0,0 +1,99 @@
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Copyright (C) 2020, Stefan Brüns <stefan.bruens@rwth-aachen.de>
#ifndef _GRFMT_OPENJPEG_H_
#define _GRFMT_OPENJPEG_H_
#ifdef HAVE_OPENJPEG
#include "grfmt_base.hpp"
#include <openjpeg.h>
namespace cv {
namespace detail {
struct OpjStreamDeleter
{
void operator()(opj_stream_t* stream) const
{
opj_stream_destroy(stream);
}
};
struct OpjCodecDeleter
{
void operator()(opj_codec_t* codec) const
{
opj_destroy_codec(codec);
}
};
struct OpjImageDeleter
{
void operator()(opj_image_t* image) const
{
opj_image_destroy(image);
}
};
struct OpjMemoryBuffer {
OPJ_BYTE* pos{nullptr};
OPJ_BYTE* begin{nullptr};
OPJ_SIZE_T length{0};
OpjMemoryBuffer() = default;
explicit OpjMemoryBuffer(cv::Mat& mat)
: pos{ mat.ptr() }, begin{ mat.ptr() }, length{ mat.rows * mat.cols * mat.elemSize() }
{
}
OPJ_SIZE_T availableBytes() const CV_NOEXCEPT {
return begin + length - pos;
}
};
using StreamPtr = std::unique_ptr<opj_stream_t, detail::OpjStreamDeleter>;
using CodecPtr = std::unique_ptr<opj_codec_t, detail::OpjCodecDeleter>;
using ImagePtr = std::unique_ptr<opj_image_t, detail::OpjImageDeleter>;
} // namespace detail
class Jpeg2KOpjDecoder CV_FINAL : public BaseImageDecoder
{
public:
Jpeg2KOpjDecoder();
~Jpeg2KOpjDecoder() CV_OVERRIDE = default;
ImageDecoder newDecoder() const CV_OVERRIDE;
bool readData( Mat& img ) CV_OVERRIDE;
bool readHeader() CV_OVERRIDE;
private:
detail::StreamPtr stream_{nullptr};
detail::CodecPtr codec_{nullptr};
detail::ImagePtr image_{nullptr};
detail::OpjMemoryBuffer opjBuf_;
OPJ_UINT32 m_maxPrec = 0;
};
class Jpeg2KOpjEncoder CV_FINAL : public BaseImageEncoder
{
public:
Jpeg2KOpjEncoder();
~Jpeg2KOpjEncoder() CV_OVERRIDE = default;
bool isFormatSupported( int depth ) const CV_OVERRIDE;
bool write( const Mat& img, const std::vector<int>& params ) CV_OVERRIDE;
ImageEncoder newEncoder() const CV_OVERRIDE;
};
} //namespace cv
#endif
#endif/*_GRFMT_OPENJPEG_H_*/
+1
View File
@@ -51,6 +51,7 @@
#include "grfmt_tiff.hpp"
#include "grfmt_png.hpp"
#include "grfmt_jpeg2000.hpp"
#include "grfmt_jpeg2000_openjpeg.hpp"
#include "grfmt_exr.hpp"
#include "grfmt_webp.hpp"
#include "grfmt_hdr.hpp"
+4
View File
@@ -178,6 +178,10 @@ struct ImageCodecInitializer
decoders.push_back( makePtr<Jpeg2KDecoder>() );
encoders.push_back( makePtr<Jpeg2KEncoder>() );
#endif
#ifdef HAVE_OPENJPEG
decoders.push_back( makePtr<Jpeg2KOpjDecoder>() );
encoders.push_back( makePtr<Jpeg2KOpjEncoder>() );
#endif
#ifdef HAVE_OPENEXR
decoders.push_back( makePtr<ExrDecoder>() );
encoders.push_back( makePtr<ExrEncoder>() );
+51
View File
@@ -0,0 +1,51 @@
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html
#include "test_precomp.hpp"
#include "test_common.hpp"
namespace opencv_test {
static
Mat generateTestImageBGR_()
{
Size sz(640, 480);
Mat result(sz, CV_8UC3, Scalar::all(0));
const string fname = cvtest::findDataFile("../cv/shared/baboon.png");
Mat image = imread(fname, IMREAD_COLOR);
CV_Assert(!image.empty());
CV_CheckEQ(image.size(), Size(512, 512), "");
Rect roi((640-512) / 2, 0, 512, 480);
image(Rect(0, 0, 512, 480)).copyTo(result(roi));
result(Rect(0, 0, 5, 5)).setTo(Scalar(0, 0, 255)); // R
result(Rect(5, 0, 5, 5)).setTo(Scalar(0, 255, 0)); // G
result(Rect(10, 0, 5, 5)).setTo(Scalar(255, 0, 0)); // B
result(Rect(0, 5, 5, 5)).setTo(Scalar(128, 128, 128)); // gray
//imshow("test_image", result); waitKey();
return result;
}
Mat generateTestImageBGR()
{
static Mat image = generateTestImageBGR_(); // initialize once
CV_Assert(!image.empty());
return image;
}
static
Mat generateTestImageGrayscale_()
{
Mat imageBGR = generateTestImageBGR();
CV_Assert(!imageBGR.empty());
Mat result;
cvtColor(imageBGR, result, COLOR_BGR2GRAY);
return result;
}
Mat generateTestImageGrayscale()
{
static Mat image = generateTestImageGrayscale_(); // initialize once
return image;
}
} // namespace
+15
View File
@@ -0,0 +1,15 @@
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html
#ifndef OPENCV_TEST_IMGCODECS_COMMON_HPP
#define OPENCV_TEST_IMGCODECS_COMMON_HPP
namespace opencv_test {
Mat generateTestImageBGR();
Mat generateTestImageGrayscale();
} // namespace
#endif // OPENCV_TEST_IMGCODECS_COMMON_HPP
+2 -1
View File
@@ -71,7 +71,8 @@ TEST_P(Imgcodecs_FileMode, regression)
const string all_images[] =
{
#if defined(HAVE_JASPER) && defined(OPENCV_IMGCODECS_ENABLE_JASPER_TESTS)
#if (defined(HAVE_JASPER) && defined(OPENCV_IMGCODECS_ENABLE_JASPER_TESTS)) \
|| defined(HAVE_OPENJPEG)
"readwrite/Rome.jp2",
"readwrite/Bretagne2.jp2",
"readwrite/Bretagne2.jp2",
+95 -40
View File
@@ -2,6 +2,7 @@
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html
#include "test_precomp.hpp"
#include "test_common.hpp"
namespace opencv_test { namespace {
@@ -145,45 +146,6 @@ TEST(Imgcodecs_Image, read_write_bmp)
typedef string Ext;
typedef testing::TestWithParam<Ext> Imgcodecs_Image;
TEST_P(Imgcodecs_Image, read_write)
{
const string ext = this->GetParam();
const string full_name = cv::tempfile(ext.c_str());
const string _name = TS::ptr()->get_data_path() + "../cv/shared/baboon.png";
const double thresDbell = 32;
Mat image = imread(_name);
image.convertTo(image, CV_8UC3);
ASSERT_FALSE(image.empty());
imwrite(full_name, image);
Mat loaded = imread(full_name);
ASSERT_FALSE(loaded.empty());
double psnr = cvtest::PSNR(loaded, image);
EXPECT_GT(psnr, thresDbell);
vector<uchar> from_file;
FILE *f = fopen(full_name.c_str(), "rb");
fseek(f, 0, SEEK_END);
long len = ftell(f);
from_file.resize((size_t)len);
fseek(f, 0, SEEK_SET);
from_file.resize(fread(&from_file[0], 1, from_file.size(), f));
fclose(f);
vector<uchar> buf;
imencode("." + ext, image, buf);
ASSERT_EQ(buf, from_file);
Mat buf_loaded = imdecode(Mat(buf), 1);
ASSERT_FALSE(buf_loaded.empty());
psnr = cvtest::PSNR(buf_loaded, image);
EXPECT_GT(psnr, thresDbell);
EXPECT_EQ(0, remove(full_name.c_str()));
}
const string exts[] = {
#ifdef HAVE_PNG
"png",
@@ -194,7 +156,8 @@ const string exts[] = {
#ifdef HAVE_JPEG
"jpg",
#endif
#if defined(HAVE_JASPER) && defined(OPENCV_IMGCODECS_ENABLE_JASPER_TESTS)
#if (defined(HAVE_JASPER) && defined(OPENCV_IMGCODECS_ENABLE_JASPER_TESTS)) \
|| defined(HAVE_OPENJPEG)
"jp2",
#endif
#if 0 /*defined HAVE_OPENEXR && !defined __APPLE__*/
@@ -209,6 +172,98 @@ const string exts[] = {
#endif
};
static
void test_image_io(const Mat& image, const std::string& fname, const std::string& ext, int imreadFlag, double psnrThreshold)
{
vector<uchar> buf;
ASSERT_NO_THROW(imencode("." + ext, image, buf));
ASSERT_NO_THROW(imwrite(fname, image));
FILE *f = fopen(fname.c_str(), "rb");
fseek(f, 0, SEEK_END);
long len = ftell(f);
cout << "File size: " << len << " bytes" << endl;
EXPECT_GT(len, 1024) << "File is small. Test or implementation is broken";
fseek(f, 0, SEEK_SET);
vector<uchar> file_buf((size_t)len);
EXPECT_EQ(len, (long)fread(&file_buf[0], 1, (size_t)len, f));
fclose(f); f = NULL;
EXPECT_EQ(buf, file_buf) << "imwrite() / imencode() calls must provide the same output (bit-exact)";
Mat buf_loaded = imdecode(Mat(buf), imreadFlag);
EXPECT_FALSE(buf_loaded.empty());
Mat loaded = imread(fname, imreadFlag);
EXPECT_FALSE(loaded.empty());
EXPECT_EQ(0, cv::norm(loaded, buf_loaded, NORM_INF)) << "imread() and imdecode() calls must provide the same result (bit-exact)";
double psnr = cvtest::PSNR(loaded, image);
EXPECT_GT(psnr, psnrThreshold);
// not necessary due bitexact check above
//double buf_psnr = cvtest::PSNR(buf_loaded, image);
//EXPECT_GT(buf_psnr, psnrThreshold);
#if 0 // debug
if (psnr <= psnrThreshold /*|| buf_psnr <= thresDbell*/)
{
cout << "File: " << fname << endl;
imshow("origin", image);
imshow("imread", loaded);
imshow("imdecode", buf_loaded);
waitKey();
}
#endif
}
TEST_P(Imgcodecs_Image, read_write_BGR)
{
const string ext = this->GetParam();
const string fname = cv::tempfile(ext.c_str());
double psnrThreshold = 100;
if (ext == "jpg")
psnrThreshold = 32;
#ifdef HAVE_JASPER
if (ext == "jp2")
psnrThreshold = 95;
#endif
Mat image = generateTestImageBGR();
EXPECT_NO_THROW(test_image_io(image, fname, ext, IMREAD_COLOR, psnrThreshold));
EXPECT_EQ(0, remove(fname.c_str()));
}
TEST_P(Imgcodecs_Image, read_write_GRAYSCALE)
{
const string ext = this->GetParam();
if (false
|| ext == "ppm" // grayscale is not implemented
|| ext == "ras" // broken (black result)
)
throw SkipTestException("GRAYSCALE mode is not supported");
const string fname = cv::tempfile(ext.c_str());
double psnrThreshold = 100;
if (ext == "jpg")
psnrThreshold = 40;
#ifdef HAVE_JASPER
if (ext == "jp2")
psnrThreshold = 70;
#endif
Mat image = generateTestImageGrayscale();
EXPECT_NO_THROW(test_image_io(image, fname, ext, IMREAD_GRAYSCALE, psnrThreshold));
EXPECT_EQ(0, remove(fname.c_str()));
}
INSTANTIATE_TEST_CASE_P(imgcodecs, Imgcodecs_Image, testing::ValuesIn(exts));
TEST(Imgcodecs_Image, regression_9376)
+14 -14
View File
@@ -59,8 +59,8 @@ class resizeNNInvokerAVX4 CV_FINAL :
public ParallelLoopBody
{
public:
resizeNNInvokerAVX4(const Mat& _src, Mat &_dst, int *_x_ofs, int _pix_size4, double _ify) :
ParallelLoopBody(), src(_src), dst(_dst), x_ofs(_x_ofs), pix_size4(_pix_size4),
resizeNNInvokerAVX4(const Mat& _src, Mat &_dst, int *_x_ofs, double _ify) :
ParallelLoopBody(), src(_src), dst(_dst), x_ofs(_x_ofs),
ify(_ify)
{
}
@@ -129,9 +129,9 @@ public:
}
private:
const Mat src;
Mat dst;
int* x_ofs, pix_size4;
const Mat& src;
Mat& dst;
int* x_ofs;
double ify;
resizeNNInvokerAVX4(const resizeNNInvokerAVX4&);
@@ -142,8 +142,8 @@ class resizeNNInvokerAVX2 CV_FINAL :
public ParallelLoopBody
{
public:
resizeNNInvokerAVX2(const Mat& _src, Mat &_dst, int *_x_ofs, int _pix_size4, double _ify) :
ParallelLoopBody(), src(_src), dst(_dst), x_ofs(_x_ofs), pix_size4(_pix_size4),
resizeNNInvokerAVX2(const Mat& _src, Mat &_dst, int *_x_ofs, double _ify) :
ParallelLoopBody(), src(_src), dst(_dst), x_ofs(_x_ofs),
ify(_ify)
{
}
@@ -235,24 +235,24 @@ public:
}
private:
const Mat src;
Mat dst;
int* x_ofs, pix_size4;
const Mat& src;
Mat& dst;
int* x_ofs;
double ify;
resizeNNInvokerAVX2(const resizeNNInvokerAVX2&);
resizeNNInvokerAVX2& operator=(const resizeNNInvokerAVX2&);
};
void resizeNN2_AVX2(const Range& range, const Mat& src, Mat &dst, int *x_ofs, int pix_size4, double ify)
void resizeNN2_AVX2(const Range& range, const Mat& src, Mat &dst, int *x_ofs, double ify)
{
resizeNNInvokerAVX2 invoker(src, dst, x_ofs, pix_size4, ify);
resizeNNInvokerAVX2 invoker(src, dst, x_ofs, ify);
parallel_for_(range, invoker, dst.total() / (double)(1 << 16));
}
void resizeNN4_AVX2(const Range& range, const Mat& src, Mat &dst, int *x_ofs, int pix_size4, double ify)
void resizeNN4_AVX2(const Range& range, const Mat& src, Mat &dst, int *x_ofs, double ify)
{
resizeNNInvokerAVX4 invoker(src, dst, x_ofs, pix_size4, ify);
resizeNNInvokerAVX4 invoker(src, dst, x_ofs, ify);
parallel_for_(range, invoker, dst.total() / (double)(1 << 16));
}
+13 -15
View File
@@ -970,8 +970,8 @@ class resizeNNInvoker :
public ParallelLoopBody
{
public:
resizeNNInvoker(const Mat& _src, Mat &_dst, int *_x_ofs, int _pix_size4, double _ify) :
ParallelLoopBody(), src(_src), dst(_dst), x_ofs(_x_ofs), pix_size4(_pix_size4),
resizeNNInvoker(const Mat& _src, Mat &_dst, int *_x_ofs, double _ify) :
ParallelLoopBody(), src(_src), dst(_dst), x_ofs(_x_ofs),
ify(_ify)
{
}
@@ -1043,19 +1043,18 @@ public:
default:
for( x = 0; x < dsize.width; x++, D += pix_size )
{
const int* _tS = (const int*)(S + x_ofs[x]);
int* _tD = (int*)D;
for( int k = 0; k < pix_size4; k++ )
_tD[k] = _tS[k];
const uchar* _tS = S + x_ofs[x];
for (int k = 0; k < pix_size; k++)
D[k] = _tS[k];
}
}
}
}
private:
const Mat src;
Mat dst;
int* x_ofs, pix_size4;
const Mat& src;
Mat& dst;
int* x_ofs;
double ify;
resizeNNInvoker(const resizeNNInvoker&);
@@ -1069,7 +1068,6 @@ resizeNN( const Mat& src, Mat& dst, double fx, double fy )
AutoBuffer<int> _x_ofs(dsize.width);
int* x_ofs = _x_ofs.data();
int pix_size = (int)src.elemSize();
int pix_size4 = (int)(pix_size / sizeof(int));
double ifx = 1./fx, ify = 1./fy;
int x;
@@ -1084,9 +1082,9 @@ resizeNN( const Mat& src, Mat& dst, double fx, double fy )
if(CV_CPU_HAS_SUPPORT_AVX2 && ((pix_size == 2) || (pix_size == 4)))
{
if(pix_size == 2)
opt_AVX2::resizeNN2_AVX2(range, src, dst, x_ofs, pix_size4, ify);
opt_AVX2::resizeNN2_AVX2(range, src, dst, x_ofs, ify);
else
opt_AVX2::resizeNN4_AVX2(range, src, dst, x_ofs, pix_size4, ify);
opt_AVX2::resizeNN4_AVX2(range, src, dst, x_ofs, ify);
}
else
#endif
@@ -1094,14 +1092,14 @@ resizeNN( const Mat& src, Mat& dst, double fx, double fy )
if(CV_CPU_HAS_SUPPORT_SSE4_1 && ((pix_size == 2) || (pix_size == 4)))
{
if(pix_size == 2)
opt_SSE4_1::resizeNN2_SSE4_1(range, src, dst, x_ofs, pix_size4, ify);
opt_SSE4_1::resizeNN2_SSE4_1(range, src, dst, x_ofs, ify);
else
opt_SSE4_1::resizeNN4_SSE4_1(range, src, dst, x_ofs, pix_size4, ify);
opt_SSE4_1::resizeNN4_SSE4_1(range, src, dst, x_ofs, ify);
}
else
#endif
{
resizeNNInvoker invoker(src, dst, x_ofs, pix_size4, ify);
resizeNNInvoker invoker(src, dst, x_ofs, ify);
parallel_for_(range, invoker, dst.total()/(double)(1<<16));
}
}
+4 -4
View File
@@ -56,16 +56,16 @@ namespace cv
namespace opt_AVX2
{
#if CV_TRY_AVX2
void resizeNN2_AVX2(const Range&, const Mat&, Mat&, int*, int, double);
void resizeNN4_AVX2(const Range&, const Mat&, Mat&, int*, int, double);
void resizeNN2_AVX2(const Range&, const Mat&, Mat&, int*, double);
void resizeNN4_AVX2(const Range&, const Mat&, Mat&, int*, double);
#endif
}
namespace opt_SSE4_1
{
#if CV_TRY_SSE4_1
void resizeNN2_SSE4_1(const Range&, const Mat&, Mat&, int*, int, double);
void resizeNN4_SSE4_1(const Range&, const Mat&, Mat&, int*, int, double);
void resizeNN2_SSE4_1(const Range&, const Mat&, Mat&, int*, double);
void resizeNN4_SSE4_1(const Range&, const Mat&, Mat&, int*, double);
int VResizeLanczos4Vec_32f16u_SSE41(const float** src, ushort* dst, const float* beta, int width);
#endif
+14 -14
View File
@@ -59,8 +59,8 @@ class resizeNNInvokerSSE2 :
public ParallelLoopBody
{
public:
resizeNNInvokerSSE2(const Mat& _src, Mat &_dst, int *_x_ofs, int _pix_size4, double _ify) :
ParallelLoopBody(), src(_src), dst(_dst), x_ofs(_x_ofs), pix_size4(_pix_size4),
resizeNNInvokerSSE2(const Mat& _src, Mat &_dst, int *_x_ofs, double _ify) :
ParallelLoopBody(), src(_src), dst(_dst), x_ofs(_x_ofs),
ify(_ify)
{
}
@@ -110,9 +110,9 @@ public:
}
private:
const Mat src;
Mat dst;
int* x_ofs, pix_size4;
const Mat& src;
Mat& dst;
int* x_ofs;
double ify;
resizeNNInvokerSSE2(const resizeNNInvokerSSE2&);
@@ -123,8 +123,8 @@ class resizeNNInvokerSSE4 :
public ParallelLoopBody
{
public:
resizeNNInvokerSSE4(const Mat& _src, Mat &_dst, int *_x_ofs, int _pix_size4, double _ify) :
ParallelLoopBody(), src(_src), dst(_dst), x_ofs(_x_ofs), pix_size4(_pix_size4),
resizeNNInvokerSSE4(const Mat& _src, Mat &_dst, int *_x_ofs, double _ify) :
ParallelLoopBody(), src(_src), dst(_dst), x_ofs(_x_ofs),
ify(_ify)
{
}
@@ -165,24 +165,24 @@ public:
}
private:
const Mat src;
Mat dst;
int* x_ofs, pix_size4;
const Mat& src;
Mat& dst;
int* x_ofs;
double ify;
resizeNNInvokerSSE4(const resizeNNInvokerSSE4&);
resizeNNInvokerSSE4& operator=(const resizeNNInvokerSSE4&);
};
void resizeNN2_SSE4_1(const Range& range, const Mat& src, Mat &dst, int *x_ofs, int pix_size4, double ify)
void resizeNN2_SSE4_1(const Range& range, const Mat& src, Mat &dst, int *x_ofs, double ify)
{
resizeNNInvokerSSE2 invoker(src, dst, x_ofs, pix_size4, ify);
resizeNNInvokerSSE2 invoker(src, dst, x_ofs, ify);
parallel_for_(range, invoker, dst.total() / (double)(1 << 16));
}
void resizeNN4_SSE4_1(const Range& range, const Mat& src, Mat &dst, int *x_ofs, int pix_size4, double ify)
void resizeNN4_SSE4_1(const Range& range, const Mat& src, Mat &dst, int *x_ofs, double ify)
{
resizeNNInvokerSSE4 invoker(src, dst, x_ofs, pix_size4, ify);
resizeNNInvokerSSE4 invoker(src, dst, x_ofs, ify);
parallel_for_(range, invoker, dst.total() / (double)(1 << 16));
}
+1 -1
View File
@@ -1413,7 +1413,7 @@ TEST(Resize, lanczos4_regression_16192)
EXPECT_EQ(cvtest::norm(dst, expected, NORM_INF), 0) << dst(Rect(0,0,8,8));
}
TEST(Resize, DISABLED_nearest_regression_15075) // reverted https://github.com/opencv/opencv/pull/16497
TEST(Resize, nearest_regression_15075)
{
const int C = 5;
const int i1 = 5, j1 = 5;
+6 -2
View File
@@ -778,7 +778,9 @@ void DpSeamFinder::computeCosts(
{
for (int x = roi.x; x < roi.br().x+1; ++x)
{
if (labels_(y, x) == l && x > 0 && labels_(y, x-1) == l)
if (x > 0 && x < labels_.cols &&
labels_(y, x) == l && labels_(y, x-1) == l
)
{
float costColor = (diff(image1, y + dy1, x + dx1 - 1, image2, y + dy2, x + dx2) +
diff(image1, y + dy1, x + dx1, image2, y + dy2, x + dx2 - 1)) / 2;
@@ -802,7 +804,9 @@ void DpSeamFinder::computeCosts(
{
for (int x = roi.x; x < roi.br().x; ++x)
{
if (labels_(y, x) == l && y > 0 && labels_(y-1, x) == l)
if (y > 0 && y < labels_.rows &&
labels_(y, x) == l && labels_(y-1, x) == l
)
{
float costColor = (diff(image1, y + dy1 - 1, x + dx1, image2, y + dy2, x + dx2) +
diff(image1, y + dy1, x + dx1, image2, y + dy2 - 1, x + dx2)) / 2;
+1 -2
View File
@@ -221,7 +221,6 @@ if(WIN32 AND HAVE_FFMPEG_WRAPPER)
endif()
install(FILES "${ffmpeg_path}" DESTINATION ${OPENCV_BIN_INSTALL_PATH} COMPONENT libs RENAME "${ffmpeg_bare_name_ver}")
if(INSTALL_CREATE_DISTRIB)
install(FILES "${ffmpeg_dir}/opencv_videoio_ffmpeg.dll" DESTINATION "bin/" COMPONENT libs RENAME "opencv_videoio_ffmpeg${OPENCV_DLLVERSION}.dll")
install(FILES "${ffmpeg_dir}/opencv_videoio_ffmpeg_64.dll" DESTINATION "bin/" COMPONENT libs RENAME "opencv_videoio_ffmpeg${OPENCV_DLLVERSION}_64.dll")
install(FILES "${ffmpeg_dir}/opencv_videoio_ffmpeg${FFMPEG_SUFFIX}.dll" DESTINATION "bin/" COMPONENT libs RENAME "opencv_videoio_ffmpeg${OPENCV_DLLVERSION}${FFMPEG_SUFFIX}.dll")
endif()
endif()
+17 -16
View File
@@ -585,7 +585,7 @@ public:
virtual bool isOpened() const CV_OVERRIDE { return isOpen; }
virtual int getCaptureDomain() CV_OVERRIDE { return CV_CAP_MSMF; }
protected:
bool configureOutput(MediaType newType, cv::uint32_t outFormat, bool convertToFormat);
bool configureOutput(MediaType newType, cv::uint32_t outFormat);
bool setTime(double time, bool rough);
bool configureHW(bool enable);
@@ -772,7 +772,7 @@ bool CvCapture_MSMF::configureHW(bool enable)
#endif
}
bool CvCapture_MSMF::configureOutput(MediaType newType, cv::uint32_t outFormat, bool convertToFormat)
bool CvCapture_MSMF::configureOutput(MediaType newType, cv::uint32_t outFormat)
{
FormatStorage formats;
formats.read(videoFileSource.Get());
@@ -780,7 +780,7 @@ bool CvCapture_MSMF::configureOutput(MediaType newType, cv::uint32_t outFormat,
dwStreamIndex = bestMatch.first.stream;
nativeFormat = bestMatch.second;
MediaType newFormat = nativeFormat;
if (convertToFormat)
if (convertFormat)
{
switch (outFormat)
{
@@ -840,7 +840,7 @@ bool CvCapture_MSMF::open(int index)
camid = index;
readCallback = cb;
duration = 0;
if (configureOutput(MediaType::createDefault(), outputFormat, convertFormat))
if (configureOutput(MediaType::createDefault(), outputFormat))
{
frameStep = captureFormat.getFrameStep();
}
@@ -861,7 +861,7 @@ bool CvCapture_MSMF::open(const cv::String& _filename)
{
isOpen = true;
sampleTime = 0;
if (configureOutput(MediaType(), outputFormat, convertFormat))
if (configureOutput(MediaType(), outputFormat))
{
frameStep = captureFormat.getFrameStep();
filename = _filename;
@@ -1302,44 +1302,45 @@ bool CvCapture_MSMF::setProperty( int property_id, double value )
return false;
}
case CV_CAP_PROP_FOURCC:
return configureOutput(newFormat, (int)cvRound(value), convertFormat);
return configureOutput(newFormat, (int)cvRound(value));
case CV_CAP_PROP_FORMAT:
return configureOutput(newFormat, (int)cvRound(value), convertFormat);
return configureOutput(newFormat, (int)cvRound(value));
case CV_CAP_PROP_CONVERT_RGB:
return configureOutput(newFormat, outputFormat, value != 0);
convertFormat = (value != 0);
return configureOutput(newFormat, outputFormat);
case CV_CAP_PROP_SAR_NUM:
if (value > 0)
{
newFormat.aspectRatioNum = (UINT32)cvRound(value);
return configureOutput(newFormat, outputFormat, convertFormat);
return configureOutput(newFormat, outputFormat);
}
break;
case CV_CAP_PROP_SAR_DEN:
if (value > 0)
{
newFormat.aspectRatioDenom = (UINT32)cvRound(value);
return configureOutput(newFormat, outputFormat, convertFormat);
return configureOutput(newFormat, outputFormat);
}
break;
case CV_CAP_PROP_FRAME_WIDTH:
if (value >= 0)
{
newFormat.width = (UINT32)cvRound(value);
return configureOutput(newFormat, outputFormat, convertFormat);
return configureOutput(newFormat, outputFormat);
}
break;
case CV_CAP_PROP_FRAME_HEIGHT:
if (value >= 0)
{
newFormat.height = (UINT32)cvRound(value);
return configureOutput(newFormat, outputFormat, convertFormat);
return configureOutput(newFormat, outputFormat);
}
break;
case CV_CAP_PROP_FPS:
if (value >= 0)
{
newFormat.setFramerate(value);
return configureOutput(newFormat, outputFormat, convertFormat);
return configureOutput(newFormat, outputFormat);
}
break;
case CV_CAP_PROP_FRAME_COUNT:
@@ -1569,7 +1570,7 @@ bool CvVideoWriter_MSMF::open( const cv::String& filename, int fourcc,
SUCCEEDED(mediaTypeOut->SetUINT32(MF_MT_AVG_BITRATE, bitRate)) &&
SUCCEEDED(mediaTypeOut->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive)) &&
SUCCEEDED(MFSetAttributeSize(mediaTypeOut.Get(), MF_MT_FRAME_SIZE, videoWidth, videoHeight)) &&
SUCCEEDED(MFSetAttributeRatio(mediaTypeOut.Get(), MF_MT_FRAME_RATE, (UINT32)fps, 1)) &&
SUCCEEDED(MFSetAttributeRatio(mediaTypeOut.Get(), MF_MT_FRAME_RATE, (UINT32)(fps * 1000), 1000)) &&
SUCCEEDED(MFSetAttributeRatio(mediaTypeOut.Get(), MF_MT_PIXEL_ASPECT_RATIO, 1, 1)) &&
// Set the input media type.
SUCCEEDED(MFCreateMediaType(&mediaTypeIn)) &&
@@ -1578,7 +1579,7 @@ bool CvVideoWriter_MSMF::open( const cv::String& filename, int fourcc,
SUCCEEDED(mediaTypeIn->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive)) &&
SUCCEEDED(mediaTypeIn->SetUINT32(MF_MT_DEFAULT_STRIDE, 4 * videoWidth)) && //Assume BGR32 input
SUCCEEDED(MFSetAttributeSize(mediaTypeIn.Get(), MF_MT_FRAME_SIZE, videoWidth, videoHeight)) &&
SUCCEEDED(MFSetAttributeRatio(mediaTypeIn.Get(), MF_MT_FRAME_RATE, (UINT32)fps, 1)) &&
SUCCEEDED(MFSetAttributeRatio(mediaTypeIn.Get(), MF_MT_FRAME_RATE, (UINT32)(fps * 1000), 1000)) &&
SUCCEEDED(MFSetAttributeRatio(mediaTypeIn.Get(), MF_MT_PIXEL_ASPECT_RATIO, 1, 1)) &&
// Set sink writer parameters
SUCCEEDED(MFCreateAttributes(&spAttr, 10)) &&
@@ -1599,7 +1600,7 @@ bool CvVideoWriter_MSMF::open( const cv::String& filename, int fourcc,
{
initiated = true;
rtStart = 0;
MFFrameRateToAverageTimePerFrame((UINT32)fps, 1, &rtDuration);
MFFrameRateToAverageTimePerFrame((UINT32)(fps * 1000), 1000, &rtDuration);
return true;
}
}
+1
View File
@@ -0,0 +1 @@
*.patch text eol=crlf -whitespace
@@ -0,0 +1,158 @@
diff --git a/inference-engine/CMakeLists.txt b/inference-engine/CMakeLists.txt
index d5feedb..1b7aa7e 100644
--- a/inference-engine/CMakeLists.txt
+++ b/inference-engine/CMakeLists.txt
@@ -59,11 +59,11 @@ if(ENABLE_TESTS)
add_subdirectory(tests)
endif()
-add_subdirectory(tools)
+#add_subdirectory(tools)
# gflags and format_reader targets are kept inside of samples directory and
# they must be built even if samples build is disabled (required for tests and tools).
-add_subdirectory(samples)
+#add_subdirectory(samples)
file(GLOB_RECURSE SAMPLES_SOURCES samples/*.cpp samples/*.hpp samples/*.h)
add_cpplint_target(sample_cpplint
@@ -134,7 +134,7 @@ install(DIRECTORY ${ie_python_api_SOURCE_DIR}/sample/
add_custom_target(ie_dev_targets ALL DEPENDS inference_engine HeteroPlugin)
# Developer package
-ie_developer_export_targets(format_reader)
+#ie_developer_export_targets(format_reader)
if (ENABLE_NGRAPH)
ie_developer_export_targets(${NGRAPH_LIBRARIES})
diff --git a/inference-engine/src/inference_engine/CMakeLists.txt b/inference-engine/src/inference_engine/CMakeLists.txt
index 54e264c..c0b7495 100644
--- a/inference-engine/src/inference_engine/CMakeLists.txt
+++ b/inference-engine/src/inference_engine/CMakeLists.txt
@@ -228,7 +228,7 @@ target_include_directories(${TARGET_NAME}_nn_builder PRIVATE "${CMAKE_CURRENT_SO
# Static library used for unit tests which are always built
-add_library(${TARGET_NAME}_s STATIC
+add_library(${TARGET_NAME}_s STATIC EXCLUDE_FROM_ALL
$<TARGET_OBJECTS:${TARGET_NAME}_obj>
${NN_BUILDER_LIBRARY_SRC})
diff --git a/inference-engine/src/mkldnn_plugin/CMakeLists.txt b/inference-engine/src/mkldnn_plugin/CMakeLists.txt
index cd727fd..2f09b44 100644
--- a/inference-engine/src/mkldnn_plugin/CMakeLists.txt
+++ b/inference-engine/src/mkldnn_plugin/CMakeLists.txt
@@ -184,9 +184,9 @@ endif()
add_library(mkldnn_plugin_layers_no_opt OBJECT ${CROSS_COMPILED_SOURCES})
set_ie_threading_interface_for(mkldnn_plugin_layers_no_opt)
-add_library(mkldnn_plugin_layers_no_opt_s OBJECT ${CROSS_COMPILED_SOURCES})
-set_ie_threading_interface_for(mkldnn_plugin_layers_no_opt_s)
-target_compile_definitions(mkldnn_plugin_layers_no_opt_s PRIVATE USE_STATIC_IE)
+#add_library(mkldnn_plugin_layers_no_opt_s OBJECT ${CROSS_COMPILED_SOURCES})
+#set_ie_threading_interface_for(mkldnn_plugin_layers_no_opt_s)
+#target_compile_definitions(mkldnn_plugin_layers_no_opt_s PRIVATE USE_STATIC_IE)
set(object_libraries mkldnn_plugin_layers_no_opt)
set(mkldnn_plugin_object_libraries mkldnn_plugin_layers_no_opt_s)
@@ -220,7 +220,7 @@ if (ENABLE_SSE42)
endfunction()
mkldnn_create_sse42_layers(mkldnn_plugin_layers_sse42)
- mkldnn_create_sse42_layers(mkldnn_plugin_layers_sse42_s)
+ #mkldnn_create_sse42_layers(mkldnn_plugin_layers_sse42_s)
list(APPEND object_libraries mkldnn_plugin_layers_sse42)
list(APPEND mkldnn_plugin_object_libraries mkldnn_plugin_layers_sse42_s)
@@ -259,7 +259,7 @@ if (ENABLE_AVX2)
endfunction()
mkldnn_create_avx2_layers(mkldnn_plugin_layers_avx2)
- mkldnn_create_avx2_layers(mkldnn_plugin_layers_avx2_s)
+ #mkldnn_create_avx2_layers(mkldnn_plugin_layers_avx2_s)
list(APPEND object_libraries mkldnn_plugin_layers_avx2)
list(APPEND mkldnn_plugin_object_libraries mkldnn_plugin_layers_avx2_s)
@@ -297,7 +297,7 @@ if (ENABLE_AVX512F)
endfunction()
mkldnn_create_avx512f_layers(mkldnn_plugin_layers_avx512)
- mkldnn_create_avx512f_layers(mkldnn_plugin_layers_avx512_s)
+ #mkldnn_create_avx512f_layers(mkldnn_plugin_layers_avx512_s)
list(APPEND object_libraries mkldnn_plugin_layers_avx512)
list(APPEND mkldnn_plugin_object_libraries mkldnn_plugin_layers_avx512_s)
@@ -317,7 +317,7 @@ target_link_libraries(${TARGET_NAME} PRIVATE inference_engine ${INTEL_ITT_LIBS}
# add test object library
-add_library(${TARGET_NAME}_obj OBJECT ${SOURCES} ${HEADERS})
+add_library(${TARGET_NAME}_obj OBJECT EXCLUDE_FROM_ALL ${SOURCES} ${HEADERS})
target_include_directories(${TARGET_NAME}_obj PRIVATE $<TARGET_PROPERTY:inference_engine_preproc_s,INTERFACE_INCLUDE_DIRECTORIES>)
diff --git a/inference-engine/src/preprocessing/CMakeLists.txt b/inference-engine/src/preprocessing/CMakeLists.txt
index 41f14a9..0e1b4f6 100644
--- a/inference-engine/src/preprocessing/CMakeLists.txt
+++ b/inference-engine/src/preprocessing/CMakeLists.txt
@@ -81,7 +81,7 @@ endif()
# Static library used for unit tests which are always built
-add_library(${TARGET_NAME}_s STATIC
+add_library(${TARGET_NAME}_s STATIC EXCLUDE_FROM_ALL
$<TARGET_OBJECTS:${TARGET_NAME}_obj>)
set_ie_threading_interface_for(${TARGET_NAME}_s)
diff --git a/inference-engine/src/vpu/common/CMakeLists.txt b/inference-engine/src/vpu/common/CMakeLists.txt
index 8995390..8413faf 100644
--- a/inference-engine/src/vpu/common/CMakeLists.txt
+++ b/inference-engine/src/vpu/common/CMakeLists.txt
@@ -49,7 +49,7 @@ add_common_target("vpu_common_lib" FALSE)
# Unit tests support for graph transformer
if(WIN32)
- add_common_target("vpu_common_lib_test_static" TRUE)
+ #add_common_target("vpu_common_lib_test_static" TRUE)
else()
add_library("vpu_common_lib_test_static" ALIAS "vpu_common_lib")
endif()
diff --git a/inference-engine/src/vpu/graph_transformer/CMakeLists.txt b/inference-engine/src/vpu/graph_transformer/CMakeLists.txt
index e77296e..333f560 100644
--- a/inference-engine/src/vpu/graph_transformer/CMakeLists.txt
+++ b/inference-engine/src/vpu/graph_transformer/CMakeLists.txt
@@ -60,7 +60,7 @@ add_graph_transformer_target("vpu_graph_transformer" FALSE)
# Unit tests support for graph transformer
if(WIN32)
- add_graph_transformer_target("vpu_graph_transformer_test_static" TRUE)
+ #add_graph_transformer_target("vpu_graph_transformer_test_static" TRUE)
else()
add_library("vpu_graph_transformer_test_static" ALIAS "vpu_graph_transformer")
endif()
diff --git a/inference-engine/thirdparty/CMakeLists.txt b/inference-engine/thirdparty/CMakeLists.txt
index ec22761..8bb3325 100644
--- a/inference-engine/thirdparty/CMakeLists.txt
+++ b/inference-engine/thirdparty/CMakeLists.txt
@@ -36,7 +36,7 @@ function(build_with_lto)
endif()
add_subdirectory(pugixml)
- add_subdirectory(stb_lib)
+ #add_subdirectory(stb_lib)
add_subdirectory(ade)
add_subdirectory(fluid/modules/gapi)
diff --git a/inference-engine/thirdparty/pugixml/CMakeLists.txt b/inference-engine/thirdparty/pugixml/CMakeLists.txt
index 8bcb280..5a17fa3 100644
--- a/inference-engine/thirdparty/pugixml/CMakeLists.txt
+++ b/inference-engine/thirdparty/pugixml/CMakeLists.txt
@@ -41,7 +41,7 @@ if(BUILD_SHARED_LIBS)
else()
add_library(pugixml STATIC ${SOURCES})
if (MSVC)
- add_library(pugixml_mt STATIC ${SOURCES})
+ #add_library(pugixml_mt STATIC ${SOURCES})
#if (WIN32)
# set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MT")
# set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MTd")
@@ -0,0 +1,13 @@
diff --git a/cmake/developer_package.cmake b/cmake/developer_package.cmake
index e59edb2..e42ac19 100644
--- a/cmake/developer_package.cmake
+++ b/cmake/developer_package.cmake
@@ -99,7 +99,7 @@ if(UNIX)
SET(LIB_DL ${CMAKE_DL_LIBS})
endif()
-set(OUTPUT_ROOT ${OpenVINO_MAIN_SOURCE_DIR})
+set(OUTPUT_ROOT ${CMAKE_BINARY_DIR})
# Enable postfixes for Debug/Release builds
set(IE_DEBUG_POSTFIX_WIN "d")
@@ -0,0 +1,25 @@
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 631465f..723153b 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -567,7 +567,7 @@ if (NGRAPH_ONNX_IMPORT_ENABLE)
endif()
endif()
-include(cmake/external_gtest.cmake)
+#include(cmake/external_gtest.cmake)
if(NGRAPH_JSON_ENABLE)
include(cmake/external_json.cmake)
endif()
@@ -623,8 +623,8 @@ endif()
add_subdirectory(src)
-add_subdirectory(test)
-add_subdirectory(doc/examples)
+#add_subdirectory(test)
+#add_subdirectory(doc/examples)
if (NGRAPH_DOC_BUILD_ENABLE)
add_subdirectory(doc)
@@ -0,0 +1,14 @@
diff --git a/CMakeLists.txt b/CMakeLists.txt
index e48cee5..5823e92 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -12,6 +12,9 @@ endif()
project(OpenVINO)
+set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /Zi")
+set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} /DEBUG /OPT:REF /OPT:ICF")
+
set(OpenVINO_MAIN_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
set(CMAKE_MODULE_PATH "${OpenVINO_MAIN_SOURCE_DIR}/cmake" ${CMAKE_MODULE_PATH})
@@ -0,0 +1,13 @@
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 7900b382..b5c53d09 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -24,6 +24,8 @@ include(features)
# include developer package
include(developer_package)
+disable_deprecated_warnings()
+
# These options are shared with 3rdparty plugins
# by means of developer package
include(check_features)
@@ -0,0 +1,5 @@
applyPatch('20200313-ngraph-disable-tests-examples.patch', 'ngraph')
applyPatch('20200313-dldt-disable-unused-targets.patch')
applyPatch('20200313-dldt-fix-binaries-location.patch')
applyPatch('20200318-dldt-pdb.patch')
applyPatch('20200319-dldt-fix-msvs2019-v16.5.0.patch')
@@ -0,0 +1,51 @@
sysroot_bin_dir = prepare_dir(self.sysrootdir / 'bin')
copytree(self.build_dir / 'install', self.sysrootdir / 'ngraph')
#rm_one(self.sysrootdir / 'ngraph' / 'lib' / 'ngraph.dll')
build_config = 'Release' if not self.config.build_debug else 'Debug'
build_bin_dir = self.build_dir / 'bin' / 'intel64' / build_config
def copy_bin(name):
global build_bin_dir, sysroot_bin_dir
copytree(build_bin_dir / name, sysroot_bin_dir / name)
dll_suffix = 'd' if self.config.build_debug else ''
def copy_dll(name):
global copy_bin, dll_suffix
copy_bin(name + dll_suffix + '.dll')
copy_bin(name + dll_suffix + '.pdb')
copy_bin('cldnn_global_custom_kernels')
copy_bin('cache.json')
copy_dll('clDNNPlugin')
copy_dll('HeteroPlugin')
copy_dll('inference_engine')
copy_dll('inference_engine_nn_builder')
copy_dll('MKLDNNPlugin')
copy_dll('myriadPlugin')
copy_dll('ngraph')
copy_bin('plugins.xml')
copytree(self.build_dir / 'bin' / 'intel64' / 'pcie-ma248x.elf', sysroot_bin_dir / 'pcie-ma248x.elf')
copytree(self.build_dir / 'bin' / 'intel64' / 'usb-ma2x8x.mvcmd', sysroot_bin_dir / 'usb-ma2x8x.mvcmd')
copytree(self.build_dir / 'bin' / 'intel64' / 'usb-ma2450.mvcmd', sysroot_bin_dir / 'usb-ma2450.mvcmd')
copytree(self.srcdir / 'inference-engine' / 'temp' / 'tbb' / 'bin', sysroot_bin_dir)
copytree(self.srcdir / 'inference-engine' / 'temp' / 'tbb', self.sysrootdir / 'tbb')
sysroot_ie_dir = prepare_dir(self.sysrootdir / 'deployment_tools' / 'inference_engine')
sysroot_ie_lib_dir = prepare_dir(sysroot_ie_dir / 'lib' / 'intel64')
copytree(self.srcdir / 'inference-engine' / 'include', sysroot_ie_dir / 'include')
if not self.config.build_debug:
copytree(self.build_dir / 'install' / 'lib' / 'ngraph.lib', sysroot_ie_lib_dir / 'ngraph.lib')
copytree(build_bin_dir / 'inference_engine.lib', sysroot_ie_lib_dir / 'inference_engine.lib')
copytree(build_bin_dir / 'inference_engine_nn_builder.lib', sysroot_ie_lib_dir / 'inference_engine_nn_builder.lib')
else:
copytree(self.build_dir / 'install' / 'lib' / 'ngraphd.lib', sysroot_ie_lib_dir / 'ngraphd.lib')
copytree(build_bin_dir / 'inference_engined.lib', sysroot_ie_lib_dir / 'inference_engined.lib')
copytree(build_bin_dir / 'inference_engine_nn_builderd.lib', sysroot_ie_lib_dir / 'inference_engine_nn_builderd.lib')
sysroot_license_dir = prepare_dir(self.sysrootdir / 'etc' / 'licenses')
copytree(self.srcdir / 'LICENSE', sysroot_license_dir / 'dldt-LICENSE')
copytree(self.srcdir / 'ngraph/LICENSE', sysroot_license_dir / 'ngraph-LICENSE')
copytree(self.sysrootdir / 'tbb/LICENSE', sysroot_license_dir / 'tbb-LICENSE')
+504
View File
@@ -0,0 +1,504 @@
#!/usr/bin/env python
import os, sys
import argparse
import glob
import re
import shutil
import subprocess
import time
import logging as log
if sys.version_info[0] == 2:
sys.exit("FATAL: Python 2.x is not supported")
from pathlib import Path
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
class Fail(Exception):
def __init__(self, text=None):
self.t = text
def __str__(self):
return "ERROR" if self.t is None else self.t
def execute(cmd, cwd=None, shell=False):
try:
log.debug("Executing: %s" % cmd)
log.info('Executing: ' + ' '.join(cmd))
if cwd:
log.info(" in: %s" % cwd)
retcode = subprocess.call(cmd, shell=shell, cwd=str(cwd) if cwd else None)
if retcode < 0:
raise Fail("Child was terminated by signal: %s" % -retcode)
elif retcode > 0:
raise Fail("Child returned: %s" % retcode)
except OSError as e:
raise Fail("Execution failed: %d / %s" % (e.errno, e.strerror))
def check_executable(cmd):
try:
log.debug("Executing: %s" % cmd)
result = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
if not isinstance(result, str):
result = result.decode("utf-8")
log.debug("Result: %s" % (result + '\n').split('\n')[0])
return True
except OSError as e:
log.debug('Failed: %s' % e)
return False
def rm_one(d):
d = str(d) # Python 3.5 may not handle Path
d = os.path.abspath(d)
if os.path.exists(d):
if os.path.isdir(d):
log.info("Removing dir: %s", d)
shutil.rmtree(d)
elif os.path.isfile(d):
log.info("Removing file: %s", d)
os.remove(d)
def prepare_dir(d, clean=False):
d = str(d) # Python 3.5 may not handle Path
d = os.path.abspath(d)
log.info("Preparing directory: '%s' (clean: %r)", d, clean)
if os.path.exists(d):
if not os.path.isdir(d):
raise Fail("Not a directory: %s" % d)
if clean:
for item in os.listdir(d):
rm_one(os.path.join(d, item))
else:
os.makedirs(d)
return Path(d)
def check_dir(d):
d = str(d) # Python 3.5 may not handle Path
d = os.path.abspath(d)
log.info("Check directory: '%s'", d)
if os.path.exists(d):
if not os.path.isdir(d):
raise Fail("Not a directory: %s" % d)
else:
raise Fail("The directory is missing: %s" % d)
return Path(d)
# shutil.copytree fails if dst exists
def copytree(src, dst, exclude=None):
log.debug('copytree(%s, %s)', src, dst)
src = str(src) # Python 3.5 may not handle Path
dst = str(dst) # Python 3.5 may not handle Path
if os.path.isfile(src):
shutil.copy2(src, dst)
return
def copy_recurse(subdir):
if exclude and subdir in exclude:
log.debug(' skip: %s', subdir)
return
s = os.path.join(src, subdir)
d = os.path.join(dst, subdir)
if os.path.exists(d) or exclude:
if os.path.isfile(s):
shutil.copy2(s, d)
elif os.path.isdir(s):
if not os.path.isdir(d):
os.makedirs(d)
for item in os.listdir(s):
copy_recurse(os.path.join(subdir, item))
else:
assert False, s + " => " + d
else:
if os.path.isfile(s):
shutil.copy2(s, d)
elif os.path.isdir(s):
shutil.copytree(s, d)
else:
assert False, s + " => " + d
copy_recurse('')
def git_checkout(dst, url, branch, revision, clone_extra_args, noFetch=False):
assert isinstance(dst, Path)
log.info("Git checkout: '%s' (%s @ %s)", dst, url, revision)
if noFetch:
pass
elif not os.path.exists(str(dst / '.git')):
execute(cmd=['git', 'clone'] +
(['-b', branch] if branch else []) +
clone_extra_args + [url, '.'], cwd=dst)
else:
execute(cmd=['git', 'fetch', 'origin'] + ([branch] if branch else []), cwd=dst)
execute(cmd=['git', 'reset', '--hard'], cwd=dst)
execute(cmd=['git', 'checkout', '-B', 'winpack_dldt', revision], cwd=dst)
execute(cmd=['git', 'clean', '-f', '-d'], cwd=dst)
execute(cmd=['git', 'submodule', 'init'], cwd=dst)
execute(cmd=['git', 'submodule', 'update', '--force', '--depth=1000'], cwd=dst)
log.info("Git checkout: DONE")
execute(cmd=['git', 'status'], cwd=dst)
execute(cmd=['git', 'log', '--max-count=1', 'HEAD'], cwd=dst)
def git_apply_patch(src_dir, patch_file):
src_dir = str(src_dir) # Python 3.5 may not handle Path
patch_file = str(patch_file) # Python 3.5 may not handle Path
assert os.path.exists(patch_file), patch_file
execute(cmd=['git', 'apply', '--3way', '-v', '--ignore-space-change', str(patch_file)], cwd=src_dir)
#===================================================================================================
class BuilderDLDT:
def __init__(self, config):
self.config = config
cpath = self.config.dldt_config
log.info('DLDT build configration: %s', cpath)
if not os.path.exists(cpath):
cpath = os.path.join(SCRIPT_DIR, cpath)
if not os.path.exists(cpath):
raise Fail('Config "%s" is missing' % cpath)
self.cpath = Path(cpath)
clean_src_dir = self.config.clean_dldt
if self.config.dldt_src_dir:
assert os.path.exists(self.config.dldt_src_dir), self.config.dldt_src_dir
dldt_dir_name = 'dldt-custom'
self.srcdir = self.config.dldt_src_dir
clean_src_dir = False
else:
assert not self.config.dldt_src_dir
self.init_patchset()
dldt_dir_name = 'dldt-' + self.config.dldt_src_commit + \
('/patch-' + self.patch_hashsum if self.patch_hashsum else '')
if self.config.build_debug:
dldt_dir_name += '-debug'
self.srcdir = None # updated below
log.info('DLDT directory: %s', dldt_dir_name)
self.outdir = prepare_dir(os.path.join(self.config.build_cache_dir, dldt_dir_name))
if self.srcdir is None:
self.srcdir = prepare_dir(self.outdir / 'sources', clean=clean_src_dir)
self.build_dir = prepare_dir(self.outdir / 'build', clean=self.config.clean_dldt)
self.sysrootdir = prepare_dir(self.outdir / 'sysroot', clean=self.config.clean_dldt)
def init_patchset(self):
cpath = self.cpath
self.patch_file = str(cpath / 'patch.config.py') # Python 3.5 may not handle Path
with open(self.patch_file, 'r') as f:
self.patch_file_contents = f.read()
patch_hashsum = None
try:
import hashlib
patch_hashsum = hashlib.md5(self.patch_file_contents.encode('utf-8')).hexdigest()
except:
log.warn("Can't compute hashsum of patches: %s", self.patch_file)
self.patch_hashsum = patch_hashsum
def prepare_sources(self):
if self.config.dldt_src_dir:
log.info('Using DLDT custom repository: %s', self.srcdir)
return
def do_clone(srcdir, noFetch):
git_checkout(srcdir, self.config.dldt_src_url, self.config.dldt_src_branch, self.config.dldt_src_commit,
['-n', '--depth=100', '--recurse-submodules'] +
(self.config.dldt_src_git_clone_extra or []),
noFetch=noFetch
)
if not os.path.exists(str(self.srcdir / '.git')):
log.info('DLDT git checkout through "reference" copy.')
reference_dir = self.config.dldt_reference_dir
if reference_dir is None:
reference_dir = prepare_dir(os.path.join(self.config.build_cache_dir, 'dldt-git-reference-repository'))
do_clone(reference_dir, False)
log.info('DLDT reference git checkout completed. Copying...')
else:
log.info('Using DLDT reference repository. Copying...')
copytree(reference_dir, self.srcdir)
do_clone(self.srcdir, True)
else:
do_clone(self.srcdir, False)
log.info('DLDT git checkout completed. Patching...')
def applyPatch(patch_file, subdir = None):
if subdir:
log.info('Patching "%s": %s' % (subdir, patch_file))
else:
log.info('Patching: %s' % (patch_file))
git_apply_patch(self.srcdir / subdir if subdir else self.srcdir, self.cpath / patch_file)
exec(compile(self.patch_file_contents, self.patch_file, 'exec'))
log.info('DLDT patches applied')
def build(self):
self.cmake_path = 'cmake'
build_config = 'Release' if not self.config.build_debug else 'Debug'
cmd = [self.cmake_path, '-G', 'Visual Studio 16 2019', '-A', 'x64']
cmake_vars = dict(
CMAKE_BUILD_TYPE=build_config,
ENABLE_SAMPLES='OFF',
ENABLE_TESTS='OFF',
BUILD_TESTS='OFF',
ENABLE_OPENCV='OFF',
ENABLE_GNA='OFF',
NGRAPH_UNIT_TEST_ENABLE='OFF',
CMAKE_INSTALL_PREFIX=str(self.build_dir / 'install'),
)
cmd += [ '-D%s=%s' % (k, v) for (k, v) in cmake_vars.items() if v is not None]
if self.config.cmake_option_dldt:
cmd += self.config.cmake_option_dldt
cmd.append(str(self.srcdir))
execute(cmd, cwd=self.build_dir)
# build
cmd = [self.cmake_path, '--build', '.', '--config', build_config, # '--target', 'install',
'--', '/v:n', '/m:2', '/consoleloggerparameters:NoSummary'
]
execute(cmd, cwd=self.build_dir)
# install ngraph only
cmd = [self.cmake_path, '-DBUILD_TYPE=' + build_config, '-P', 'cmake_install.cmake']
execute(cmd, cwd=self.build_dir / 'ngraph')
log.info('DLDT build completed')
def make_sysroot(self):
cfg_file = str(self.cpath / 'sysroot.config.py') # Python 3.5 may not handle Path
with open(cfg_file, 'r') as f:
cfg = f.read()
exec(compile(cfg, cfg_file, 'exec'))
log.info('DLDT sysroot preparation completed')
#===================================================================================================
class Builder:
def __init__(self, config):
self.config = config
build_dir_name = 'opencv_build' if not self.config.build_debug else 'opencv_build_debug'
self.build_dir = prepare_dir(Path(self.config.output_dir) / build_dir_name, clean=self.config.clean_opencv)
self.package_dir = prepare_dir(Path(self.config.output_dir) / 'package/opencv', clean=True)
self.install_dir = prepare_dir(self.package_dir / 'build')
self.src_dir = check_dir(self.config.opencv_dir)
def build(self, builderDLDT):
self.cmake_path = 'cmake'
build_config = 'Release' if not self.config.build_debug else 'Debug'
cmd = [self.cmake_path, '-G', 'Visual Studio 16 2019', '-A', 'x64']
cmake_vars = dict(
CMAKE_BUILD_TYPE=build_config,
INSTALL_CREATE_DISTRIB='ON',
BUILD_opencv_world='OFF',
BUILD_TESTS='OFF',
BUILD_PERF_TESTS='OFF',
ENABLE_CXX11='ON',
WITH_INF_ENGINE='ON',
INF_ENGINE_RELEASE=str(self.config.dldt_release),
WITH_TBB='ON',
CPU_BASELINE='AVX2',
CMAKE_INSTALL_PREFIX=str(self.install_dir),
INSTALL_PDB='ON',
INSTALL_PDB_COMPONENT_EXCLUDE_FROM_ALL='OFF',
OPENCV_SKIP_CMAKE_ROOT_CONFIG='ON',
OPENCV_BIN_INSTALL_PATH='bin',
OPENCV_INCLUDE_INSTALL_PATH='include',
OPENCV_LIB_INSTALL_PATH='lib',
OPENCV_CONFIG_INSTALL_PATH='cmake',
OPENCV_3P_LIB_INSTALL_PATH='3rdparty',
OPENCV_SAMPLES_SRC_INSTALL_PATH='samples',
OPENCV_DOC_INSTALL_PATH='doc',
OPENCV_OTHER_INSTALL_PATH='etc',
OPENCV_LICENSES_INSTALL_PATH='etc/licenses',
OPENCV_INSTALL_DATA_DIR_RELATIVE='../../src/opencv',
BUILD_opencv_python2='OFF',
BUILD_opencv_python3='ON',
PYTHON3_LIMITED_API='ON',
OPENCV_PYTHON_INSTALL_PATH='python',
)
cmake_vars['INF_ENGINE_LIB_DIRS:PATH'] = str(builderDLDT.sysrootdir / 'deployment_tools/inference_engine/lib/intel64')
cmake_vars['INF_ENGINE_INCLUDE_DIRS:PATH'] = str(builderDLDT.sysrootdir / 'deployment_tools/inference_engine/include')
cmake_vars['ngraph_DIR:PATH'] = str(builderDLDT.sysrootdir / 'ngraph/cmake')
cmake_vars['TBB_DIR:PATH'] = str(builderDLDT.sysrootdir / 'tbb/cmake')
if self.config.build_debug:
cmake_vars['CMAKE_BUILD_TYPE'] = 'Debug'
cmake_vars['BUILD_opencv_python3'] ='OFF' # python3x_d.lib is missing
cmake_vars['OPENCV_INSTALL_APPS_LIST'] = 'all'
if self.config.build_tests:
cmake_vars['BUILD_TESTS'] = 'ON'
cmake_vars['BUILD_PERF_TESTS'] = 'ON'
cmake_vars['BUILD_opencv_ts'] = 'ON'
cmake_vars['INSTALL_TESTS']='ON'
if self.config.build_tests_dnn:
cmake_vars['BUILD_TESTS'] = 'ON'
cmake_vars['BUILD_PERF_TESTS'] = 'ON'
cmake_vars['BUILD_opencv_ts'] = 'ON'
cmake_vars['OPENCV_BUILD_TEST_MODULES_LIST'] = 'dnn'
cmake_vars['OPENCV_BUILD_PERF_TEST_MODULES_LIST'] = 'dnn'
cmake_vars['INSTALL_TESTS']='ON'
cmd += [ "-D%s=%s" % (k, v) for (k, v) in cmake_vars.items() if v is not None]
if self.config.cmake_option:
cmd += self.config.cmake_option
cmd.append(str(self.src_dir))
log.info('Configuring OpenCV...')
execute(cmd, cwd=self.build_dir)
log.info('Building OpenCV...')
# build
cmd = [self.cmake_path, '--build', '.', '--config', build_config, '--target', 'install',
'--', '/v:n', '/m:2', '/consoleloggerparameters:NoSummary'
]
execute(cmd, cwd=self.build_dir)
log.info('OpenCV build/install completed')
def copy_sysroot(self, builderDLDT):
log.info('Copy sysroot files')
copytree(builderDLDT.sysrootdir / 'bin', self.install_dir / 'bin')
copytree(builderDLDT.sysrootdir / 'etc', self.install_dir / 'etc')
log.info('Copy sysroot files - DONE')
def package_sources(self):
package_opencv = prepare_dir(self.package_dir / 'src/opencv', clean=True)
package_opencv = str(package_opencv) # Python 3.5 may not handle Path
execute(cmd=['git', 'clone', '-s', str(self.src_dir), '.'], cwd=str(package_opencv))
for item in os.listdir(package_opencv):
if str(item).startswith('.git'):
rm_one(os.path.join(package_opencv, item))
with open(str(self.package_dir / 'README.md'), 'w') as f:
f.write('See licensing/copying statements in "build/etc/licenses"\n')
f.write('Wiki page: https://github.com/opencv/opencv/wiki/Intel%27s-Deep-Learning-Inference-Engine-backend\n')
log.info('Package OpenCV sources - DONE')
#===================================================================================================
def main():
dldt_src_url = 'https://github.com/opencv/dldt.git'
dldt_src_commit = '2020.1'
dldt_release = '2020010000'
build_cache_dir_default = os.environ.get('BUILD_CACHE_DIR', '.build_cache')
parser = argparse.ArgumentParser(
description='Build OpenCV Windows package with Inference Engine (DLDT)',
)
parser.add_argument('output_dir', nargs='?', default='.', help='Output directory')
parser.add_argument('opencv_dir', nargs='?', default=os.path.join(SCRIPT_DIR, '../..'), help='Path to OpenCV source dir')
parser.add_argument('--build_cache_dir', default=build_cache_dir_default, help='Build cache directory (sources and binaries cache of build dependencies, default = "%s")' % build_cache_dir_default)
parser.add_argument('--cmake_option', action='append', help='Append OpenCV CMake option')
parser.add_argument('--cmake_option_dldt', action='append', help='Append CMake option for DLDT project')
parser.add_argument('--clean_dldt', action='store_true', help='Clear DLDT build and sysroot directories')
parser.add_argument('--clean_opencv', action='store_true', help='Clear OpenCV build directory')
parser.add_argument('--build_debug', action='store_true', help='Build debug binaries')
parser.add_argument('--build_tests', action='store_true', help='Build OpenCV tests')
parser.add_argument('--build_tests_dnn', action='store_true', help='Build OpenCV DNN accuracy and performance tests only')
parser.add_argument('--dldt_src_url', default=dldt_src_url, help='DLDT source URL (tag / commit, default: %s)' % dldt_src_url)
parser.add_argument('--dldt_src_branch', help='DLDT checkout branch')
parser.add_argument('--dldt_src_commit', default=dldt_src_commit, help='DLDT source commit / tag (default: %s)' % dldt_src_commit)
parser.add_argument('--dldt_src_git_clone_extra', action='append', help='DLDT git clone extra args')
parser.add_argument('--dldt_release', default=dldt_release, help='DLDT release code for INF_ENGINE_RELEASE (default: %s)' % dldt_release)
parser.add_argument('--dldt_reference_dir', help='DLDT reference git repository (optional)')
parser.add_argument('--dldt_src_dir', help='DLDT custom source repository (skip git checkout and patching, use for TESTING only)')
parser.add_argument('--dldt_config', help='Specify DLDT build configuration (defaults to DLDT commit)')
args = parser.parse_args()
log.basicConfig(
format='%(asctime)s %(levelname)-8s %(message)s',
level=os.environ.get('LOGLEVEL', 'INFO'),
datefmt='%Y-%m-%d %H:%M:%S'
)
log.debug('Args: %s', args)
if not check_executable(['git', '--version']):
sys.exit("FATAL: 'git' is not available")
if not check_executable(['cmake', '--version']):
sys.exit("FATAL: 'cmake' is not available")
if os.path.realpath(args.output_dir) == os.path.realpath(SCRIPT_DIR):
raise Fail("Specify output_dir (building from script directory is not supported)")
if os.path.realpath(args.output_dir) == os.path.realpath(args.opencv_dir):
raise Fail("Specify output_dir (building from OpenCV source directory is not supported)")
# Relative paths become invalid in sub-directories
if args.opencv_dir is not None and not os.path.isabs(args.opencv_dir):
args.opencv_dir = os.path.abspath(args.opencv_dir)
if not args.dldt_config:
args.dldt_config = args.dldt_src_commit
_opencv_dir = check_dir(args.opencv_dir)
_outdir = prepare_dir(args.output_dir)
_cachedir = prepare_dir(args.build_cache_dir)
ocv_hooks_dir = os.environ.get('OPENCV_CMAKE_HOOKS_DIR', None)
hooks_dir = os.path.join(SCRIPT_DIR, 'cmake-opencv-checks')
os.environ['OPENCV_CMAKE_HOOKS_DIR'] = hooks_dir if ocv_hooks_dir is None else (hooks_dir + ';' + ocv_hooks_dir)
builder_dldt = BuilderDLDT(args)
builder_dldt.prepare_sources()
builder_dldt.build()
builder_dldt.make_sysroot()
builder_opencv = Builder(args)
builder_opencv.build(builder_dldt)
builder_opencv.copy_sysroot(builder_dldt)
builder_opencv.package_sources()
log.info("=====")
log.info("===== Build finished")
log.info("=====")
if __name__ == "__main__":
try:
main()
except:
log.info('FATAL: Error occured. To investigate problem try to change logging level using LOGLEVEL=DEBUG environment variable.')
raise
@@ -0,0 +1,17 @@
message(STATUS "Winpack-DLDT: Validating OpenCV build configuration...")
if(NOT INF_ENGINE_TARGET)
message(SEND_ERROR "Inference engine must be detected")
set(HAS_ERROR 1)
endif()
if(NOT HAVE_NGRAPH)
message(SEND_ERROR "Inference engine nGraph must be detected")
set(HAS_ERROR 1)
endif()
if(HAS_ERROR)
ocv_cmake_dump_vars("^IE_|INF_|INFERENCE|ngraph")
message(FATAL_ERROR "Winpack-DLDT: Validating OpenCV build configuration... FAILED")
endif()
message(STATUS "Winpack-DLDT: Validating OpenCV build configuration... DONE")
@@ -0,0 +1,13 @@
import sys
print(sys.version_info)
try:
import cv2 as cv
print(cv.__version__)
print(cv.dnn.getAvailableTargets(cv.dnn.DNN_BACKEND_INFERENCE_ENGINE))
except:
print(sys.path)
import os
print(os.environ.get('PATH', ''))
raise
print('OK')
+36 -9
View File
@@ -4,16 +4,24 @@
:: - > _winpack_build_sample.cmd cpp\opencv_version.cpp
:: Requires:
:: - CMake
:: - MSVS 2015/2017
:: - MSVS 2015/2017/2019
:: (tools are searched on default paths or environment should be pre-configured)
@echo off
setlocal
set SCRIPTDIR=%~dp0
if NOT exist "%SCRIPTDIR%\..\..\build" (
SET SCRIPT_DIR=%~dp0
SET "OPENCV_SETUPVARS_SCRIPT=setup_vars_opencv4.cmd"
SET "PACKAGE_BUILD_DIR=%SCRIPT_DIR%\..\..\build"
IF NOT EXIST "%PACKAGE_BUILD_DIR%\%OPENCV_SETUPVARS_SCRIPT%" (
:: Winpack DLDT
SET "PACKAGE_BUILD_DIR=%SCRIPT_DIR%\..\..\..\build"
)
IF NOT EXIST "%PACKAGE_BUILD_DIR%\%OPENCV_SETUPVARS_SCRIPT%" (
set "MSG=OpenCV Winpack installation is required"
goto die
)
:: normalize path
for %%i in ("%PACKAGE_BUILD_DIR%") do SET "PACKAGE_BUILD_DIR=%%~fi"
if [%1]==[] (
set "MSG=Sample path is required"
@@ -35,8 +43,8 @@ set "SRC_NAME=%~n1"
echo SRC_NAME=%SRC_NAME%
echo ================================================================================
:: Path to FFMPEG binary files
set "PATH=%PATH%;%SCRIPTDIR%\..\..\build\bin\"
:: Path to root 'bin' dir
set "PATH=%PACKAGE_BUILD_DIR%\bin;%PATH%"
:: Detect compiler
cl /? >NUL 2>NUL <NUL
@@ -102,12 +110,21 @@ if NOT DEFINED VisualStudioVersion (
if "%VisualStudioVersion%" == "14.0" (
set "CMAKE_GENERATOR=-G^"Visual Studio 14 Win64^""
set "BUILD_DIR_SUFFIX=.vc14"
set "PATH=%PATH%;%SCRIPTDIR%\..\..\build\x64\vc14\bin\"
if EXIST "%PACKAGE_BUILD_DIR%\x64\vc14\bin" (
set "PATH=%PACKAGE_BUILD_DIR%\x64\vc14\bin;%PATH%"
)
) else (
if "%VisualStudioVersion%" == "15.0" (
set "CMAKE_GENERATOR=-G^"Visual Studio 15 Win64^""
set "BUILD_DIR_SUFFIX=.vc15"
set "PATH=%PATH%;%SCRIPTDIR%\..\..\build\x64\vc15\bin\"
if EXIST "%PACKAGE_BUILD_DIR%\x64\vc15\bin" (
set "PATH=%PACKAGE_BUILD_DIR%\x64\vc15\bin;%PATH%"
) else (
if EXIST "%PACKAGE_BUILD_DIR%\x64\vc14\bin" (
set "PATH=%PACKAGE_BUILD_DIR%\x64\vc14\bin;%PATH%"
)
)
) else (
if "%VisualStudioVersion%" == "16.0" (
echo.==========================================
@@ -115,7 +132,17 @@ if "%VisualStudioVersion%" == "14.0" (
echo.==========================================
set "CMAKE_GENERATOR=-G^"Visual Studio 16 2019^" -A x64"
set "BUILD_DIR_SUFFIX=.vc16"
set "PATH=%PATH%;%SCRIPTDIR%\..\..\build\x64\vc15\bin\"
if EXIST "%PACKAGE_BUILD_DIR%\x64\vc16\bin" (
set "PATH=%PACKAGE_BUILD_DIR%\x64\vc16\bin;%PATH%"
) else (
if EXIST "%PACKAGE_BUILD_DIR%\x64\vc15\bin" (
set "PATH=%PACKAGE_BUILD_DIR%\x64\vc15\bin;%PATH%"
) else (
if EXIST "%PACKAGE_BUILD_DIR%\x64\vc14\bin" (
set "PATH=%PACKAGE_BUILD_DIR%\x64\vc14\bin;%PATH%"
)
)
)
) else (
set "MSG=Unsupported MSVS version. VisualStudioVersion=%VisualStudioVersion%"
goto die
@@ -128,10 +155,10 @@ call :set_title Create build directory
if NOT exist "%BUILD_DIR%" ( call :execute md "%BUILD_DIR%" )
PUSHD "%BUILD_DIR%"
if NOT exist "%BUILD_DIR%/sample" ( call :execute md "%BUILD_DIR%/sample" )
call :execute copy /Y "%SCRIPTDIR%/CMakeLists.example.in" "%BUILD_DIR%/sample/CMakeLists.txt"
call :execute copy /Y "%SCRIPT_DIR%/CMakeLists.example.in" "%BUILD_DIR%/sample/CMakeLists.txt"
call :set_title Configuring via CMake
call :execute cmake %CMAKE_GENERATOR% "%BUILD_DIR%\sample" -DEXAMPLE_NAME=%SRC_NAME% "-DEXAMPLE_FILE=%SRC_FILENAME%" "-DOpenCV_DIR=%SCRIPTDIR%\..\..\build"
call :execute cmake %CMAKE_GENERATOR% "%BUILD_DIR%\sample" -DEXAMPLE_NAME=%SRC_NAME% "-DEXAMPLE_FILE=%SRC_FILENAME%"
if %ERRORLEVEL% NEQ 0 (
set "MSG=CMake configuration step failed: %BUILD_DIR%"
goto die
+21 -3
View File
@@ -2,11 +2,19 @@
SETLOCAL
SET SCRIPT_DIR=%~dp0
IF NOT EXIST "%SCRIPT_DIR%\..\..\build\setup_vars_opencv4.cmd" (
SET "OPENCV_SETUPVARS_SCRIPT=setup_vars_opencv4.cmd"
SET "BUILD_DIR=%SCRIPT_DIR%\..\..\build"
IF NOT EXIST "%BUILD_DIR%\%OPENCV_SETUPVARS_SCRIPT%" (
:: Winpack DLDT
SET "BUILD_DIR=%SCRIPT_DIR%\..\..\..\build"
)
IF NOT EXIST "%BUILD_DIR%\%OPENCV_SETUPVARS_SCRIPT%" (
ECHO ERROR: OpenCV Winpack installation is required
pause
exit
)
:: normalize path
for %%i in ("%PACKAGE_BUILD_DIR%") do SET "PACKAGE_BUILD_DIR=%%~fi"
:: Detect Python binary
python -V 2>nul
@@ -80,7 +88,11 @@ echo SRC_FILENAME=%SRC_FILENAME%
call :dirname "%SRC_FILENAME%" SRC_DIR
call :dirname "%PYTHON%" PYTHON_DIR
PUSHD %SRC_DIR%
CALL "%SCRIPT_DIR%\..\..\build\setup_vars_opencv4.cmd"
CALL "%BUILD_DIR%\%OPENCV_SETUPVARS_SCRIPT%"
:: repair SCRIPT_DIR
SET "SCRIPT_DIR=%~dp0"
ECHO Run: %*
%PYTHON% %*
SET result=%errorlevel%
@@ -94,17 +106,23 @@ IF %result% NEQ 0 (
cmd /k echo Current directory: %CD%
)
)
POPD
EXIT /B %result%
:rundemo
PUSHD "%SCRIPT_DIR%\python"
CALL "%SCRIPT_DIR%\..\..\build\setup_vars_opencv4.cmd"
CALL "%BUILD_DIR%\%OPENCV_SETUPVARS_SCRIPT%"
:: repair SCRIPT_DIR
SET "SCRIPT_DIR=%~dp0"
%PYTHON% demo.py
SET result=%errorlevel%
IF %result% NEQ 0 (
IF NOT DEFINED OPENCV_BATCH_MODE ( pause )
)
POPD
EXIT /B %result%
+17 -5
View File
@@ -114,12 +114,24 @@ class App:
def on_demo_select(self, evt):
name = self.demos_lb.get( self.demos_lb.curselection()[0] )
fn = self.samples[name]
loc = {}
descr = ""
try:
execfile(fn, loc) # Python 2
except NameError:
exec(open(fn).read(), loc) # Python 3
descr = loc.get('__doc__', 'no-description')
if sys.version_info[0] > 2:
# Python 3.x
module_globals = {}
module_locals = {}
with open(fn, 'r') as f:
module_code = f.read()
exec(compile(module_code, fn, 'exec'), module_globals, module_locals)
descr = module_locals.get('__doc__', 'no-description')
else:
# Python 2
module_globals = {}
execfile(fn, module_globals) # noqa: F821
descr = module_globals.get('__doc__', 'no-description')
except Exception as e:
descr = str(e)
self.linker.reset()
self.text.config(state='normal')