Merge remote-tracking branch 'upstream/3.4' into merge-3.4

This commit is contained in:
Alexander Alekhin 2019-03-22 19:31:31 +03:00
commit 8c25a8eb7b
67 changed files with 1221 additions and 682 deletions

View File

@ -715,7 +715,7 @@ if(UNIX)
CHECK_INCLUDE_FILE(pthread.h HAVE_PTHREAD) CHECK_INCLUDE_FILE(pthread.h HAVE_PTHREAD)
if(ANDROID) if(ANDROID)
set(OPENCV_LINKER_LIBS ${OPENCV_LINKER_LIBS} dl m log) set(OPENCV_LINKER_LIBS ${OPENCV_LINKER_LIBS} dl m log)
elseif(${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD|NetBSD|DragonFly|OpenBSD|Haiku") elseif(CMAKE_SYSTEM_NAME MATCHES "FreeBSD|NetBSD|DragonFly|OpenBSD|Haiku")
set(OPENCV_LINKER_LIBS ${OPENCV_LINKER_LIBS} m pthread) set(OPENCV_LINKER_LIBS ${OPENCV_LINKER_LIBS} m pthread)
elseif(EMSCRIPTEN) elseif(EMSCRIPTEN)
# no need to link to system libs with emscripten # no need to link to system libs with emscripten

View File

@ -296,11 +296,18 @@ endif()
# workaround gcc bug for aligned ld/st # workaround gcc bug for aligned ld/st
# https://github.com/opencv/opencv/issues/13211 # https://github.com/opencv/opencv/issues/13211
if((PPC64LE AND NOT CMAKE_CROSSCOMPILING) OR OPENCV_FORCE_COMPILER_CHECK_VSX_ALIGNED) if((PPC64LE AND NOT CMAKE_CROSSCOMPILING) OR OPENCV_FORCE_COMPILER_CHECK_VSX_ALIGNED)
ocv_check_runtime_flag("${CPU_BASELINE_FLAGS}" "OPENCV_CHECK_VSX_ALIGNED" "${OpenCV_SOURCE_DIR}/cmake/checks/runtime/cpu_vsx_aligned.cpp") ocv_check_runtime_flag("${CPU_BASELINE_FLAGS}" OPENCV_CHECK_VSX_ALIGNED "${OpenCV_SOURCE_DIR}/cmake/checks/runtime/cpu_vsx_aligned.cpp")
if(NOT OPENCV_CHECK_VSX_ALIGNED) if(NOT OPENCV_CHECK_VSX_ALIGNED)
add_extra_compiler_option_force(-DCV_COMPILER_VSX_BROKEN_ALIGNED) add_extra_compiler_option_force(-DCV_COMPILER_VSX_BROKEN_ALIGNED)
endif() endif()
endif() endif()
# validate inline asm with fixes register number and constraints wa, wd, wf
if(PPC64LE)
ocv_check_compiler_flag(CXX "${CPU_BASELINE_FLAGS}" OPENCV_CHECK_VSX_ASM "${OpenCV_SOURCE_DIR}/cmake/checks/cpu_vsx_asm.cpp")
if(NOT OPENCV_CHECK_VSX_ASM)
add_extra_compiler_option_force(-DCV_COMPILER_VSX_BROKEN_ASM)
endif()
endif()
# combine all "extra" options # combine all "extra" options
if(NOT OPENCV_SKIP_EXTRA_COMPILER_FLAGS) if(NOT OPENCV_SKIP_EXTRA_COMPILER_FLAGS)

View File

@ -1,7 +1,6 @@
# The script detects Intel(R) Inference Engine installation # The script detects Intel(R) Inference Engine installation
# #
# Cache variables: # Cache variables:
# INF_ENGINE_OMP_DIR - directory with OpenMP library to link with (needed by some versions of IE)
# INF_ENGINE_RELEASE - a number reflecting IE source interface (linked with OpenVINO release) # INF_ENGINE_RELEASE - a number reflecting IE source interface (linked with OpenVINO release)
# #
# Detect parameters: # Detect parameters:
@ -11,8 +10,8 @@
# - INF_ENGINE_INCLUDE_DIRS - headers search location # - INF_ENGINE_INCLUDE_DIRS - headers search location
# - INF_ENGINE_LIB_DIRS - library search location # - INF_ENGINE_LIB_DIRS - library search location
# 3. OpenVINO location: # 3. OpenVINO location:
# - environment variable INTEL_CVSDK_DIR is set to location of OpenVINO installation dir # - environment variable INTEL_OPENVINO_DIR is set to location of OpenVINO installation dir
# - INF_ENGINE_PLATFORM - part of name of library directory representing its platform (default ubuntu_16.04) # - INF_ENGINE_PLATFORM - part of name of library directory representing its platform
# #
# Result: # Result:
# INF_ENGINE_TARGET - set to name of imported library target representing InferenceEngine # INF_ENGINE_TARGET - set to name of imported library target representing InferenceEngine
@ -36,11 +35,13 @@ function(add_custom_ie_build _inc _lib _lib_rel _lib_dbg _msg)
IMPORTED_IMPLIB_DEBUG "${_lib_dbg}" IMPORTED_IMPLIB_DEBUG "${_lib_dbg}"
INTERFACE_INCLUDE_DIRECTORIES "${_inc}" INTERFACE_INCLUDE_DIRECTORIES "${_inc}"
) )
find_library(omp_lib iomp5 PATHS "${INF_ENGINE_OMP_DIR}" NO_DEFAULT_PATH) if(NOT INF_ENGINE_RELEASE VERSION_GREATER "2018050000")
if(NOT omp_lib) find_library(INF_ENGINE_OMP_LIBRARY iomp5 PATHS "${INF_ENGINE_OMP_DIR}" NO_DEFAULT_PATH)
message(WARNING "OpenMP for IE have not been found. Set INF_ENGINE_OMP_DIR variable if you experience build errors.") if(NOT INF_ENGINE_OMP_LIBRARY)
else() message(WARNING "OpenMP for IE have not been found. Set INF_ENGINE_OMP_DIR variable if you experience build errors.")
set_target_properties(inference_engine PROPERTIES IMPORTED_LINK_INTERFACE_LIBRARIES "${omp_lib}") else()
set_target_properties(inference_engine PROPERTIES IMPORTED_LINK_INTERFACE_LIBRARIES "${INF_ENGINE_OMP_LIBRARY}")
endif()
endif() endif()
set(INF_ENGINE_VERSION "Unknown" CACHE STRING "") set(INF_ENGINE_VERSION "Unknown" CACHE STRING "")
set(INF_ENGINE_TARGET inference_engine PARENT_SCOPE) set(INF_ENGINE_TARGET inference_engine PARENT_SCOPE)
@ -64,9 +65,17 @@ if(NOT INF_ENGINE_TARGET AND INF_ENGINE_LIB_DIRS AND INF_ENGINE_INCLUDE_DIRS)
add_custom_ie_build("${ie_custom_inc}" "${ie_custom_lib}" "${ie_custom_lib_rel}" "${ie_custom_lib_dbg}" "INF_ENGINE_{INCLUDE,LIB}_DIRS") add_custom_ie_build("${ie_custom_inc}" "${ie_custom_lib}" "${ie_custom_lib_rel}" "${ie_custom_lib_dbg}" "INF_ENGINE_{INCLUDE,LIB}_DIRS")
endif() endif()
set(_loc "$ENV{INTEL_CVSDK_DIR}") set(_loc "$ENV{INTEL_OPENVINO_DIR}")
if(NOT _loc AND DEFINED ENV{INTEL_CVSDK_DIR})
set(_loc "$ENV{INTEL_CVSDK_DIR}") # OpenVINO 2018.x
endif()
if(NOT INF_ENGINE_TARGET AND _loc) if(NOT INF_ENGINE_TARGET AND _loc)
set(INF_ENGINE_PLATFORM "ubuntu_16.04" CACHE STRING "InferenceEngine platform (library dir)") if(NOT INF_ENGINE_RELEASE VERSION_GREATER "2018050000")
set(INF_ENGINE_PLATFORM_DEFAULT "ubuntu_16.04")
else()
set(INF_ENGINE_PLATFORM_DEFAULT "")
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) find_path(ie_custom_env_inc "inference_engine.hpp" PATHS "${_loc}/deployment_tools/inference_engine/include" NO_DEFAULT_PATH)
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 "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_rel "inference_engine" PATHS "${_loc}/deployment_tools/inference_engine/lib/intel64/Release" NO_DEFAULT_PATH)

View File

@ -822,6 +822,11 @@ function(ocv_output_status msg)
message(STATUS "${msg}") message(STATUS "${msg}")
string(REPLACE "\\" "\\\\" msg "${msg}") string(REPLACE "\\" "\\\\" msg "${msg}")
string(REPLACE "\"" "\\\"" msg "${msg}") string(REPLACE "\"" "\\\"" msg "${msg}")
string(REGEX REPLACE "^\n+|\n+$" "" msg "${msg}")
if(msg MATCHES "\n")
message(WARNING "String to be inserted to version_string.inc has an unexpected line break: '${msg}'")
string(REPLACE "\n" "\\n" msg "${msg}")
endif()
set(OPENCV_BUILD_INFO_STR "${OPENCV_BUILD_INFO_STR}\"${msg}\\n\"\n" CACHE INTERNAL "") set(OPENCV_BUILD_INFO_STR "${OPENCV_BUILD_INFO_STR}\"${msg}\\n\"\n" CACHE INTERNAL "")
endfunction() endfunction()

View File

@ -0,0 +1,21 @@
#if defined(__VSX__)
#if defined(__PPC64__) && defined(__LITTLE_ENDIAN__)
#include <altivec.h>
#else
#error "OpenCV only supports little-endian mode"
#endif
#else
#error "VSX is not supported"
#endif
/*
* xlc and wide versions of clang don't support %x<n> in the inline asm template which fixes register number
* when using any of the register constraints wa, wd, wf
*/
int main()
{
__vector float vf;
__vector signed int vi;
__asm__ __volatile__ ("xvcvsxwsp %x0,%x1" : "=wf" (vf) : "wa" (vi));
return 0;
}

View File

@ -2,6 +2,7 @@
// https://github.com/opencv/opencv/issues/13211 // https://github.com/opencv/opencv/issues/13211
#include <altivec.h> #include <altivec.h>
#undef bool
#define vsx_ld vec_vsx_ld #define vsx_ld vec_vsx_ld
#define vsx_st vec_vsx_st #define vsx_st vec_vsx_st

View File

@ -1,6 +1,9 @@
Anisotropic image segmentation by a gradient structure tensor {#tutorial_anisotropic_image_segmentation_by_a_gst} Anisotropic image segmentation by a gradient structure tensor {#tutorial_anisotropic_image_segmentation_by_a_gst}
========================== ==========================
@prev_tutorial{tutorial_motion_deblur_filter}
@next_tutorial{tutorial_periodic_noise_removing_filter}
Goal Goal
---- ----
@ -45,28 +48,65 @@ The orientation of an anisotropic image:
Coherency: Coherency:
\f[C = \frac{\lambda_1 - \lambda_2}{\lambda_1 + \lambda_2}\f] \f[C = \frac{\lambda_1 - \lambda_2}{\lambda_1 + \lambda_2}\f]
The coherency ranges from 0 to 1. For ideal local orientation (\f$\lambda_2\f$ = 0, \f$\lambda_1\f$ > 0) it is one, for an isotropic gray value structure (\f$\lambda_1\f$ = \f$\lambda_2\f$ > 0) it is zero. The coherency ranges from 0 to 1. For ideal local orientation (\f$\lambda_2\f$ = 0, \f$\lambda_1\f$ > 0) it is one, for an isotropic gray value structure (\f$\lambda_1\f$ = \f$\lambda_2\f$ \> 0) it is zero.
Source code Source code
----------- -----------
You can find source code in the `samples/cpp/tutorial_code/ImgProc/anisotropic_image_segmentation/anisotropic_image_segmentation.cpp` of the OpenCV source code library. You can find source code in the `samples/cpp/tutorial_code/ImgProc/anisotropic_image_segmentation/anisotropic_image_segmentation.cpp` of the OpenCV source code library.
@include cpp/tutorial_code/ImgProc/anisotropic_image_segmentation/anisotropic_image_segmentation.cpp @add_toggle_cpp
@include cpp/tutorial_code/ImgProc/anisotropic_image_segmentation/anisotropic_image_segmentation.cpp
@end_toggle
@add_toggle_python
@include samples/python/tutorial_code/imgProc/anisotropic_image_segmentation/anisotropic_image_segmentation.py
@end_toggle
Explanation Explanation
----------- -----------
An anisotropic image segmentation algorithm consists of a gradient structure tensor calculation, an orientation calculation, a coherency calculation and an orientation and coherency thresholding: An anisotropic image segmentation algorithm consists of a gradient structure tensor calculation, an orientation calculation, a coherency calculation and an orientation and coherency thresholding:
@snippet samples/cpp/tutorial_code/ImgProc/anisotropic_image_segmentation/anisotropic_image_segmentation.cpp main
@add_toggle_cpp
@snippet samples/cpp/tutorial_code/ImgProc/anisotropic_image_segmentation/anisotropic_image_segmentation.cpp main
@end_toggle
@add_toggle_python
@snippet samples/python/tutorial_code/imgProc/anisotropic_image_segmentation/anisotropic_image_segmentation.py main
@end_toggle
A function calcGST() calculates orientation and coherency by using a gradient structure tensor. An input parameter w defines a window size: A function calcGST() calculates orientation and coherency by using a gradient structure tensor. An input parameter w defines a window size:
@snippet samples/cpp/tutorial_code/ImgProc/anisotropic_image_segmentation/anisotropic_image_segmentation.cpp calcGST
@add_toggle_cpp
@snippet samples/cpp/tutorial_code/ImgProc/anisotropic_image_segmentation/anisotropic_image_segmentation.cpp calcGST
@end_toggle
@add_toggle_python
@snippet samples/python/tutorial_code/imgProc/anisotropic_image_segmentation/anisotropic_image_segmentation.py calcGST
@end_toggle
The below code applies a thresholds LowThr and HighThr to image orientation and a threshold C_Thr to image coherency calculated by the previous function. LowThr and HighThr define orientation range: The below code applies a thresholds LowThr and HighThr to image orientation and a threshold C_Thr to image coherency calculated by the previous function. LowThr and HighThr define orientation range:
@snippet samples/cpp/tutorial_code/ImgProc/anisotropic_image_segmentation/anisotropic_image_segmentation.cpp thresholding
@add_toggle_cpp
@snippet samples/cpp/tutorial_code/ImgProc/anisotropic_image_segmentation/anisotropic_image_segmentation.cpp thresholding
@end_toggle
@add_toggle_python
@snippet samples/python/tutorial_code/imgProc/anisotropic_image_segmentation/anisotropic_image_segmentation.py thresholding
@end_toggle
And finally we combine thresholding results: And finally we combine thresholding results:
@snippet samples/cpp/tutorial_code/ImgProc/anisotropic_image_segmentation/anisotropic_image_segmentation.cpp combining
@add_toggle_cpp
@snippet samples/cpp/tutorial_code/ImgProc/anisotropic_image_segmentation/anisotropic_image_segmentation.cpp combining
@end_toggle
@add_toggle_python
@snippet samples/python/tutorial_code/imgProc/anisotropic_image_segmentation/anisotropic_image_segmentation.py combining
@end_toggle
Result Result
------ ------

View File

@ -1,6 +1,9 @@
Motion Deblur Filter {#tutorial_motion_deblur_filter} Motion Deblur Filter {#tutorial_motion_deblur_filter}
========================== ==========================
@prev_tutorial{tutorial_out_of_focus_deblur_filter}
@next_tutorial{tutorial_anisotropic_image_segmentation_by_a_gst}
Goal Goal
---- ----

View File

@ -2,6 +2,7 @@ Out-of-focus Deblur Filter {#tutorial_out_of_focus_deblur_filter}
========================== ==========================
@prev_tutorial{tutorial_distance_transform} @prev_tutorial{tutorial_distance_transform}
@next_tutorial{tutorial_motion_deblur_filter}
Goal Goal
---- ----

View File

@ -1,6 +1,8 @@
Periodic Noise Removing Filter {#tutorial_periodic_noise_removing_filter} Periodic Noise Removing Filter {#tutorial_periodic_noise_removing_filter}
========================== ==========================
@prev_tutorial{tutorial_anisotropic_image_segmentation_by_a_gst}
Goal Goal
---- ----

View File

@ -177,8 +177,6 @@ pattern (every view is described by several 3D-2D point correspondences).
opencv_source_code/samples/cpp/calibration.cpp opencv_source_code/samples/cpp/calibration.cpp
- A calibration sample in order to do 3D reconstruction can be found at - A calibration sample in order to do 3D reconstruction can be found at
opencv_source_code/samples/cpp/build3dmodel.cpp opencv_source_code/samples/cpp/build3dmodel.cpp
- A calibration sample of an artificially generated camera and chessboard patterns can be
found at opencv_source_code/samples/cpp/calibration_artificial.cpp
- A calibration example on stereo calibration can be found at - A calibration example on stereo calibration can be found at
opencv_source_code/samples/cpp/stereo_calib.cpp opencv_source_code/samples/cpp/stereo_calib.cpp
- A calibration example on stereo matching can be found at - A calibration example on stereo matching can be found at

View File

@ -3,7 +3,7 @@ set(the_description "The Core Functionality")
ocv_add_dispatched_file(mathfuncs_core SSE2 AVX AVX2) ocv_add_dispatched_file(mathfuncs_core SSE2 AVX AVX2)
ocv_add_dispatched_file(stat SSE4_2 AVX2) ocv_add_dispatched_file(stat SSE4_2 AVX2)
ocv_add_dispatched_file(arithm SSE2 SSE4_1 AVX2 VSX3) ocv_add_dispatched_file(arithm SSE2 SSE4_1 AVX2 VSX3)
ocv_add_dispatched_file(convert SSE2 AVX2) ocv_add_dispatched_file(convert SSE2 AVX2 VSX3)
ocv_add_dispatched_file(convert_scale SSE2 AVX2) ocv_add_dispatched_file(convert_scale SSE2 AVX2)
ocv_add_dispatched_file(count_non_zero SSE2 AVX2) ocv_add_dispatched_file(count_non_zero SSE2 AVX2)
ocv_add_dispatched_file(matmul SSE2 AVX2) ocv_add_dispatched_file(matmul SSE2 AVX2)

View File

@ -11,11 +11,6 @@
#define CV_SIMD128 1 #define CV_SIMD128 1
#define CV_SIMD128_64F 1 #define CV_SIMD128_64F 1
/**
* todo: supporting half precision for power9
* convert instractions xvcvhpsp, xvcvsphp
**/
namespace cv namespace cv
{ {
@ -1077,117 +1072,188 @@ inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) { return v_loa
inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec)
{ {
int CV_DECL_ALIGNED(32) idx[4]; const int idx[4] = {
v_store_aligned(idx, idxvec); vec_extract(idxvec.val, 0),
vec_extract(idxvec.val, 1),
vec_extract(idxvec.val, 2),
vec_extract(idxvec.val, 3)
};
return v_int32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); return v_int32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]);
} }
inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec)
{ {
int CV_DECL_ALIGNED(32) idx[4]; const int idx[4] = {
v_store_aligned(idx, idxvec); vec_extract(idxvec.val, 0),
vec_extract(idxvec.val, 1),
vec_extract(idxvec.val, 2),
vec_extract(idxvec.val, 3)
};
return v_uint32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); return v_uint32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]);
} }
inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec)
{ {
int CV_DECL_ALIGNED(32) idx[4]; const int idx[4] = {
v_store_aligned(idx, idxvec); vec_extract(idxvec.val, 0),
vec_extract(idxvec.val, 1),
vec_extract(idxvec.val, 2),
vec_extract(idxvec.val, 3)
};
return v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); return v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]);
} }
inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec)
{ {
int CV_DECL_ALIGNED(32) idx[4]; const int idx[2] = {
v_store_aligned(idx, idxvec); vec_extract(idxvec.val, 0),
vec_extract(idxvec.val, 1)
};
return v_float64x2(tab[idx[0]], tab[idx[1]]); return v_float64x2(tab[idx[0]], tab[idx[1]]);
} }
inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y)
{ {
int CV_DECL_ALIGNED(32) idx[4]; vec_float4 xy0 = vec_ld_l8(tab + vec_extract(idxvec.val, 0));
v_store_aligned(idx, idxvec); vec_float4 xy1 = vec_ld_l8(tab + vec_extract(idxvec.val, 1));
x = v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); vec_float4 xy2 = vec_ld_l8(tab + vec_extract(idxvec.val, 2));
y = v_float32x4(tab[idx[0]+1], tab[idx[1]+1], tab[idx[2]+1], tab[idx[3]+1]); vec_float4 xy3 = vec_ld_l8(tab + vec_extract(idxvec.val, 3));
vec_float4 xy02 = vec_mergeh(xy0, xy2); // x0, x2, y0, y2
vec_float4 xy13 = vec_mergeh(xy1, xy3); // x1, x3, y1, y3
x.val = vec_mergeh(xy02, xy13);
y.val = vec_mergel(xy02, xy13);
} }
inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y)
{ {
int CV_DECL_ALIGNED(32) idx[4]; vec_double2 xy0 = vsx_ld(vec_extract(idxvec.val, 0), tab);
v_store_aligned(idx, idxvec); vec_double2 xy1 = vsx_ld(vec_extract(idxvec.val, 1), tab);
x = v_float64x2(tab[idx[0]], tab[idx[1]]); x.val = vec_mergeh(xy0, xy1);
y = v_float64x2(tab[idx[0]+1], tab[idx[1]+1]); y.val = vec_mergel(xy0, xy1);
} }
inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) inline v_int8x16 v_interleave_pairs(const v_int8x16& vec)
{ {
vec_short8 vec0 = vec_mergeh((vec_short8)vec.val, (vec_short8)vec_mergesql(vec.val, vec.val)); static const vec_uchar16 perm = {0, 2, 1, 3, 4, 6, 5, 7, 8, 10, 9, 11, 12, 14, 13, 15};
vec0 = vec_mergeh(vec0, vec_mergesql(vec0, vec0)); return v_int8x16(vec_perm(vec.val, vec.val, perm));
return v_int8x16(vec_mergeh((vec_char16)vec0, (vec_char16)vec_mergesql(vec0, vec0)));
} }
inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec)
{ return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); }
inline v_int8x16 v_interleave_quads(const v_int8x16& vec) inline v_int8x16 v_interleave_quads(const v_int8x16& vec)
{ {
vec_char16 vec0 = (vec_char16)vec_mergeh((vec_int4)vec.val, (vec_int4)vec_mergesql(vec.val, vec.val)); static const vec_uchar16 perm = {0, 4, 1, 5, 2, 6, 3, 7, 8, 12, 9, 13, 10, 14, 11, 15};
return v_int8x16(vec_mergeh(vec0, vec_mergesql(vec0, vec0))); return v_int8x16(vec_perm(vec.val, vec.val, perm));
} }
inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec)
{ return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); }
inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) inline v_int16x8 v_interleave_pairs(const v_int16x8& vec)
{ {
vec_short8 vec0 = (vec_short8)vec_mergeh((vec_int4)vec.val, (vec_int4)vec_mergesql(vec.val, vec.val)); static const vec_uchar16 perm = {0,1, 4,5, 2,3, 6,7, 8,9, 12,13, 10,11, 14,15};
return v_int16x8(vec_mergeh(vec0, vec_mergesql(vec0, vec0))); return v_int16x8(vec_perm(vec.val, vec.val, perm));
} }
inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec)
{ return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); }
inline v_int16x8 v_interleave_quads(const v_int16x8& vec) inline v_int16x8 v_interleave_quads(const v_int16x8& vec)
{ {
return v_int16x8(vec_mergeh(vec.val, vec_mergesql(vec.val, vec.val))); static const vec_uchar16 perm = {0,1, 8,9, 2,3, 10,11, 4,5, 12,13, 6,7, 14,15};
return v_int16x8(vec_perm(vec.val, vec.val, perm));
} }
inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec)
{ return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); }
inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) inline v_int32x4 v_interleave_pairs(const v_int32x4& vec)
{ {
return v_int32x4(vec_mergeh(vec.val, vec_mergesql(vec.val, vec.val))); static const vec_uchar16 perm = {0,1,2,3, 8,9,10,11, 4,5,6,7, 12,13,14,15};
return v_int32x4(vec_perm(vec.val, vec.val, perm));
} }
inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec)
inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); }
inline v_float32x4 v_interleave_pairs(const v_float32x4& vec)
{ return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); }
inline v_int8x16 v_pack_triplets(const v_int8x16& vec) inline v_int8x16 v_pack_triplets(const v_int8x16& vec)
{ {
schar CV_DECL_ALIGNED(32) val[16]; static const vec_uchar16 perm = {0, 1, 2, 4, 5, 6, 8, 9, 10, 12, 13, 14, 15, 15, 15, 15};
v_store_aligned(val, vec); return v_int8x16(vec_perm(vec.val, vec.val, perm));
return v_int8x16(val[0], val[1], val[2], val[4], val[5], val[6], val[8], val[9], val[10], val[12], val[13], val[14], val[15], val[15], val[15], val[15]);
} }
inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec)
{ return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); }
inline v_int16x8 v_pack_triplets(const v_int16x8& vec) inline v_int16x8 v_pack_triplets(const v_int16x8& vec)
{ {
short CV_DECL_ALIGNED(32) val[8]; static const vec_uchar16 perm = {0,1, 2,3, 4,5, 8,9, 10,11, 12,13, 14,15, 14,15};
v_store_aligned(val, vec); return v_int16x8(vec_perm(vec.val, vec.val, perm));
return v_int16x8(val[0], val[1], val[2], val[4], val[5], val[6], val[7], val[7]);
} }
inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec)
{ return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); }
inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } inline v_int32x4 v_pack_triplets(const v_int32x4& vec)
inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } { return vec; }
inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec)
{ return vec; }
inline v_float32x4 v_pack_triplets(const v_float32x4& vec)
{ return vec; }
/////// FP16 support //////// /////// FP16 support ////////
// [TODO] implement these 2 using VSX or universal intrinsics (copy from intrin_sse.cpp and adopt)
inline v_float32x4 v_load_expand(const float16_t* ptr) inline v_float32x4 v_load_expand(const float16_t* ptr)
{ {
return v_float32x4((float)ptr[0], (float)ptr[1], (float)ptr[2], (float)ptr[3]); vec_ushort8 vf16 = vec_ld_l8((const ushort*)ptr);
#if CV_VSX3 && defined(vec_extract_fp_from_shorth)
return v_float32x4(vec_extract_fp_from_shorth(vf16));
#elif CV_VSX3 && !defined(CV_COMPILER_VSX_BROKEN_ASM)
vec_float4 vf32;
__asm__ __volatile__ ("xvcvhpsp %x0,%x1" : "=wf" (vf32) : "wa" (vec_mergeh(vf16, vf16)));
return v_float32x4(vf32);
#else
const vec_int4 z = vec_int4_z, delta = vec_int4_sp(0x38000000);
const vec_int4 signmask = vec_int4_sp(0x80000000);
const vec_int4 maxexp = vec_int4_sp(0x7c000000);
const vec_float4 deltaf = vec_float4_c(vec_int4_sp(0x38800000));
vec_int4 bits = vec_int4_c(vec_mergeh(vec_short8_c(z), vec_short8_c(vf16)));
vec_int4 e = vec_and(bits, maxexp), sign = vec_and(bits, signmask);
vec_int4 t = vec_add(vec_sr(vec_xor(bits, sign), vec_uint4_sp(3)), delta); // ((h & 0x7fff) << 13) + delta
vec_int4 zt = vec_int4_c(vec_sub(vec_float4_c(vec_add(t, vec_int4_sp(1 << 23))), deltaf));
t = vec_add(t, vec_and(delta, vec_cmpeq(maxexp, e)));
vec_bint4 zmask = vec_cmpeq(e, z);
vec_int4 ft = vec_sel(t, zt, zmask);
return v_float32x4(vec_float4_c(vec_or(ft, sign)));
#endif
} }
inline void v_pack_store(float16_t* ptr, const v_float32x4& v) inline void v_pack_store(float16_t* ptr, const v_float32x4& v)
{ {
float CV_DECL_ALIGNED(32) f[4]; // fixme: Is there any buitin op or intrinsic that cover "xvcvsphp"?
v_store_aligned(f, v); #if CV_VSX3 && !defined(CV_COMPILER_VSX_BROKEN_ASM)
ptr[0] = float16_t(f[0]); vec_ushort8 vf16;
ptr[1] = float16_t(f[1]); __asm__ __volatile__ ("xvcvsphp %x0,%x1" : "=wa" (vf16) : "wf" (v.val));
ptr[2] = float16_t(f[2]); vec_st_l8(vec_mergesqe(vf16, vf16), ptr);
ptr[3] = float16_t(f[3]); #else
const vec_int4 signmask = vec_int4_sp(0x80000000);
const vec_int4 rval = vec_int4_sp(0x3f000000);
vec_int4 t = vec_int4_c(v.val);
vec_int4 sign = vec_sra(vec_and(t, signmask), vec_uint4_sp(16));
t = vec_and(vec_nor(signmask, signmask), t);
vec_bint4 finitemask = vec_cmpgt(vec_int4_sp(0x47800000), t);
vec_bint4 isnan = vec_cmpgt(t, vec_int4_sp(0x7f800000));
vec_int4 naninf = vec_sel(vec_int4_sp(0x7c00), vec_int4_sp(0x7e00), isnan);
vec_bint4 tinymask = vec_cmpgt(vec_int4_sp(0x38800000), t);
vec_int4 tt = vec_int4_c(vec_add(vec_float4_c(t), vec_float4_c(rval)));
tt = vec_sub(tt, rval);
vec_int4 odd = vec_and(vec_sr(t, vec_uint4_sp(13)), vec_int4_sp(1));
vec_int4 nt = vec_add(t, vec_int4_sp(0xc8000fff));
nt = vec_sr(vec_add(nt, odd), vec_uint4_sp(13));
t = vec_sel(nt, tt, tinymask);
t = vec_sel(naninf, t, finitemask);
t = vec_or(t, sign);
vec_st_l8(vec_packs(t, t), ptr);
#endif
} }
inline void v_cleanup() {} inline void v_cleanup() {}

View File

@ -291,6 +291,8 @@ VSX_IMPL_1RG(vec_udword2, wi, vec_float4, wf, xvcvspuxds, vec_ctulo)
* *
* So we're not able to use inline asm and only use built-in functions that CLANG supports * So we're not able to use inline asm and only use built-in functions that CLANG supports
* and use __builtin_convertvector if clang missng any of vector conversions built-in functions * and use __builtin_convertvector if clang missng any of vector conversions built-in functions
*
* todo: clang asm template bug is fixed, need to reconsider the current workarounds.
*/ */
// convert vector helper // convert vector helper

View File

@ -322,6 +322,8 @@ private:
// Fortran subroutine in EISPACK. // Fortran subroutine in EISPACK.
// Initialize // Initialize
const int max_iters_count = 1000 * this->n;
int nn = this->n; int nn = this->n;
int n1 = nn - 1; int n1 = nn - 1;
int low = 0; int low = 0;
@ -487,7 +489,9 @@ private:
} }
} }
iter = iter + 1; // (Could check iteration count here.) iter = iter + 1;
if (iter > max_iters_count)
CV_Error(Error::StsNoConv, "Algorithm doesn't converge (complex eigen values?)");
// Look for two consecutive small sub-diagonal elements // Look for two consecutive small sub-diagonal elements
int m = n1 - 2; int m = n1 - 2;

View File

@ -1451,115 +1451,82 @@ transform_( const T* src, T* dst, const WT* m, int len, int scn, int dcn )
} }
} }
#if CV_SIMD128 && !defined(__aarch64__)
static inline void
load3x3Matrix(const float* m, v_float32x4& m0, v_float32x4& m1, v_float32x4& m2, v_float32x4& m3)
{
m0 = v_float32x4(m[0], m[4], m[8], 0);
m1 = v_float32x4(m[1], m[5], m[9], 0);
m2 = v_float32x4(m[2], m[6], m[10], 0);
m3 = v_float32x4(m[3], m[7], m[11], 0);
}
#endif
#if CV_SIMD128
static inline v_int16x8
v_matmulvec(const v_int16x8 &v0, const v_int16x8 &m0, const v_int16x8 &m1, const v_int16x8 &m2, const v_int32x4 &m3, const int BITS)
{
// v0 : 0 b0 g0 r0 b1 g1 r1 ?
v_int32x4 t0 = v_dotprod(v0, m0); // a0 b0 a1 b1
v_int32x4 t1 = v_dotprod(v0, m1); // c0 d0 c1 d1
v_int32x4 t2 = v_dotprod(v0, m2); // e0 f0 e1 f1
v_int32x4 t3 = v_setzero_s32();
v_int32x4 s0, s1, s2, s3;
v_transpose4x4(t0, t1, t2, t3, s0, s1, s2, s3);
s0 = s0 + s1 + m3; // B0 G0 R0 ?
s2 = s2 + s3 + m3; // B1 G1 R1 ?
s0 = s0 >> BITS;
s2 = s2 >> BITS;
v_int16x8 result = v_pack(s0, v_setzero_s32()); // B0 G0 R0 0 0 0 0 0
result = v_reinterpret_as_s16(v_reinterpret_as_s64(result) << 16); // 0 B0 G0 R0 0 0 0 0
result = result | v_pack(v_setzero_s32(), s2); // 0 B0 G0 R0 B1 G1 R1 0
return result;
}
#endif
static void static void
transform_8u( const uchar* src, uchar* dst, const float* m, int len, int scn, int dcn ) transform_8u( const uchar* src, uchar* dst, const float* m, int len, int scn, int dcn )
{ {
#if CV_SIMD128 #if CV_SIMD
const int BITS = 10, SCALE = 1 << BITS; const int BITS = 10, SCALE = 1 << BITS;
const float MAX_M = (float)(1 << (15 - BITS)); const float MAX_M = (float)(1 << (15 - BITS));
if( hasSIMD128() && scn == 3 && dcn == 3 && if( scn == 3 && dcn == 3 &&
std::abs(m[0]) < MAX_M && std::abs(m[1]) < MAX_M && std::abs(m[2]) < MAX_M && std::abs(m[3]) < MAX_M*256 && std::abs(m[0]) < MAX_M && std::abs(m[1]) < MAX_M && std::abs(m[ 2]) < MAX_M*256 && std::abs(m[ 3]) < MAX_M*256 &&
std::abs(m[4]) < MAX_M && std::abs(m[5]) < MAX_M && std::abs(m[6]) < MAX_M && std::abs(m[7]) < MAX_M*256 && std::abs(m[4]) < MAX_M && std::abs(m[5]) < MAX_M && std::abs(m[ 6]) < MAX_M*256 && std::abs(m[ 7]) < MAX_M*256 &&
std::abs(m[8]) < MAX_M && std::abs(m[9]) < MAX_M && std::abs(m[10]) < MAX_M && std::abs(m[11]) < MAX_M*256 ) std::abs(m[8]) < MAX_M && std::abs(m[9]) < MAX_M && std::abs(m[10]) < MAX_M*256 && std::abs(m[11]) < MAX_M*256 )
{ {
const int nChannels = 3; const int nChannels = 3;
const int cWidth = v_int16x8::nlanes;
// faster fixed-point transformation
short m00 = saturate_cast<short>(m[0]*SCALE), m01 = saturate_cast<short>(m[1]*SCALE),
m02 = saturate_cast<short>(m[2]*SCALE), m10 = saturate_cast<short>(m[4]*SCALE),
m11 = saturate_cast<short>(m[5]*SCALE), m12 = saturate_cast<short>(m[6]*SCALE),
m20 = saturate_cast<short>(m[8]*SCALE), m21 = saturate_cast<short>(m[9]*SCALE),
m22 = saturate_cast<short>(m[10]*SCALE);
int m03 = saturate_cast<int>((m[3]+0.5f)*SCALE), m13 = saturate_cast<int>((m[7]+0.5f)*SCALE ),
m23 = saturate_cast<int>((m[11]+0.5f)*SCALE);
v_int16x8 m0 = v_int16x8(0, m00, m01, m02, m00, m01, m02, 0); union {
v_int16x8 m1 = v_int16x8(0, m10, m11, m12, m10, m11, m12, 0); short s[6];
v_int16x8 m2 = v_int16x8(0, m20, m21, m22, m20, m21, m22, 0); int p[3];
v_int32x4 m3 = v_int32x4(m03, m13, m23, 0); } m16;
m16.s[0] = saturate_cast<short>(m[0] * SCALE); m16.s[1] = saturate_cast<short>(m[1] * SCALE);
m16.s[2] = saturate_cast<short>(m[4] * SCALE); m16.s[3] = saturate_cast<short>(m[5] * SCALE);
m16.s[4] = saturate_cast<short>(m[8] * SCALE); m16.s[5] = saturate_cast<short>(m[9] * SCALE);
int m32[] = {saturate_cast<int>(m[ 2] * SCALE), saturate_cast<int>(m[ 3] * SCALE),
saturate_cast<int>(m[ 6] * SCALE), saturate_cast<int>(m[ 7] * SCALE),
saturate_cast<int>(m[10] * SCALE), saturate_cast<int>(m[11] * SCALE)};
v_int16 m01 = v_reinterpret_as_s16(vx_setall_s32(m16.p[0]));
v_int32 m2 = vx_setall_s32(m32[0]);
v_int32 m3 = vx_setall_s32(m32[1]);
v_int16 m45 = v_reinterpret_as_s16(vx_setall_s32(m16.p[1]));
v_int32 m6 = vx_setall_s32(m32[2]);
v_int32 m7 = vx_setall_s32(m32[3]);
v_int16 m89 = v_reinterpret_as_s16(vx_setall_s32(m16.p[2]));
v_int32 m10 = vx_setall_s32(m32[4]);
v_int32 m11 = vx_setall_s32(m32[5]);
int x = 0; int x = 0;
for (; x <= (len - v_uint8::nlanes) * nChannels; x += v_uint8::nlanes * nChannels)
for (; x <= (len - cWidth) * nChannels; x += cWidth * nChannels)
{ {
// load 8 pixels v_uint8 b, g, r;
v_int16x8 v0 = v_reinterpret_as_s16(v_load_expand(src + x)); v_load_deinterleave(src + x, b, g, r);
v_int16x8 v1 = v_reinterpret_as_s16(v_load_expand(src + x + cWidth)); v_uint8 bgl, bgh;
v_int16x8 v2 = v_reinterpret_as_s16(v_load_expand(src + x + cWidth * 2)); v_zip(b, g, bgl, bgh);
v_int16x8 v3; v_uint16 rl, rh;
v_expand(r, rl, rh);
// rotate and pack v_int16 dbl, dbh, dgl, dgh, drl, drh;
v3 = v_rotate_right<1>(v2); // 0 b6 g6 r6 b7 g7 r7 0 v_uint16 p0, p2;
v2 = v_rotate_left <5>(v2, v1); // 0 b4 g4 r4 b5 g5 r5 0 v_int32 p1, p3;
v1 = v_rotate_left <3>(v1, v0); // 0 b2 g2 r2 b3 g3 r3 0 v_expand(bgl, p0, p2);
v0 = v_rotate_left <1>(v0); // 0 b0 g0 r0 b1 g1 r1 0 v_expand(v_reinterpret_as_s16(rl), p1, p3);
dbl = v_rshr_pack<BITS>(v_dotprod(v_reinterpret_as_s16(p0), m01) + p1 * m2 + m3,
// multiply with matrix and normalize v_dotprod(v_reinterpret_as_s16(p2), m01) + p3 * m2 + m3);
v0 = v_matmulvec(v0, m0, m1, m2, m3, BITS); // 0 B0 G0 R0 B1 G1 R1 0 dgl = v_rshr_pack<BITS>(v_dotprod(v_reinterpret_as_s16(p0), m45) + p1 * m6 + m7,
v1 = v_matmulvec(v1, m0, m1, m2, m3, BITS); // 0 B2 G2 R2 B3 G3 R3 0 v_dotprod(v_reinterpret_as_s16(p2), m45) + p3 * m6 + m7);
v2 = v_matmulvec(v2, m0, m1, m2, m3, BITS); // 0 B4 G4 R4 B5 G5 R5 0 drl = v_rshr_pack<BITS>(v_dotprod(v_reinterpret_as_s16(p0), m89) + p1 * m10 + m11,
v3 = v_matmulvec(v3, m0, m1, m2, m3, BITS); // 0 B6 G6 R6 B7 G7 R7 0 v_dotprod(v_reinterpret_as_s16(p2), m89) + p3 * m10 + m11);
v_expand(bgh, p0, p2);
// narrow down as uint8x16 v_expand(v_reinterpret_as_s16(rh), p1, p3);
v_uint8x16 z0 = v_pack_u(v0, v_setzero_s16()); // 0 B0 G0 R0 B1 G1 R1 0 0 0 0 0 0 0 0 0 dbh = v_rshr_pack<BITS>(v_dotprod(v_reinterpret_as_s16(p0), m01) + p1 * m2 + m3,
v_uint8x16 z1 = v_pack_u(v1, v_setzero_s16()); // 0 B2 G2 R2 B3 G3 R3 0 0 0 0 0 0 0 0 0 v_dotprod(v_reinterpret_as_s16(p2), m01) + p3 * m2 + m3);
v_uint8x16 z2 = v_pack_u(v2, v_setzero_s16()); // 0 B4 G4 R4 B5 G5 R5 0 0 0 0 0 0 0 0 0 dgh = v_rshr_pack<BITS>(v_dotprod(v_reinterpret_as_s16(p0), m45) + p1 * m6 + m7,
v_uint8x16 z3 = v_pack_u(v3, v_setzero_s16()); // 0 B6 G6 R6 B7 G7 R7 0 0 0 0 0 0 0 0 0 v_dotprod(v_reinterpret_as_s16(p2), m45) + p3 * m6 + m7);
drh = v_rshr_pack<BITS>(v_dotprod(v_reinterpret_as_s16(p0), m89) + p1 * m10 + m11,
// rotate and pack v_dotprod(v_reinterpret_as_s16(p2), m89) + p3 * m10 + m11);
z0 = v_reinterpret_as_u8(v_reinterpret_as_u64(z0) >> 8) | v_reinterpret_as_u8(v_reinterpret_as_u64(z1) << 40); // B0 G0 R0 B1 G1 R1 B2 G2 0 0 0 0 0 0 0 0 v_store_interleave(dst + x, v_pack_u(dbl, dbh), v_pack_u(dgl, dgh), v_pack_u(drl, drh));
z1 = v_reinterpret_as_u8(v_reinterpret_as_u64(z1) >> 24) | v_reinterpret_as_u8(v_reinterpret_as_u64(z2) << 24); // R2 B3 G3 R3 B4 G4 R4 B5 0 0 0 0 0 0 0 0
z2 = v_reinterpret_as_u8(v_reinterpret_as_u64(z2) >> 40) | v_reinterpret_as_u8(v_reinterpret_as_u64(z3) << 8); // G5 R6 B6 G6 R6 B7 G7 R7 0 0 0 0 0 0 0 0
// store on memory
v_store_low(dst + x, z0);
v_store_low(dst + x + cWidth, z1);
v_store_low(dst + x + cWidth * 2, z2);
} }
m32[1] = saturate_cast<int>((m[3] + 0.5f)*SCALE);
m32[3] = saturate_cast<int>((m[7] + 0.5f)*SCALE);
m32[5] = saturate_cast<int>((m[11] + 0.5f)*SCALE);
for( ; x < len * nChannels; x += nChannels ) for( ; x < len * nChannels; x += nChannels )
{ {
int v0 = src[x], v1 = src[x+1], v2 = src[x+2]; int v0 = src[x], v1 = src[x+1], v2 = src[x+2];
uchar t0 = saturate_cast<uchar>((m00*v0 + m01*v1 + m02*v2 + m03)>>BITS); uchar t0 = saturate_cast<uchar>((m16.s[0] * v0 + m16.s[1] * v1 + m32[0] * v2 + m32[1]) >> BITS);
uchar t1 = saturate_cast<uchar>((m10*v0 + m11*v1 + m12*v2 + m13)>>BITS); uchar t1 = saturate_cast<uchar>((m16.s[2] * v0 + m16.s[3] * v1 + m32[2] * v2 + m32[3]) >> BITS);
uchar t2 = saturate_cast<uchar>((m20*v0 + m21*v1 + m22*v2 + m23)>>BITS); uchar t2 = saturate_cast<uchar>((m16.s[4] * v0 + m16.s[5] * v1 + m32[4] * v2 + m32[5]) >> BITS);
dst[x] = t0; dst[x+1] = t1; dst[x+2] = t2; dst[x] = t0; dst[x+1] = t1; dst[x+2] = t2;
} }
vx_cleanup();
return; return;
} }
#endif #endif
@ -1570,64 +1537,65 @@ transform_8u( const uchar* src, uchar* dst, const float* m, int len, int scn, in
static void static void
transform_16u( const ushort* src, ushort* dst, const float* m, int len, int scn, int dcn ) transform_16u( const ushort* src, ushort* dst, const float* m, int len, int scn, int dcn )
{ {
#if CV_SIMD128 && !defined(__aarch64__) #if CV_SIMD && !defined(__aarch64__)
if( hasSIMD128() && scn == 3 && dcn == 3 ) if( scn == 3 && dcn == 3 )
{ {
const int nChannels = 3;
const int cWidth = v_float32x4::nlanes;
v_int16x8 delta = v_int16x8(0, -32768, -32768, -32768, -32768, -32768, -32768, 0);
v_float32x4 m0, m1, m2, m3;
load3x3Matrix(m, m0, m1, m2, m3);
m3 -= v_float32x4(32768.f, 32768.f, 32768.f, 0.f);
int x = 0; int x = 0;
for( ; x <= (len - cWidth) * nChannels; x += cWidth * nChannels ) #if CV_SIMD_WIDTH > 16
v_float32 m0 = vx_setall_f32(m[ 0]);
v_float32 m1 = vx_setall_f32(m[ 1]);
v_float32 m2 = vx_setall_f32(m[ 2]);
v_float32 m3 = vx_setall_f32(m[ 3] - 32768.f);
v_float32 m4 = vx_setall_f32(m[ 4]);
v_float32 m5 = vx_setall_f32(m[ 5]);
v_float32 m6 = vx_setall_f32(m[ 6]);
v_float32 m7 = vx_setall_f32(m[ 7] - 32768.f);
v_float32 m8 = vx_setall_f32(m[ 8]);
v_float32 m9 = vx_setall_f32(m[ 9]);
v_float32 m10 = vx_setall_f32(m[10]);
v_float32 m11 = vx_setall_f32(m[11] - 32768.f);
v_int16 delta = vx_setall_s16(-32768);
for (; x <= (len - v_uint16::nlanes)*3; x += v_uint16::nlanes*3)
{ {
// load 4 pixels v_uint16 b, g, r;
v_uint16x8 v0_16 = v_load(src + x); // b0 g0 r0 b1 g1 r1 b2 g2 v_load_deinterleave(src + x, b, g, r);
v_uint16x8 v2_16 = v_load_low(src + x + cWidth * 2); // r2 b3 g3 r3 ? ? ? ? v_uint32 bl, bh, gl, gh, rl, rh;
v_expand(b, bl, bh);
v_expand(g, gl, gh);
v_expand(r, rl, rh);
// expand to 4 vectors v_int16 db, dg, dr;
v_uint32x4 v0_32, v1_32, v2_32, v3_32, dummy_32; db = v_add_wrap(v_pack(v_round(v_muladd(v_cvt_f32(v_reinterpret_as_s32(bl)), m0, v_muladd(v_cvt_f32(v_reinterpret_as_s32(gl)), m1, v_muladd(v_cvt_f32(v_reinterpret_as_s32(rl)), m2, m3)))),
v_expand(v_rotate_right<3>(v0_16), v1_32, dummy_32); // b1 g1 r1 v_round(v_muladd(v_cvt_f32(v_reinterpret_as_s32(bh)), m0, v_muladd(v_cvt_f32(v_reinterpret_as_s32(gh)), m1, v_muladd(v_cvt_f32(v_reinterpret_as_s32(rh)), m2, m3))))), delta);
v_expand(v_rotate_right<1>(v2_16), v3_32, dummy_32); // b3 g3 r3 dg = v_add_wrap(v_pack(v_round(v_muladd(v_cvt_f32(v_reinterpret_as_s32(bl)), m4, v_muladd(v_cvt_f32(v_reinterpret_as_s32(gl)), m5, v_muladd(v_cvt_f32(v_reinterpret_as_s32(rl)), m6, m7)))),
v_expand(v_rotate_right<6>(v0_16, v2_16), v2_32, dummy_32); // b2 g2 r2 v_round(v_muladd(v_cvt_f32(v_reinterpret_as_s32(bh)), m4, v_muladd(v_cvt_f32(v_reinterpret_as_s32(gh)), m5, v_muladd(v_cvt_f32(v_reinterpret_as_s32(rh)), m6, m7))))), delta);
v_expand(v0_16, v0_32, dummy_32); // b0 g0 r0 dr = v_add_wrap(v_pack(v_round(v_muladd(v_cvt_f32(v_reinterpret_as_s32(bl)), m8, v_muladd(v_cvt_f32(v_reinterpret_as_s32(gl)), m9, v_muladd(v_cvt_f32(v_reinterpret_as_s32(rl)), m10, m11)))),
v_round(v_muladd(v_cvt_f32(v_reinterpret_as_s32(bh)), m8, v_muladd(v_cvt_f32(v_reinterpret_as_s32(gh)), m9, v_muladd(v_cvt_f32(v_reinterpret_as_s32(rh)), m10, m11))))), delta);
// convert to float32x4 v_store_interleave(dst + x, v_reinterpret_as_u16(db), v_reinterpret_as_u16(dg), v_reinterpret_as_u16(dr));
v_float32x4 x0 = v_cvt_f32(v_reinterpret_as_s32(v0_32)); // b0 g0 r0
v_float32x4 x1 = v_cvt_f32(v_reinterpret_as_s32(v1_32)); // b1 g1 r1
v_float32x4 x2 = v_cvt_f32(v_reinterpret_as_s32(v2_32)); // b2 g2 r2
v_float32x4 x3 = v_cvt_f32(v_reinterpret_as_s32(v3_32)); // b3 g3 r3
// multiply and convert back to int32x4
v_int32x4 y0, y1, y2, y3;
y0 = v_round(v_matmuladd(x0, m0, m1, m2, m3)); // B0 G0 R0
y1 = v_round(v_matmuladd(x1, m0, m1, m2, m3)); // B1 G1 R1
y2 = v_round(v_matmuladd(x2, m0, m1, m2, m3)); // B2 G2 R2
y3 = v_round(v_matmuladd(x3, m0, m1, m2, m3)); // B3 G3 R3
// narrow down to int16x8
v_int16x8 v0 = v_add_wrap(v_pack(v_rotate_left<1>(y0), y1), delta); // 0 B0 G0 R0 B1 G1 R1 0
v_int16x8 v2 = v_add_wrap(v_pack(v_rotate_left<1>(y2), y3), delta); // 0 B2 G2 R2 B3 G3 R3 0
// rotate and pack
v0 = v_rotate_right<1>(v0) | v_rotate_left<5>(v2); // B0 G0 R0 B1 G1 R1 B2 G2
v2 = v_rotate_right<3>(v2); // R2 B3 G3 R3 0 0 0 0
// store 4 pixels
v_store(dst + x, v_reinterpret_as_u16(v0));
v_store_low(dst + x + cWidth * 2, v_reinterpret_as_u16(v2));
} }
#endif
for( ; x < len * nChannels; x += nChannels ) v_float32x4 _m0l(m[0], m[4], m[ 8], 0.f);
v_float32x4 _m1l(m[1], m[5], m[ 9], 0.f);
v_float32x4 _m2l(m[2], m[6], m[10], 0.f);
v_float32x4 _m3l(m[3] - 32768.f, m[7] - 32768.f, m[11] - 32768.f, 0.f);
v_float32x4 _m0h = v_rotate_left<1>(_m0l);
v_float32x4 _m1h = v_rotate_left<1>(_m1l);
v_float32x4 _m2h = v_rotate_left<1>(_m2l);
v_float32x4 _m3h = v_rotate_left<1>(_m3l);
v_int16x8 _delta(0, -32768, -32768, -32768, -32768, -32768, -32768, 0);
for( ; x <= len*3 - v_uint16x8::nlanes; x += 3*v_uint16x8::nlanes/4 )
v_store(dst + x, v_rotate_right<1>(v_reinterpret_as_u16(v_add_wrap(v_pack(
v_round(v_matmuladd(v_cvt_f32(v_reinterpret_as_s32(v_load_expand(src + x ))), _m0h, _m1h, _m2h, _m3h)),
v_round(v_matmuladd(v_cvt_f32(v_reinterpret_as_s32(v_load_expand(src + x + 3))), _m0l, _m1l, _m2l, _m3l))), _delta))));
for( ; x < len * 3; x += 3 )
{ {
float v0 = src[x], v1 = src[x + 1], v2 = src[x + 2]; float v0 = src[x], v1 = src[x + 1], v2 = src[x + 2];
ushort t0 = saturate_cast<ushort>(m[0] * v0 + m[1] * v1 + m[2] * v2 + m[3]); ushort t0 = saturate_cast<ushort>(m[0] * v0 + m[1] * v1 + m[ 2] * v2 + m[ 3]);
ushort t1 = saturate_cast<ushort>(m[4] * v0 + m[5] * v1 + m[6] * v2 + m[7]); ushort t1 = saturate_cast<ushort>(m[4] * v0 + m[5] * v1 + m[ 6] * v2 + m[ 7]);
ushort t2 = saturate_cast<ushort>(m[8] * v0 + m[9] * v1 + m[10] * v2 + m[11]); ushort t2 = saturate_cast<ushort>(m[8] * v0 + m[9] * v1 + m[10] * v2 + m[11]);
dst[x] = t0; dst[x + 1] = t1; dst[x + 2] = t2; dst[x] = t0; dst[x + 1] = t1; dst[x + 2] = t2;
} }
vx_cleanup();
return; return;
} }
#endif #endif
@ -1638,52 +1606,68 @@ transform_16u( const ushort* src, ushort* dst, const float* m, int len, int scn,
static void static void
transform_32f( const float* src, float* dst, const float* m, int len, int scn, int dcn ) transform_32f( const float* src, float* dst, const float* m, int len, int scn, int dcn )
{ {
#if CV_SIMD128 && !defined(__aarch64__) #if CV_SIMD && !defined(__aarch64__)
if( hasSIMD128() ) int x = 0;
if( scn == 3 && dcn == 3 )
{ {
int x = 0; int idx[v_float32::nlanes/2];
if( scn == 3 && dcn == 3 ) for( int i = 0; i < v_float32::nlanes/4; i++ )
{ {
const int cWidth = 3; idx[i] = 3*i;
v_float32x4 m0, m1, m2, m3; idx[i + v_float32::nlanes/4] = 0;
load3x3Matrix(m, m0, m1, m2, m3);
for( ; x < (len - 1)*cWidth; x += cWidth )
{
v_float32x4 x0 = v_load(src + x);
v_float32x4 y0 = v_matmuladd(x0, m0, m1, m2, m3);
v_store_low(dst + x, y0);
dst[x + 2] = v_combine_high(y0, y0).get0();
}
for( ; x < len*cWidth; x += cWidth )
{
float v0 = src[x], v1 = src[x+1], v2 = src[x+2];
float t0 = saturate_cast<float>(m[0]*v0 + m[1]*v1 + m[2]*v2 + m[3]);
float t1 = saturate_cast<float>(m[4]*v0 + m[5]*v1 + m[6]*v2 + m[7]);
float t2 = saturate_cast<float>(m[8]*v0 + m[9]*v1 + m[10]*v2 + m[11]);
dst[x] = t0; dst[x+1] = t1; dst[x+2] = t2;
}
return;
} }
float _m[] = { m[0], m[4], m[ 8], 0.f,
if( scn == 4 && dcn == 4 ) m[1], m[5], m[ 9], 0.f,
m[2], m[6], m[10], 0.f,
m[3], m[7], m[11], 0.f };
v_float32 m0 = vx_lut_quads(_m , idx + v_float32::nlanes/4);
v_float32 m1 = vx_lut_quads(_m + 4, idx + v_float32::nlanes/4);
v_float32 m2 = vx_lut_quads(_m + 8, idx + v_float32::nlanes/4);
v_float32 m3 = vx_lut_quads(_m + 12, idx + v_float32::nlanes/4);
for( ; x <= len*3 - v_float32::nlanes; x += 3*v_float32::nlanes/4 )
v_store(dst + x, v_pack_triplets(v_matmuladd(vx_lut_quads(src + x, idx), m0, m1, m2, m3)));
for( ; x < len*3; x += 3 )
{ {
const int cWidth = 4; float v0 = src[x], v1 = src[x+1], v2 = src[x+2];
v_float32x4 m0 = v_float32x4(m[0], m[5], m[10], m[15]); float t0 = saturate_cast<float>(m[0]*v0 + m[1]*v1 + m[ 2]*v2 + m[ 3]);
v_float32x4 m1 = v_float32x4(m[1], m[6], m[11], m[16]); float t1 = saturate_cast<float>(m[4]*v0 + m[5]*v1 + m[ 6]*v2 + m[ 7]);
v_float32x4 m2 = v_float32x4(m[2], m[7], m[12], m[17]); float t2 = saturate_cast<float>(m[8]*v0 + m[9]*v1 + m[10]*v2 + m[11]);
v_float32x4 m3 = v_float32x4(m[3], m[8], m[13], m[18]); dst[x] = t0; dst[x+1] = t1; dst[x+2] = t2;
v_float32x4 m4 = v_float32x4(m[4], m[9], m[14], m[19]);
for( ; x < len*cWidth; x += cWidth )
{
v_float32x4 x0 = v_load(src + x);
v_float32x4 y0 = v_matmul(x0, m0, m1, m2, m3) + m4;
v_store(dst + x, y0);
}
return;
} }
vx_cleanup();
return;
}
if( scn == 4 && dcn == 4 )
{
#if CV_SIMD_WIDTH > 16
int idx[v_float32::nlanes/4];
for( int i = 0; i < v_float32::nlanes/4; i++ )
idx[i] = 0;
float _m[] = { m[4], m[9], m[14], m[19] };
v_float32 m0 = vx_lut_quads(m , idx);
v_float32 m1 = vx_lut_quads(m+ 5, idx);
v_float32 m2 = vx_lut_quads(m+10, idx);
v_float32 m3 = vx_lut_quads(m+15, idx);
v_float32 m4 = vx_lut_quads(_m, idx);
for( ; x <= len*4 - v_float32::nlanes; x += v_float32::nlanes )
{
v_float32 v_src = vx_load(src + x);
v_store(dst + x, v_reduce_sum4(v_src * m0, v_src * m1, v_src * m2, v_src * m3) + m4);
}
#endif
v_float32x4 _m0 = v_load(m );
v_float32x4 _m1 = v_load(m + 5);
v_float32x4 _m2 = v_load(m + 10);
v_float32x4 _m3 = v_load(m + 15);
v_float32x4 _m4(m[4], m[9], m[14], m[19]);
for( ; x < len*4; x += v_float32x4::nlanes )
{
v_float32x4 v_src = v_load(src + x);
v_store(dst + x, v_reduce_sum4(v_src * _m0, v_src * _m1, v_src * _m2, v_src * _m3) + _m4);
}
vx_cleanup();
return;
} }
#endif #endif

View File

@ -519,4 +519,27 @@ TEST_P(Core_EigenZero, double)
} }
INSTANTIATE_TEST_CASE_P(/**/, Core_EigenZero, testing::Values(2, 3, 5)); INSTANTIATE_TEST_CASE_P(/**/, Core_EigenZero, testing::Values(2, 3, 5));
TEST(Core_EigenNonSymmetric, convergence)
{
Matx33d m(
0, -1, 0,
1, 0, 1,
0, -1, 0);
Mat eigenvalues, eigenvectors;
// eigen values are complex, algorithm doesn't converge
try
{
cv::eigenNonSymmetric(m, eigenvalues, eigenvectors);
std::cout << Mat(eigenvalues.t()) << std::endl;
}
catch (const cv::Exception& e)
{
EXPECT_EQ(Error::StsNoConv, e.code) << e.what();
}
catch (...)
{
FAIL() << "Unknown exception has been raised";
}
}
}} // namespace }} // namespace

View File

@ -276,17 +276,15 @@ public:
public: public:
KMeansDistanceComputer(Distance _distance, const Matrix<ElementType>& _dataset, KMeansDistanceComputer(Distance _distance, const Matrix<ElementType>& _dataset,
const int _branching, const int* _indices, const Matrix<double>& _dcenters, const size_t _veclen, const int _branching, const int* _indices, const Matrix<double>& _dcenters, const size_t _veclen,
int* _count, int* _belongs_to, std::vector<DistanceType>& _radiuses, bool& _converged) std::vector<int> &_new_centroids, std::vector<DistanceType> &_sq_dists)
: distance(_distance) : distance(_distance)
, dataset(_dataset) , dataset(_dataset)
, branching(_branching) , branching(_branching)
, indices(_indices) , indices(_indices)
, dcenters(_dcenters) , dcenters(_dcenters)
, veclen(_veclen) , veclen(_veclen)
, count(_count) , new_centroids(_new_centroids)
, belongs_to(_belongs_to) , sq_dists(_sq_dists)
, radiuses(_radiuses)
, converged(_converged)
{ {
} }
@ -297,8 +295,8 @@ public:
for( int i = begin; i<end; ++i) for( int i = begin; i<end; ++i)
{ {
DistanceType sq_dist = distance(dataset[indices[i]], dcenters[0], veclen); DistanceType sq_dist(distance(dataset[indices[i]], dcenters[0], veclen));
int new_centroid = 0; int new_centroid(0);
for (int j=1; j<branching; ++j) { for (int j=1; j<branching; ++j) {
DistanceType new_sq_dist = distance(dataset[indices[i]], dcenters[j], veclen); DistanceType new_sq_dist = distance(dataset[indices[i]], dcenters[j], veclen);
if (sq_dist>new_sq_dist) { if (sq_dist>new_sq_dist) {
@ -306,15 +304,8 @@ public:
sq_dist = new_sq_dist; sq_dist = new_sq_dist;
} }
} }
if (sq_dist > radiuses[new_centroid]) { sq_dists[i] = sq_dist;
radiuses[new_centroid] = sq_dist; new_centroids[i] = new_centroid;
}
if (new_centroid != belongs_to[i]) {
CV_XADD(&count[belongs_to[i]], -1);
CV_XADD(&count[new_centroid], 1);
belongs_to[i] = new_centroid;
converged = false;
}
} }
} }
@ -325,10 +316,8 @@ public:
const int* indices; const int* indices;
const Matrix<double>& dcenters; const Matrix<double>& dcenters;
const size_t veclen; const size_t veclen;
int* count; std::vector<int> &new_centroids;
int* belongs_to; std::vector<DistanceType> &sq_dists;
std::vector<DistanceType>& radiuses;
bool& converged;
KMeansDistanceComputer& operator=( const KMeansDistanceComputer & ) { return *this; } KMeansDistanceComputer& operator=( const KMeansDistanceComputer & ) { return *this; }
}; };
@ -796,10 +785,27 @@ private:
} }
} }
std::vector<int> new_centroids(indices_length);
std::vector<DistanceType> sq_dists(indices_length);
// reassign points to clusters // reassign points to clusters
KMeansDistanceComputer invoker(distance_, dataset_, branching, indices, dcenters, veclen_, count, belongs_to, radiuses, converged); KMeansDistanceComputer invoker(distance_, dataset_, branching, indices, dcenters, veclen_, new_centroids, sq_dists);
parallel_for_(cv::Range(0, (int)indices_length), invoker); parallel_for_(cv::Range(0, (int)indices_length), invoker);
for (int i=0; i < (int)indices_length; ++i) {
DistanceType sq_dist(sq_dists[i]);
int new_centroid(new_centroids[i]);
if (sq_dist > radiuses[new_centroid]) {
radiuses[new_centroid] = sq_dist;
}
if (new_centroid != belongs_to[i]) {
count[belongs_to[i]]--;
count[new_centroid]++;
belongs_to[i] = new_centroid;
converged = false;
}
}
for (int i=0; i<branching; ++i) { for (int i=0; i<branching; ++i) {
// if one cluster converges to an empty cluster, // if one cluster converges to an empty cluster,
// move an element into that cluster // move an element into that cluster

View File

@ -106,9 +106,8 @@ def affine_detect(detector, img, mask=None, pool=None):
print() print()
return keypoints, np.array(descrs) return keypoints, np.array(descrs)
if __name__ == '__main__':
print(__doc__)
def main():
import sys, getopt import sys, getopt
opts, args = getopt.getopt(sys.argv[1:], '', ['feature=']) opts, args = getopt.getopt(sys.argv[1:], '', ['feature='])
opts = dict(opts) opts = dict(opts)
@ -160,4 +159,10 @@ if __name__ == '__main__':
match_and_draw('affine find_obj') match_and_draw('affine find_obj')
cv.waitKey() cv.waitKey()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -26,11 +26,7 @@ import cv2 as cv
# built-in modules # built-in modules
import sys import sys
if __name__ == '__main__': def main():
print('This sample shows how to implement a simple hi resolution image navigation.')
print('USAGE: browse.py [image filename]')
print()
if len(sys.argv) > 1: if len(sys.argv) > 1:
fn = cv.samples.findFile(sys.argv[1]) fn = cv.samples.findFile(sys.argv[1])
print('loading %s ...' % fn) print('loading %s ...' % fn)
@ -62,4 +58,10 @@ if __name__ == '__main__':
cv.imshow('preview', small) cv.imshow('preview', small)
cv.setMouseCallback('preview', onmouse) cv.setMouseCallback('preview', onmouse)
cv.waitKey() cv.waitKey()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -25,7 +25,7 @@ from common import splitfn
# built-in modules # built-in modules
import os import os
if __name__ == '__main__': def main():
import sys import sys
import getopt import getopt
from glob import glob from glob import glob
@ -126,4 +126,10 @@ if __name__ == '__main__':
print('Undistorted image written to: %s' % outfile) print('Undistorted image written to: %s' % outfile)
cv.imwrite(outfile, dst) cv.imwrite(outfile, dst)
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -1,14 +1,14 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from mpl_toolkits.mplot3d import Axes3D # Python 2/3 compatibility
import matplotlib.pyplot as plt from __future__ import print_function
import numpy as np import numpy as np
from matplotlib import cm
from numpy import linspace
import argparse
import cv2 as cv import cv2 as cv
from numpy import linspace
def inverse_homogeneoux_matrix(M): def inverse_homogeneoux_matrix(M):
R = M[0:3, 0:3] R = M[0:3, 0:3]
T = M[0:3, 3] T = M[0:3, 3]
@ -119,6 +119,8 @@ def create_board_model(extrinsics, board_width, board_height, square_size, draw_
def draw_camera_boards(ax, camera_matrix, cam_width, cam_height, scale_focal, def draw_camera_boards(ax, camera_matrix, cam_width, cam_height, scale_focal,
extrinsics, board_width, board_height, square_size, extrinsics, board_width, board_height, square_size,
patternCentric): patternCentric):
from matplotlib import cm
min_values = np.zeros((3,1)) min_values = np.zeros((3,1))
min_values = np.inf min_values = np.inf
max_values = np.zeros((3,1)) max_values = np.zeros((3,1))
@ -158,6 +160,8 @@ def draw_camera_boards(ax, camera_matrix, cam_width, cam_height, scale_focal,
return min_values, max_values return min_values, max_values
def main(): def main():
import argparse
parser = argparse.ArgumentParser(description='Plot camera calibration extrinsics.', parser = argparse.ArgumentParser(description='Plot camera calibration extrinsics.',
formatter_class=argparse.ArgumentDefaultsHelpFormatter) formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--calibration', type=str, default='left_intrinsics.yml', parser.add_argument('--calibration', type=str, default='left_intrinsics.yml',
@ -179,6 +183,9 @@ def main():
camera_matrix = fs.getNode('camera_matrix').mat() camera_matrix = fs.getNode('camera_matrix').mat()
extrinsics = fs.getNode('extrinsic_parameters').mat() extrinsics = fs.getNode('extrinsic_parameters').mat()
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure() fig = plt.figure()
ax = fig.gca(projection='3d') ax = fig.gca(projection='3d')
ax.set_aspect("equal") ax.set_aspect("equal")
@ -211,6 +218,10 @@ def main():
ax.set_title('Extrinsic Parameters Visualization') ax.set_title('Extrinsic Parameters Visualization')
plt.show() plt.show()
print('Done')
if __name__ == "__main__":
if __name__ == '__main__':
print(__doc__)
main() main()
cv.destroyAllWindows()

View File

@ -119,10 +119,10 @@ class App(object):
if __name__ == '__main__': if __name__ == '__main__':
print(__doc__)
import sys import sys
try: try:
video_src = sys.argv[1] video_src = sys.argv[1]
except: except:
video_src = 0 video_src = 0
print(__doc__)
App(video_src).run() App(video_src).run()

View File

@ -46,7 +46,7 @@ def coherence_filter(img, sigma = 11, str_sigma = 11, blend = 0.5, iter_n = 4):
return img return img
if __name__ == '__main__': def main():
import sys import sys
try: try:
fn = sys.argv[1] fn = sys.argv[1]
@ -82,4 +82,11 @@ if __name__ == '__main__':
update() update()
if ch == 27: if ch == 27:
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -8,6 +8,9 @@ Keys:
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
@ -17,46 +20,54 @@ import sys
# local modules # local modules
import video import video
class App():
def set_scale(self, val):
self.hist_scale = val
def run(self):
hsv_map = np.zeros((180, 256, 3), np.uint8)
h, s = np.indices(hsv_map.shape[:2])
hsv_map[:,:,0] = h
hsv_map[:,:,1] = s
hsv_map[:,:,2] = 255
hsv_map = cv.cvtColor(hsv_map, cv.COLOR_HSV2BGR)
cv.imshow('hsv_map', hsv_map)
cv.namedWindow('hist', 0)
self.hist_scale = 10
cv.createTrackbar('scale', 'hist', self.hist_scale, 32, self.set_scale)
try:
fn = sys.argv[1]
except:
fn = 0
cam = video.create_capture(fn, fallback='synth:bg=baboon.jpg:class=chess:noise=0.05')
while True:
flag, frame = cam.read()
cv.imshow('camera', frame)
small = cv.pyrDown(frame)
hsv = cv.cvtColor(small, cv.COLOR_BGR2HSV)
dark = hsv[...,2] < 32
hsv[dark] = 0
h = cv.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])
h = np.clip(h*0.005*self.hist_scale, 0, 1)
vis = hsv_map*h[:,:,np.newaxis] / 255.0
cv.imshow('hist', vis)
ch = cv.waitKey(1)
if ch == 27:
break
print('Done')
if __name__ == '__main__': if __name__ == '__main__':
print(__doc__)
hsv_map = np.zeros((180, 256, 3), np.uint8) App().run()
h, s = np.indices(hsv_map.shape[:2])
hsv_map[:,:,0] = h
hsv_map[:,:,1] = s
hsv_map[:,:,2] = 255
hsv_map = cv.cvtColor(hsv_map, cv.COLOR_HSV2BGR)
cv.imshow('hsv_map', hsv_map)
cv.namedWindow('hist', 0)
hist_scale = 10
def set_scale(val):
global hist_scale
hist_scale = val
cv.createTrackbar('scale', 'hist', hist_scale, 32, set_scale)
try:
fn = sys.argv[1]
except:
fn = 0
cam = video.create_capture(fn, fallback='synth:bg=baboon.jpg:class=chess:noise=0.05')
while True:
flag, frame = cam.read()
cv.imshow('camera', frame)
small = cv.pyrDown(frame)
hsv = cv.cvtColor(small, cv.COLOR_BGR2HSV)
dark = hsv[...,2] < 32
hsv[dark] = 0
h = cv.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])
h = np.clip(h*0.005*hist_scale, 0, 1)
vis = hsv_map*h[:,:,np.newaxis] / 255.0
cv.imshow('hist', vis)
ch = cv.waitKey(1)
if ch == 27:
break
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -48,9 +48,7 @@ def make_image():
cv.ellipse( img, (dx+273, dy+100), (20,35), 0, 0, 360, white, -1 ) cv.ellipse( img, (dx+273, dy+100), (20,35), 0, 0, 360, white, -1 )
return img return img
if __name__ == '__main__': def main():
print(__doc__)
img = make_image() img = make_image()
h, w = img.shape[:2] h, w = img.shape[:2]
@ -67,4 +65,10 @@ if __name__ == '__main__':
cv.createTrackbar( "levels+3", "contours", 3, 7, update ) cv.createTrackbar( "levels+3", "contours", 3, 7, update )
cv.imshow('image', img) cv.imshow('image', img)
cv.waitKey() cv.waitKey()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -65,8 +65,7 @@ def defocus_kernel(d, sz=65):
return kern return kern
if __name__ == '__main__': def main():
print(__doc__)
import sys, getopt import sys, getopt
opts, args = getopt.getopt(sys.argv[1:], '', ['circle', 'angle=', 'd=', 'snr=']) opts, args = getopt.getopt(sys.argv[1:], '', ['circle', 'angle=', 'd=', 'snr='])
opts = dict(opts) opts = dict(opts)
@ -128,3 +127,11 @@ if __name__ == '__main__':
if ch == ord(' '): if ch == ord(' '):
defocus = not defocus defocus = not defocus
update(None) update(None)
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()

View File

@ -11,8 +11,9 @@ USAGE:
# Python 2/3 compatibility # Python 2/3 compatibility
from __future__ import print_function from __future__ import print_function
import cv2 as cv
import numpy as np import numpy as np
import cv2 as cv
import sys import sys
@ -62,8 +63,8 @@ def shift_dft(src, dst=None):
return dst return dst
if __name__ == "__main__":
def main():
if len(sys.argv) > 1: if len(sys.argv) > 1:
fname = sys.argv[1] fname = sys.argv[1]
else: else:
@ -110,4 +111,10 @@ if __name__ == "__main__":
cv.imshow("magnitude", log_spectrum) cv.imshow("magnitude", log_spectrum)
cv.waitKey(0) cv.waitKey(0)
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -27,12 +27,12 @@ Usage:
# Python 2/3 compatibility # Python 2/3 compatibility
from __future__ import print_function from __future__ import print_function
import numpy as np
import cv2 as cv
# built-in modules # built-in modules
from multiprocessing.pool import ThreadPool from multiprocessing.pool import ThreadPool
import cv2 as cv
import numpy as np
from numpy.linalg import norm from numpy.linalg import norm
# local modules # local modules

View File

@ -23,6 +23,7 @@ if PY3:
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
from multiprocessing.pool import ThreadPool from multiprocessing.pool import ThreadPool
from digits import * from digits import *

View File

@ -96,6 +96,10 @@ def main():
if ch == 27: if ch == 27:
break break
print('Done')
if __name__ == '__main__': if __name__ == '__main__':
print(__doc__)
main() main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -19,13 +19,12 @@ import cv2 as cv
from common import make_cmap from common import make_cmap
if __name__ == '__main__': def main():
import sys import sys
try: try:
fn = sys.argv[1] fn = sys.argv[1]
except: except:
fn = 'fruits.jpg' fn = 'fruits.jpg'
print(__doc__)
fn = cv.samples.findFile(fn) fn = cv.samples.findFile(fn)
img = cv.imread(fn, cv.IMREAD_GRAYSCALE) img = cv.imread(fn, cv.IMREAD_GRAYSCALE)
@ -69,4 +68,11 @@ if __name__ == '__main__':
update() update()
if need_update: if need_update:
update() update()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -23,9 +23,7 @@ import video
import sys import sys
if __name__ == '__main__': def main():
print(__doc__)
try: try:
fn = sys.argv[1] fn = sys.argv[1]
except: except:
@ -52,4 +50,11 @@ if __name__ == '__main__':
ch = cv.waitKey(5) ch = cv.waitKey(5)
if ch == 27: if ch == 27:
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -30,9 +30,8 @@ def draw_rects(img, rects, color):
for x1, y1, x2, y2 in rects: for x1, y1, x2, y2 in rects:
cv.rectangle(img, (x1, y1), (x2, y2), color, 2) cv.rectangle(img, (x1, y1), (x2, y2), color, 2)
if __name__ == '__main__': def main():
import sys, getopt import sys, getopt
print(__doc__)
args, video_src = getopt.getopt(sys.argv[1:], '', ['cascade=', 'nested-cascade=']) args, video_src = getopt.getopt(sys.argv[1:], '', ['cascade=', 'nested-cascade='])
try: try:
@ -70,4 +69,11 @@ if __name__ == '__main__':
if cv.waitKey(5) == 27: if cv.waitKey(5) == 27:
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -19,6 +19,7 @@ from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
from common import anorm, getsize from common import anorm, getsize
FLANN_INDEX_KDTREE = 1 # bug: flann enums are missing FLANN_INDEX_KDTREE = 1 # bug: flann enums are missing
@ -137,9 +138,7 @@ def explore_match(win, img1, img2, kp_pairs, status = None, H = None):
return vis return vis
if __name__ == '__main__': def main():
print(__doc__)
import sys, getopt import sys, getopt
opts, args = getopt.getopt(sys.argv[1:], '', ['feature=']) opts, args = getopt.getopt(sys.argv[1:], '', ['feature='])
opts = dict(opts) opts = dict(opts)
@ -187,4 +186,11 @@ if __name__ == '__main__':
match_and_draw('find_obj') match_and_draw('find_obj')
cv.waitKey() cv.waitKey()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -79,9 +79,7 @@ def update(_=None):
draw_str(img, (20, 20), cur_func_name) draw_str(img, (20, 20), cur_func_name)
cv.imshow('fit line', img) cv.imshow('fit line', img)
if __name__ == '__main__': def main():
print(__doc__)
cv.namedWindow('fit line') cv.namedWindow('fit line')
cv.createTrackbar('noise', 'fit line', 3, 50, update) cv.createTrackbar('noise', 'fit line', 3, 50, update)
cv.createTrackbar('point n', 'fit line', 100, 500, update) cv.createTrackbar('point n', 'fit line', 100, 500, update)
@ -96,3 +94,11 @@ if __name__ == '__main__':
cur_func_name = dist_func_names.next() cur_func_name = dist_func_names.next()
if ch == 27: if ch == 27:
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()

View File

@ -20,61 +20,69 @@ from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
if __name__ == '__main__': import sys
import sys
try:
fn = sys.argv[1]
except:
fn = 'fruits.jpg'
print(__doc__)
img = cv.imread(cv.samples.findFile(fn)) class App():
if img is None:
print('Failed to load image file:', fn)
sys.exit(1)
h, w = img.shape[:2] def update(self, dummy=None):
mask = np.zeros((h+2, w+2), np.uint8) if self.seed_pt is None:
seed_pt = None cv.imshow('floodfill', self.img)
fixed_range = True
connectivity = 4
def update(dummy=None):
if seed_pt is None:
cv.imshow('floodfill', img)
return return
flooded = img.copy() flooded = self.img.copy()
mask[:] = 0 self.mask[:] = 0
lo = cv.getTrackbarPos('lo', 'floodfill') lo = cv.getTrackbarPos('lo', 'floodfill')
hi = cv.getTrackbarPos('hi', 'floodfill') hi = cv.getTrackbarPos('hi', 'floodfill')
flags = connectivity flags = self.connectivity
if fixed_range: if self.fixed_range:
flags |= cv.FLOODFILL_FIXED_RANGE flags |= cv.FLOODFILL_FIXED_RANGE
cv.floodFill(flooded, mask, seed_pt, (255, 255, 255), (lo,)*3, (hi,)*3, flags) cv.floodFill(flooded, self.mask, self.seed_pt, (255, 255, 255), (lo,)*3, (hi,)*3, flags)
cv.circle(flooded, seed_pt, 2, (0, 0, 255), -1) cv.circle(flooded, self.seed_pt, 2, (0, 0, 255), -1)
cv.imshow('floodfill', flooded) cv.imshow('floodfill', flooded)
def onmouse(event, x, y, flags, param): def onmouse(self, event, x, y, flags, param):
global seed_pt
if flags & cv.EVENT_FLAG_LBUTTON: if flags & cv.EVENT_FLAG_LBUTTON:
seed_pt = x, y self.seed_pt = x, y
update() self.update()
update() def run(self):
cv.setMouseCallback('floodfill', onmouse) try:
cv.createTrackbar('lo', 'floodfill', 20, 255, update) fn = sys.argv[1]
cv.createTrackbar('hi', 'floodfill', 20, 255, update) except:
fn = 'fruits.jpg'
while True: self.img = cv.imread(cv.samples.findFile(fn))
ch = cv.waitKey() if self.img is None:
if ch == 27: print('Failed to load image file:', fn)
break sys.exit(1)
if ch == ord('f'):
fixed_range = not fixed_range h, w = self.img.shape[:2]
print('using %s range' % ('floating', 'fixed')[fixed_range]) self.mask = np.zeros((h+2, w+2), np.uint8)
update() self.seed_pt = None
if ch == ord('c'): self.fixed_range = True
connectivity = 12-connectivity self.connectivity = 4
print('connectivity =', connectivity)
update() self.update()
cv.setMouseCallback('floodfill', self.onmouse)
cv.createTrackbar('lo', 'floodfill', 20, 255, self.update)
cv.createTrackbar('hi', 'floodfill', 20, 255, self.update)
while True:
ch = cv.waitKey()
if ch == 27:
break
if ch == ord('f'):
self.fixed_range = not self.fixed_range
print('using %s range' % ('floating', 'fixed')[self.fixed_range])
self.update()
if ch == ord('c'):
self.connectivity = 12-self.connectivity
print('connectivity =', self.connectivity)
self.update()
print('Done')
if __name__ == '__main__':
print(__doc__)
App().run()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -19,6 +19,7 @@ from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
from multiprocessing.pool import ThreadPool from multiprocessing.pool import ThreadPool
@ -47,11 +48,10 @@ def process_threaded(img, filters, threadn = 8):
np.maximum(accum, fimg, accum) np.maximum(accum, fimg, accum)
return accum return accum
if __name__ == '__main__': def main():
import sys import sys
from common import Timer from common import Timer
print(__doc__)
try: try:
img_fn = sys.argv[1] img_fn = sys.argv[1]
except: except:
@ -73,4 +73,10 @@ if __name__ == '__main__':
cv.imshow('img', img) cv.imshow('img', img)
cv.imshow('result', res2) cv.imshow('result', res2)
cv.waitKey() cv.waitKey()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -9,9 +9,10 @@ if PY3:
xrange = range xrange = range
import numpy as np import numpy as np
from numpy import random
import cv2 as cv import cv2 as cv
from numpy import random
def make_gaussians(cluster_n, img_size): def make_gaussians(cluster_n, img_size):
points = [] points = []
ref_distrs = [] ref_distrs = []
@ -34,7 +35,7 @@ def draw_gaussain(img, mean, cov, color):
cv.ellipse(img, (x, y), (s1, s2), ang, 0, 360, color, 1, cv.LINE_AA) cv.ellipse(img, (x, y), (s1, s2), ang, 0, 360, color, 1, cv.LINE_AA)
if __name__ == '__main__': def main():
cluster_n = 5 cluster_n = 5
img_size = 512 img_size = 512
@ -66,4 +67,11 @@ if __name__ == '__main__':
ch = cv.waitKey(0) ch = cv.waitKey(0)
if ch == 27: if ch == 27:
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -32,148 +32,154 @@ from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
import sys import sys
BLUE = [255,0,0] # rectangle color class App():
RED = [0,0,255] # PR BG BLUE = [255,0,0] # rectangle color
GREEN = [0,255,0] # PR FG RED = [0,0,255] # PR BG
BLACK = [0,0,0] # sure BG GREEN = [0,255,0] # PR FG
WHITE = [255,255,255] # sure FG BLACK = [0,0,0] # sure BG
WHITE = [255,255,255] # sure FG
DRAW_BG = {'color' : BLACK, 'val' : 0} DRAW_BG = {'color' : BLACK, 'val' : 0}
DRAW_FG = {'color' : WHITE, 'val' : 1} DRAW_FG = {'color' : WHITE, 'val' : 1}
DRAW_PR_FG = {'color' : GREEN, 'val' : 3} DRAW_PR_FG = {'color' : GREEN, 'val' : 3}
DRAW_PR_BG = {'color' : RED, 'val' : 2} DRAW_PR_BG = {'color' : RED, 'val' : 2}
# setting up flags # setting up flags
rect = (0,0,1,1) rect = (0,0,1,1)
drawing = False # flag for drawing curves drawing = False # flag for drawing curves
rectangle = False # flag for drawing rect rectangle = False # flag for drawing rect
rect_over = False # flag to check if rect drawn rect_over = False # flag to check if rect drawn
rect_or_mask = 100 # flag for selecting rect or mask mode rect_or_mask = 100 # flag for selecting rect or mask mode
value = DRAW_FG # drawing initialized to FG value = DRAW_FG # drawing initialized to FG
thickness = 3 # brush thickness thickness = 3 # brush thickness
def onmouse(event,x,y,flags,param): def onmouse(self, event, x, y, flags, param):
global img,img2,drawing,value,mask,rectangle,rect,rect_or_mask,ix,iy,rect_over # Draw Rectangle
if event == cv.EVENT_RBUTTONDOWN:
self.rectangle = True
self.ix, self.iy = x,y
# Draw Rectangle elif event == cv.EVENT_MOUSEMOVE:
if event == cv.EVENT_RBUTTONDOWN: if self.rectangle == True:
rectangle = True self.img = self.img2.copy()
ix,iy = x,y cv.rectangle(self.img, (self.ix, self.iy), (x, y), self.BLUE, 2)
self.rect = (min(self.ix, x), min(self.iy, y), abs(self.ix - x), abs(self.iy - y))
self.rect_or_mask = 0
elif event == cv.EVENT_MOUSEMOVE: elif event == cv.EVENT_RBUTTONUP:
if rectangle == True: self.rectangle = False
img = img2.copy() self.rect_over = True
cv.rectangle(img,(ix,iy),(x,y),BLUE,2) cv.rectangle(self.img, (self.ix, self.iy), (x, y), self.BLUE, 2)
rect = (min(ix,x),min(iy,y),abs(ix-x),abs(iy-y)) self.rect = (min(self.ix, x), min(self.iy, y), abs(self.ix - x), abs(self.iy - y))
rect_or_mask = 0 self.rect_or_mask = 0
print(" Now press the key 'n' a few times until no further change \n")
elif event == cv.EVENT_RBUTTONUP: # draw touchup curves
rectangle = False
rect_over = True
cv.rectangle(img,(ix,iy),(x,y),BLUE,2)
rect = (min(ix,x),min(iy,y),abs(ix-x),abs(iy-y))
rect_or_mask = 0
print(" Now press the key 'n' a few times until no further change \n")
# draw touchup curves if event == cv.EVENT_LBUTTONDOWN:
if self.rect_over == False:
print("first draw rectangle \n")
else:
self.drawing = True
cv.circle(self.img, (x,y), self.thickness, self.value['color'], -1)
cv.circle(self.mask, (x,y), self.thickness, self.value['val'], -1)
if event == cv.EVENT_LBUTTONDOWN: elif event == cv.EVENT_MOUSEMOVE:
if rect_over == False: if self.drawing == True:
print("first draw rectangle \n") cv.circle(self.img, (x, y), self.thickness, self.value['color'], -1)
cv.circle(self.mask, (x, y), self.thickness, self.value['val'], -1)
elif event == cv.EVENT_LBUTTONUP:
if self.drawing == True:
self.drawing = False
cv.circle(self.img, (x, y), self.thickness, self.value['color'], -1)
cv.circle(self.mask, (x, y), self.thickness, self.value['val'], -1)
def run(self):
# Loading images
if len(sys.argv) == 2:
filename = sys.argv[1] # for drawing purposes
else: else:
drawing = True print("No input image given, so loading default image, lena.jpg \n")
cv.circle(img,(x,y),thickness,value['color'],-1) print("Correct Usage: python grabcut.py <filename> \n")
cv.circle(mask,(x,y),thickness,value['val'],-1) filename = 'lena.jpg'
elif event == cv.EVENT_MOUSEMOVE: self.img = cv.imread(cv.samples.findFile(filename))
if drawing == True: self.img2 = self.img.copy() # a copy of original image
cv.circle(img,(x,y),thickness,value['color'],-1) self.mask = np.zeros(self.img.shape[:2], dtype = np.uint8) # mask initialized to PR_BG
cv.circle(mask,(x,y),thickness,value['val'],-1) self.output = np.zeros(self.img.shape, np.uint8) # output image to be shown
# input and output windows
cv.namedWindow('output')
cv.namedWindow('input')
cv.setMouseCallback('input', self.onmouse)
cv.moveWindow('input', self.img.shape[1]+10,90)
print(" Instructions: \n")
print(" Draw a rectangle around the object using right mouse button \n")
while(1):
cv.imshow('output', self.output)
cv.imshow('input', self.img)
k = cv.waitKey(1)
# key bindings
if k == 27: # esc to exit
break
elif k == ord('0'): # BG drawing
print(" mark background regions with left mouse button \n")
self.value = self.DRAW_BG
elif k == ord('1'): # FG drawing
print(" mark foreground regions with left mouse button \n")
self.value = self.DRAW_FG
elif k == ord('2'): # PR_BG drawing
self.value = self.DRAW_PR_BG
elif k == ord('3'): # PR_FG drawing
self.value = self.DRAW_PR_FG
elif k == ord('s'): # save image
bar = np.zeros((self.img.shape[0], 5, 3), np.uint8)
res = np.hstack((self.img2, bar, self.img, bar, self.output))
cv.imwrite('grabcut_output.png', res)
print(" Result saved as image \n")
elif k == ord('r'): # reset everything
print("resetting \n")
self.rect = (0,0,1,1)
self.drawing = False
self.rectangle = False
self.rect_or_mask = 100
self.rect_over = False
self.value = self.DRAW_FG
self.img = self.img2.copy()
self.mask = np.zeros(self.img.shape[:2], dtype = np.uint8) # mask initialized to PR_BG
self.output = np.zeros(self.img.shape, np.uint8) # output image to be shown
elif k == ord('n'): # segment the image
print(""" For finer touchups, mark foreground and background after pressing keys 0-3
and again press 'n' \n""")
try:
if (self.rect_or_mask == 0): # grabcut with rect
bgdmodel = np.zeros((1, 65), np.float64)
fgdmodel = np.zeros((1, 65), np.float64)
cv.grabCut(self.img2, self.mask, self.rect, bgdmodel, fgdmodel, 1, cv.GC_INIT_WITH_RECT)
self.rect_or_mask = 1
elif self.rect_or_mask == 1: # grabcut with mask
bgdmodel = np.zeros((1, 65), np.float64)
fgdmodel = np.zeros((1, 65), np.float64)
cv.grabCut(self.img2, self.mask, self.rect, bgdmodel, fgdmodel, 1, cv.GC_INIT_WITH_MASK)
except:
import traceback
traceback.print_exc()
mask2 = np.where((self.mask==1) + (self.mask==3), 255, 0).astype('uint8')
self.output = cv.bitwise_and(self.img2, self.img2, mask=mask2)
print('Done')
elif event == cv.EVENT_LBUTTONUP:
if drawing == True:
drawing = False
cv.circle(img,(x,y),thickness,value['color'],-1)
cv.circle(mask,(x,y),thickness,value['val'],-1)
if __name__ == '__main__': if __name__ == '__main__':
# print documentation
print(__doc__) print(__doc__)
App().run()
# Loading images
if len(sys.argv) == 2:
filename = sys.argv[1] # for drawing purposes
else:
print("No input image given, so loading default image, lena.jpg \n")
print("Correct Usage: python grabcut.py <filename> \n")
filename = 'lena.jpg'
img = cv.imread(cv.samples.findFile(filename))
img2 = img.copy() # a copy of original image
mask = np.zeros(img.shape[:2],dtype = np.uint8) # mask initialized to PR_BG
output = np.zeros(img.shape,np.uint8) # output image to be shown
# input and output windows
cv.namedWindow('output')
cv.namedWindow('input')
cv.setMouseCallback('input',onmouse)
cv.moveWindow('input',img.shape[1]+10,90)
print(" Instructions: \n")
print(" Draw a rectangle around the object using right mouse button \n")
while(1):
cv.imshow('output',output)
cv.imshow('input',img)
k = cv.waitKey(1)
# key bindings
if k == 27: # esc to exit
break
elif k == ord('0'): # BG drawing
print(" mark background regions with left mouse button \n")
value = DRAW_BG
elif k == ord('1'): # FG drawing
print(" mark foreground regions with left mouse button \n")
value = DRAW_FG
elif k == ord('2'): # PR_BG drawing
value = DRAW_PR_BG
elif k == ord('3'): # PR_FG drawing
value = DRAW_PR_FG
elif k == ord('s'): # save image
bar = np.zeros((img.shape[0],5,3),np.uint8)
res = np.hstack((img2,bar,img,bar,output))
cv.imwrite('grabcut_output.png',res)
print(" Result saved as image \n")
elif k == ord('r'): # reset everything
print("resetting \n")
rect = (0,0,1,1)
drawing = False
rectangle = False
rect_or_mask = 100
rect_over = False
value = DRAW_FG
img = img2.copy()
mask = np.zeros(img.shape[:2],dtype = np.uint8) # mask initialized to PR_BG
output = np.zeros(img.shape,np.uint8) # output image to be shown
elif k == ord('n'): # segment the image
print(""" For finer touchups, mark foreground and background after pressing keys 0-3
and again press 'n' \n""")
if (rect_or_mask == 0): # grabcut with rect
bgdmodel = np.zeros((1,65),np.float64)
fgdmodel = np.zeros((1,65),np.float64)
cv.grabCut(img2,mask,rect,bgdmodel,fgdmodel,1,cv.GC_INIT_WITH_RECT)
rect_or_mask = 1
elif rect_or_mask == 1: # grabcut with mask
bgdmodel = np.zeros((1,65),np.float64)
fgdmodel = np.zeros((1,65),np.float64)
cv.grabCut(img2,mask,rect,bgdmodel,fgdmodel,1,cv.GC_INIT_WITH_MASK)
mask2 = np.where((mask==1) + (mask==3),255,0).astype('uint8')
output = cv.bitwise_and(img2,img2,mask=mask2)
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -18,8 +18,8 @@ Abid Rahman 3/14/12 debug Gary Bradski
# Python 2/3 compatibility # Python 2/3 compatibility
from __future__ import print_function from __future__ import print_function
import cv2 as cv
import numpy as np import numpy as np
import cv2 as cv
bins = np.arange(256).reshape(256,1) bins = np.arange(256).reshape(256,1)
@ -53,8 +53,7 @@ def hist_lines(im):
return y return y
if __name__ == '__main__': def main():
import sys import sys
if len(sys.argv)>1: if len(sys.argv)>1:
@ -116,4 +115,11 @@ if __name__ == '__main__':
print('ESC') print('ESC')
cv.destroyAllWindows() cv.destroyAllWindows()
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -11,13 +11,12 @@ Usage:
# Python 2/3 compatibility # Python 2/3 compatibility
from __future__ import print_function from __future__ import print_function
import cv2 as cv
import numpy as np import numpy as np
import cv2 as cv
import sys import sys
if __name__ == '__main__': def main():
print(__doc__)
try: try:
fn = sys.argv[1] fn = sys.argv[1]
except IndexError: except IndexError:
@ -40,3 +39,10 @@ if __name__ == '__main__':
cv.imshow("source", src) cv.imshow("source", src)
cv.waitKey(0) cv.waitKey(0)
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()

View File

@ -13,12 +13,11 @@ from __future__ import print_function
import cv2 as cv import cv2 as cv
import numpy as np import numpy as np
import sys import sys
import math import math
if __name__ == '__main__': def main():
print(__doc__)
try: try:
fn = sys.argv[1] fn = sys.argv[1]
except IndexError: except IndexError:
@ -52,3 +51,10 @@ if __name__ == '__main__':
cv.imshow("source", src) cv.imshow("source", src)
cv.waitKey(0) cv.waitKey(0)
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()

View File

@ -20,17 +20,16 @@ from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
from common import Sketcher from common import Sketcher
if __name__ == '__main__': def main():
import sys import sys
try: try:
fn = sys.argv[1] fn = sys.argv[1]
except: except:
fn = 'fruits.jpg' fn = 'fruits.jpg'
print(__doc__)
img = cv.imread(cv.samples.findFile(fn)) img = cv.imread(cv.samples.findFile(fn))
if img is None: if img is None:
print('Failed to load image file:', fn) print('Failed to load image file:', fn)
@ -51,4 +50,11 @@ if __name__ == '__main__':
img_mark[:] = img img_mark[:] = img
mark[:] = 0 mark[:] = 0
sketch.show() sketch.show()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -18,12 +18,13 @@ PY3 = sys.version_info[0] == 3
if PY3: if PY3:
long = int long = int
import numpy as np
import cv2 as cv import cv2 as cv
from math import cos, sin, sqrt from math import cos, sin, sqrt
import numpy as np import numpy as np
if __name__ == "__main__": def main():
img_height = 500 img_height = 500
img_width = 500 img_width = 500
kalman = cv.KalmanFilter(2, 1, 0) kalman = cv.KalmanFilter(2, 1, 0)
@ -93,4 +94,10 @@ if __name__ == "__main__":
if code in [27, ord('q'), ord('Q')]: if code in [27, ord('q'), ord('Q')]:
break break
cv.destroyWindow("Kalman") print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()

View File

@ -18,12 +18,10 @@ import cv2 as cv
from gaussian_mix import make_gaussians from gaussian_mix import make_gaussians
if __name__ == '__main__': def main():
cluster_n = 5 cluster_n = 5
img_size = 512 img_size = 512
print(__doc__)
# generating bright palette # generating bright palette
colors = np.zeros((1, cluster_n, 3), np.uint8) colors = np.zeros((1, cluster_n, 3), np.uint8)
colors[0,:] = 255 colors[0,:] = 255
@ -43,8 +41,15 @@ if __name__ == '__main__':
cv.circle(img, (x, y), 1, c, -1) cv.circle(img, (x, y), 1, c, -1)
cv.imshow('gaussian mixture', img) cv.imshow('kmeans', img)
ch = cv.waitKey(0) ch = cv.waitKey(0)
if ch == 27: if ch == 27:
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -22,6 +22,7 @@ if PY3:
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
import video import video
from common import nothing, getsize from common import nothing, getsize
@ -44,9 +45,8 @@ def merge_lappyr(levels):
return np.uint8(np.clip(img, 0, 255)) return np.uint8(np.clip(img, 0, 255))
if __name__ == '__main__': def main():
import sys import sys
print(__doc__)
try: try:
fn = sys.argv[1] fn = sys.argv[1]
@ -72,3 +72,11 @@ if __name__ == '__main__':
if cv.waitKey(1) == 27: if cv.waitKey(1) == 27:
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()

View File

@ -145,12 +145,10 @@ class MLP(LetterStatModel):
if __name__ == '__main__': def main():
import getopt import getopt
import sys import sys
print(__doc__)
models = [RTrees, KNearest, Boost, SVM, MLP] # NBayes models = [RTrees, KNearest, Boost, SVM, MLP] # NBayes
models = dict( [(cls.__name__.lower(), cls) for cls in models] ) models = dict( [(cls.__name__.lower(), cls) for cls in models] )
@ -186,4 +184,11 @@ if __name__ == '__main__':
fn = args['--save'] fn = args['--save']
print('saving model to %s ...' % fn) print('saving model to %s ...' % fn)
model.save(fn) model.save(fn)
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -25,6 +25,7 @@ from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
import video import video
from common import draw_str from common import draw_str
from video import presets from video import presets
@ -112,9 +113,11 @@ def main():
except: except:
video_src = 0 video_src = 0
print(__doc__)
App(video_src).run() App(video_src).run()
cv.destroyAllWindows() print('Done')
if __name__ == '__main__': if __name__ == '__main__':
print(__doc__)
main() main()
cv.destroyAllWindows()

View File

@ -23,6 +23,7 @@ from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
import video import video
from common import anorm2, draw_str from common import anorm2, draw_str
from time import clock from time import clock
@ -96,9 +97,11 @@ def main():
except: except:
video_src = 0 video_src = 0
print(__doc__)
App(video_src).run() App(video_src).run()
cv.destroyAllWindows() print('Done')
if __name__ == '__main__': if __name__ == '__main__':
print(__doc__)
main() main()
cv.destroyAllWindows()

View File

@ -13,11 +13,10 @@ Keys:
# Python 2/3 compatibility # Python 2/3 compatibility
from __future__ import print_function from __future__ import print_function
import numpy as np
import cv2 as cv import cv2 as cv
if __name__ == '__main__': def main():
print(__doc__)
import sys import sys
try: try:
fn = sys.argv[1] fn = sys.argv[1]
@ -37,3 +36,10 @@ if __name__ == '__main__':
cv.imshow('linearpolar', img3) cv.imshow('linearpolar', img3)
cv.waitKey(0) cv.waitKey(0)
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()

View File

@ -21,9 +21,7 @@ import numpy as np
import cv2 as cv import cv2 as cv
if __name__ == '__main__': def main():
print(__doc__)
import sys import sys
from itertools import cycle from itertools import cycle
from common import draw_str from common import draw_str
@ -93,4 +91,11 @@ if __name__ == '__main__':
else: else:
cur_str_mode = str_modes.next() cur_str_mode = str_modes.next()
update() update()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -25,59 +25,64 @@ import argparse
from math import * from math import *
drag_start = None class App():
sel = (0,0,0,0) drag_start = None
sel = (0,0,0,0)
def onmouse(self, event, x, y, flags, param):
if event == cv.EVENT_LBUTTONDOWN:
self.drag_start = x, y
self.sel = (0,0,0,0)
elif event == cv.EVENT_LBUTTONUP:
if self.sel[2] > self.sel[0] and self.sel[3] > self.sel[1]:
patch = self.gray[self.sel[1]:self.sel[3], self.sel[0]:self.sel[2]]
result = cv.matchTemplate(self.gray, patch, cv.TM_CCOEFF_NORMED)
result = np.abs(result)**3
_val, result = cv.threshold(result, 0.01, 0, cv.THRESH_TOZERO)
result8 = cv.normalize(result, None, 0, 255, cv.NORM_MINMAX, cv.CV_8U)
cv.imshow("result", result8)
self.drag_start = None
elif self.drag_start:
#print flags
if flags & cv.EVENT_FLAG_LBUTTON:
minpos = min(self.drag_start[0], x), min(self.drag_start[1], y)
maxpos = max(self.drag_start[0], x), max(self.drag_start[1], y)
self.sel = (minpos[0], minpos[1], maxpos[0], maxpos[1])
img = cv.cvtColor(self.gray, cv.COLOR_GRAY2BGR)
cv.rectangle(img, (self.sel[0], self.sel[1]), (self.sel[2], self.sel[3]), (0,255,255), 1)
cv.imshow("gray", img)
else:
print("selection is complete")
self.drag_start = None
def run(self):
parser = argparse.ArgumentParser(description='Demonstrate mouse interaction with images')
parser.add_argument("-i","--input", default='../data/', help="Input directory.")
args = parser.parse_args()
path = args.input
cv.namedWindow("gray",1)
cv.setMouseCallback("gray", self.onmouse)
'''Loop through all the images in the directory'''
for infile in glob.glob( os.path.join(path, '*.*') ):
ext = os.path.splitext(infile)[1][1:] #get the filename extension
if ext == "png" or ext == "jpg" or ext == "bmp" or ext == "tiff" or ext == "pbm":
print(infile)
img = cv.imread(infile,1)
if img is None:
continue
self.sel = (0,0,0,0)
self.drag_start = None
self.gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow("gray", self.gray)
if cv.waitKey() == 27:
break
print('Done')
def onmouse(event, x, y, flags, param):
global drag_start, sel
if event == cv.EVENT_LBUTTONDOWN:
drag_start = x, y
sel = 0,0,0,0
elif event == cv.EVENT_LBUTTONUP:
if sel[2] > sel[0] and sel[3] > sel[1]:
patch = gray[sel[1]:sel[3],sel[0]:sel[2]]
result = cv.matchTemplate(gray,patch,cv.TM_CCOEFF_NORMED)
result = np.abs(result)**3
_val, result = cv.threshold(result, 0.01, 0, cv.THRESH_TOZERO)
result8 = cv.normalize(result,None,0,255,cv.NORM_MINMAX,cv.CV_8U)
cv.imshow("result", result8)
drag_start = None
elif drag_start:
#print flags
if flags & cv.EVENT_FLAG_LBUTTON:
minpos = min(drag_start[0], x), min(drag_start[1], y)
maxpos = max(drag_start[0], x), max(drag_start[1], y)
sel = minpos[0], minpos[1], maxpos[0], maxpos[1]
img = cv.cvtColor(gray, cv.COLOR_GRAY2BGR)
cv.rectangle(img, (sel[0], sel[1]), (sel[2], sel[3]), (0,255,255), 1)
cv.imshow("gray", img)
else:
print("selection is complete")
drag_start = None
if __name__ == '__main__': if __name__ == '__main__':
print(__doc__) print(__doc__)
App().run()
parser = argparse.ArgumentParser(description='Demonstrate mouse interaction with images')
parser.add_argument("-i","--input", default='../data/', help="Input directory.")
args = parser.parse_args()
path = args.input
cv.namedWindow("gray",1)
cv.setMouseCallback("gray", onmouse)
'''Loop through all the images in the directory'''
for infile in glob.glob( os.path.join(path, '*.*') ):
ext = os.path.splitext(infile)[1][1:] #get the filename extension
if ext == "png" or ext == "jpg" or ext == "bmp" or ext == "tiff" or ext == "pbm":
print(infile)
img=cv.imread(infile,1)
if img is None:
continue
sel = (0,0,0,0)
drag_start = None
gray=cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cv.imshow("gray",gray)
if cv.waitKey() == 27:
break
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -14,12 +14,16 @@ Keys:
''' '''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
import video import video
import sys import sys
if __name__ == '__main__': def main():
try: try:
video_src = sys.argv[1] video_src = sys.argv[1]
except: except:
@ -42,4 +46,11 @@ if __name__ == '__main__':
cv.imshow('img', vis) cv.imshow('img', vis)
if cv.waitKey(5) == 27: if cv.waitKey(5) == 27:
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -13,11 +13,11 @@ Usage:
# Python 2/3 compatibility # Python 2/3 compatibility
from __future__ import print_function from __future__ import print_function
import numpy as np
import cv2 as cv import cv2 as cv
if __name__ == '__main__': def main():
import sys import sys
print(__doc__)
try: try:
param = sys.argv[1] param = sys.argv[1]
@ -31,3 +31,11 @@ if __name__ == '__main__':
print("\t--help\n\t\tprint this help") print("\t--help\n\t\tprint this help")
else: else:
print("Welcome to OpenCV") print("Welcome to OpenCV")
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()

View File

@ -18,6 +18,7 @@ from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
import video import video
@ -55,9 +56,8 @@ def warp_flow(img, flow):
res = cv.remap(img, flow, None, cv.INTER_LINEAR) res = cv.remap(img, flow, None, cv.INTER_LINEAR)
return res return res
if __name__ == '__main__': def main():
import sys import sys
print(__doc__)
try: try:
fn = sys.argv[1] fn = sys.argv[1]
except IndexError: except IndexError:
@ -94,4 +94,11 @@ if __name__ == '__main__':
if show_glitch: if show_glitch:
cur_glitch = img.copy() cur_glitch = img.copy()
print('glitch is', ['off', 'on'][show_glitch]) print('glitch is', ['off', 'on'][show_glitch])
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -30,13 +30,11 @@ def draw_detections(img, rects, thickness = 1):
cv.rectangle(img, (x+pad_w, y+pad_h), (x+w-pad_w, y+h-pad_h), (0, 255, 0), thickness) cv.rectangle(img, (x+pad_w, y+pad_h), (x+w-pad_w, y+h-pad_h), (0, 255, 0), thickness)
if __name__ == '__main__': def main():
import sys import sys
from glob import glob from glob import glob
import itertools as it import itertools as it
print(__doc__)
hog = cv.HOGDescriptor() hog = cv.HOGDescriptor()
hog.setSVMDetector( cv.HOGDescriptor_getDefaultPeopleDetector() ) hog.setSVMDetector( cv.HOGDescriptor_getDefaultPeopleDetector() )
@ -68,4 +66,11 @@ if __name__ == '__main__':
ch = cv.waitKey() ch = cv.waitKey()
if ch == 27: if ch == 27:
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -7,6 +7,7 @@ Loads several images sequentially and tries to find squares in each image.
''' '''
# Python 2/3 compatibility # Python 2/3 compatibility
from __future__ import print_function
import sys import sys
PY3 = sys.version_info[0] == 3 PY3 = sys.version_info[0] == 3
@ -42,7 +43,7 @@ def find_squares(img):
squares.append(cnt) squares.append(cnt)
return squares return squares
if __name__ == '__main__': def main():
from glob import glob from glob import glob
for fn in glob('../data/pic*.png'): for fn in glob('../data/pic*.png'):
img = cv.imread(fn) img = cv.imread(fn)
@ -52,4 +53,11 @@ if __name__ == '__main__':
ch = cv.waitKey() ch = cv.waitKey()
if ch == 27: if ch == 27:
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -33,7 +33,7 @@ def write_ply(fn, verts, colors):
np.savetxt(f, verts, fmt='%f %f %f %d %d %d ') np.savetxt(f, verts, fmt='%f %f %f %d %d %d ')
if __name__ == '__main__': def main():
print('loading images...') print('loading images...')
imgL = cv.pyrDown(cv.imread(cv.samples.findFile('aloeL.jpg'))) # downscale images for faster processing imgL = cv.pyrDown(cv.imread(cv.samples.findFile('aloeL.jpg'))) # downscale images for faster processing
imgR = cv.pyrDown(cv.imread(cv.samples.findFile('aloeR.jpg'))) imgR = cv.pyrDown(cv.imread(cv.samples.findFile('aloeR.jpg')))
@ -75,4 +75,11 @@ if __name__ == '__main__':
cv.imshow('left', imgL) cv.imshow('left', imgL)
cv.imshow('disparity', (disp-min_disp)/num_disp) cv.imshow('disparity', (disp-min_disp)/num_disp)
cv.waitKey() cv.waitKey()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -16,7 +16,7 @@ from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv import cv2 as cv
if __name__ == '__main__': def main():
import sys import sys
try: try:
fn = sys.argv[1] fn = sys.argv[1]
@ -45,3 +45,11 @@ if __name__ == '__main__':
cv.imshow('input', img) cv.imshow('input', img)
cv.imshow('flow', vis) cv.imshow('flow', vis)
cv.waitKey() cv.waitKey()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()

View File

@ -5,9 +5,10 @@
from __future__ import print_function from __future__ import print_function
import numpy as np import numpy as np
import cv2 as cv
from numpy import pi, sin, cos from numpy import pi, sin, cos
import cv2 as cv
defaultSize = 512 defaultSize = 512
@ -86,7 +87,7 @@ class TestSceneRender():
else: else:
self.currentRect = self.initialRect + np.int( 30*cos(self.time*self.speed) + 50*sin(self.time*self.speed)) self.currentRect = self.initialRect + np.int( 30*cos(self.time*self.speed) + 50*sin(self.time*self.speed))
if self.deformation: if self.deformation:
self.currentRect[1:3] += self.h/20*cos(self.time) self.currentRect[1:3] += int(self.h/20*cos(self.time))
cv.fillConvexPoly(img, self.currentRect, (0, 0, 255)) cv.fillConvexPoly(img, self.currentRect, (0, 0, 255))
self.time += self.timeStep self.time += self.timeStep
@ -96,8 +97,7 @@ class TestSceneRender():
self.time = 0.0 self.time = 0.0
if __name__ == '__main__': def main():
backGr = cv.imread(cv.samples.findFile('graf1.png')) backGr = cv.imread(cv.samples.findFile('graf1.png'))
fgr = cv.imread(cv.samples.findFile('box.png')) fgr = cv.imread(cv.samples.findFile('box.png'))
@ -111,6 +111,11 @@ if __name__ == '__main__':
ch = cv.waitKey(3) ch = cv.waitKey(3)
if ch == 27: if ch == 27:
break break
#import os
#print (os.environ['PYTHONPATH']) print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -27,7 +27,7 @@ USAGE: turing.py [-o <output.avi>]
Press ESC to stop. Press ESC to stop.
''' '''
if __name__ == '__main__': def main():
print(help_message) print(help_message)
w, h = 512, 512 w, h = 512, 512
@ -71,4 +71,11 @@ if __name__ == '__main__':
cv.imshow('a', vis) cv.imshow('a', vis)
if cv.waitKey(5) == 27: if cv.waitKey(5) == 27:
break break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows() cv.destroyAllWindows()

View File

@ -0,0 +1,92 @@
import cv2 as cv
import numpy as np
import argparse
W = 52 # window size is WxW
C_Thr = 0.43 # threshold for coherency
LowThr = 35 # threshold1 for orientation, it ranges from 0 to 180
HighThr = 57 # threshold2 for orientation, it ranges from 0 to 180
## [calcGST]
## [calcJ_header]
## [calcGST_proto]
def calcGST(inputIMG, w):
## [calcGST_proto]
img = inputIMG.astype(np.float32)
# GST components calculation (start)
# J = (J11 J12; J12 J22) - GST
imgDiffX = cv.Sobel(img, cv.CV_32F, 1, 0, 3)
imgDiffY = cv.Sobel(img, cv.CV_32F, 0, 1, 3)
imgDiffXY = cv.multiply(imgDiffX, imgDiffY)
## [calcJ_header]
imgDiffXX = cv.multiply(imgDiffX, imgDiffX)
imgDiffYY = cv.multiply(imgDiffY, imgDiffY)
J11 = cv.boxFilter(imgDiffXX, cv.CV_32F, (w,w))
J22 = cv.boxFilter(imgDiffYY, cv.CV_32F, (w,w))
J12 = cv.boxFilter(imgDiffXY, cv.CV_32F, (w,w))
# GST components calculations (stop)
# eigenvalue calculation (start)
# lambda1 = J11 + J22 + sqrt((J11-J22)^2 + 4*J12^2)
# lambda2 = J11 + J22 - sqrt((J11-J22)^2 + 4*J12^2)
tmp1 = J11 + J22
tmp2 = J11 - J22
tmp2 = cv.multiply(tmp2, tmp2)
tmp3 = cv.multiply(J12, J12)
tmp4 = np.sqrt(tmp2 + 4.0 * tmp3)
lambda1 = tmp1 + tmp4 # biggest eigenvalue
lambda2 = tmp1 - tmp4 # smallest eigenvalue
# eigenvalue calculation (stop)
# Coherency calculation (start)
# Coherency = (lambda1 - lambda2)/(lambda1 + lambda2)) - measure of anisotropism
# Coherency is anisotropy degree (consistency of local orientation)
imgCoherencyOut = cv.divide(lambda1 - lambda2, lambda1 + lambda2)
# Coherency calculation (stop)
# orientation angle calculation (start)
# tan(2*Alpha) = 2*J12/(J22 - J11)
# Alpha = 0.5 atan2(2*J12/(J22 - J11))
imgOrientationOut = cv.phase(J22 - J11, 2.0 * J12, angleInDegrees = True)
imgOrientationOut = 0.5 * imgOrientationOut
# orientation angle calculation (stop)
return imgCoherencyOut, imgOrientationOut
## [calcGST]
parser = argparse.ArgumentParser(description='Code for Anisotropic image segmentation tutorial.')
parser.add_argument('-i', '--input', help='Path to input image.', required=True)
args = parser.parse_args()
imgIn = cv.imread(args.input, cv.IMREAD_GRAYSCALE)
if imgIn is None:
print('Could not open or find the image: {}'.format(args.input))
exit(0)
## [main_extra]
## [main]
imgCoherency, imgOrientation = calcGST(imgIn, W)
## [thresholding]
_, imgCoherencyBin = cv.threshold(imgCoherency, C_Thr, 255, cv.THRESH_BINARY)
_, imgOrientationBin = cv.threshold(imgOrientation, LowThr, HighThr, cv.THRESH_BINARY)
## [thresholding]
## [combining]
imgBin = cv.bitwise_and(imgCoherencyBin, imgOrientationBin)
## [combining]
## [main]
imgCoherency = cv.normalize(imgCoherency, None, alpha=0, beta=1, norm_type=cv.NORM_MINMAX, dtype=cv.CV_32F)
imgOrientation = cv.normalize(imgOrientation, None, alpha=0, beta=1, norm_type=cv.NORM_MINMAX, dtype=cv.CV_32F)
cv.imshow('result.jpg', np.uint8(0.5*(imgIn + imgBin)))
cv.imshow('Coherency.jpg', imgCoherency)
cv.imshow('Orientation.jpg', imgOrientation)
cv.waitKey(0)
## [main_extra]

View File

@ -32,13 +32,13 @@ Keys:
# Python 2/3 compatibility # Python 2/3 compatibility
from __future__ import print_function from __future__ import print_function
import numpy as np
import cv2 as cv
import re import re
import numpy as np
from numpy import pi, sin, cos from numpy import pi, sin, cos
import cv2 as cv
# built-in modules # built-in modules
from time import clock from time import clock

View File

@ -36,11 +36,9 @@ class DummyTask:
def get(self): def get(self):
return self.data return self.data
if __name__ == '__main__': def main():
import sys import sys
print(__doc__)
try: try:
fn = sys.argv[1] fn = sys.argv[1]
except: except:
@ -86,4 +84,11 @@ if __name__ == '__main__':
threaded_mode = not threaded_mode threaded_mode = not threaded_mode
if ch == 27: if ch == 27:
break break
cv.destroyAllWindows()
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()

View File

@ -17,51 +17,62 @@ Keys:
# Python 2/3 compatibility # Python 2/3 compatibility
from __future__ import print_function from __future__ import print_function
import numpy as np
import cv2 as cv import cv2 as cv
def decode_fourcc(v): def main():
v = int(v)
return "".join([chr((v >> 8 * i) & 0xFF) for i in range(4)])
font = cv.FONT_HERSHEY_SIMPLEX def decode_fourcc(v):
color = (0, 255, 0) v = int(v)
return "".join([chr((v >> 8 * i) & 0xFF) for i in range(4)])
cap = cv.VideoCapture(0) font = cv.FONT_HERSHEY_SIMPLEX
cap.set(cv.CAP_PROP_AUTOFOCUS, False) # Known bug: https://github.com/opencv/opencv/pull/5474 color = (0, 255, 0)
cv.namedWindow("Video") cap = cv.VideoCapture(0)
cap.set(cv.CAP_PROP_AUTOFOCUS, False) # Known bug: https://github.com/opencv/opencv/pull/5474
convert_rgb = True cv.namedWindow("Video")
fps = int(cap.get(cv.CAP_PROP_FPS))
focus = int(min(cap.get(cv.CAP_PROP_FOCUS) * 100, 2**31-1)) # ceil focus to C_LONG as Python3 int can go to +inf
cv.createTrackbar("FPS", "Video", fps, 30, lambda v: cap.set(cv.CAP_PROP_FPS, v)) convert_rgb = True
cv.createTrackbar("Focus", "Video", focus, 100, lambda v: cap.set(cv.CAP_PROP_FOCUS, v / 100)) fps = int(cap.get(cv.CAP_PROP_FPS))
focus = int(min(cap.get(cv.CAP_PROP_FOCUS) * 100, 2**31-1)) # ceil focus to C_LONG as Python3 int can go to +inf
while True: cv.createTrackbar("FPS", "Video", fps, 30, lambda v: cap.set(cv.CAP_PROP_FPS, v))
status, img = cap.read() cv.createTrackbar("Focus", "Video", focus, 100, lambda v: cap.set(cv.CAP_PROP_FOCUS, v / 100))
fourcc = decode_fourcc(cap.get(cv.CAP_PROP_FOURCC)) while True:
status, img = cap.read()
fps = cap.get(cv.CAP_PROP_FPS) fourcc = decode_fourcc(cap.get(cv.CAP_PROP_FOURCC))
if not bool(cap.get(cv.CAP_PROP_CONVERT_RGB)): fps = cap.get(cv.CAP_PROP_FPS)
if fourcc == "MJPG":
img = cv.imdecode(img, cv.IMREAD_GRAYSCALE) if not bool(cap.get(cv.CAP_PROP_CONVERT_RGB)):
elif fourcc == "YUYV": if fourcc == "MJPG":
img = cv.cvtColor(img, cv.COLOR_YUV2GRAY_YUYV) img = cv.imdecode(img, cv.IMREAD_GRAYSCALE)
else: elif fourcc == "YUYV":
print("unsupported format") img = cv.cvtColor(img, cv.COLOR_YUV2GRAY_YUYV)
else:
print("unsupported format")
break
cv.putText(img, "Mode: {}".format(fourcc), (15, 40), font, 1.0, color)
cv.putText(img, "FPS: {}".format(fps), (15, 80), font, 1.0, color)
cv.imshow("Video", img)
k = cv.waitKey(1)
if k == 27:
break break
elif k == ord('g'):
convert_rgb = not convert_rgb
cap.set(cv.CAP_PROP_CONVERT_RGB, convert_rgb)
cv.putText(img, "Mode: {}".format(fourcc), (15, 40), font, 1.0, color) print('Done')
cv.putText(img, "FPS: {}".format(fps), (15, 80), font, 1.0, color)
cv.imshow("Video", img)
k = cv.waitKey(1)
if k == 27: if __name__ == '__main__':
break print(__doc__)
elif k == ord('g'): main()
convert_rgb = not convert_rgb cv.destroyAllWindows()
cap.set(cv.CAP_PROP_CONVERT_RGB, convert_rgb)

View File

@ -76,10 +76,10 @@ class App:
if __name__ == '__main__': if __name__ == '__main__':
print(__doc__)
import sys import sys
try: try:
fn = sys.argv[1] fn = sys.argv[1]
except: except:
fn = 'fruits.jpg' fn = 'fruits.jpg'
print(__doc__)
App(cv.samples.findFile(fn)).run() App(cv.samples.findFile(fn)).run()