1
0
mirror of https://github.com/opencv/opencv.git synced 2026-07-21 19:33:03 +04:00
Files
opencv/modules/core/test/test_operations.cpp
T
Vadim Pisarevsky f968fb969f Broadcasting element-wise engine for cv::Mat (+ cv::texpr) (#29426)
* experimental new arithmetics; work-in-progress

* continue working on new-gen arithmetic expressions

* * improved performance of the new add on small arrays
* added sub
* extended tests

* fixed potential bug when adding multi-channel array and a single-channel scalar

* improved const handling

* * added copyMask
* added mul/dev (without scale so far)

* * accelerated mul
* addedd scale to mul and div

* * done substantial refactoring; however a few more rounds of refactoring are ahead.
* added min, max, absdiff, addweighted.

* improved performance of the new arithmetic functions, but some of them are still slow, e.g. operations with mask have some bugs (that affect speed, not accuracy).

* * further (significantly) accelerated several functions, especially on small arrays: mul, binary ops with mask

* further polished the new arithmetic engine

* started integration of the new element-wise arithmetic engine into core

* big step forward. We now use the new engine inside cv::add, subtract, multiply, divide, absdiff, min and max.

* big progress:
* added bitwise operations
* fixed and accelerated compare
* ported regression tests to test new broadcasting behaviour of arithmetic functions

* lot's of improvements in compare, divide, addWeighted!

* lot's of small and big performance improvements in the new arithmetics

* * some more optimizations; parsing texpr-expressions is now faster as well

* port new_arithm to Linux/x86: dispatch guards, scalar-Mat compat fallback, dnn shape-contract fixes

Core:
- arithm.simd.hpp: CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY guards (the file is included
  once per dispatched mode on x86), vx_load_expand instead of the 128-bit v_load_expand,
  VTraits::vlanes() instead of ::nlanes
- arithm.cpp/precomp.hpp: compat fallback for scalar-like Mat operands (1x1, 1xcn/cnx1,
  4x1 CV_64F - java/python tuples, operator-(Mat, Matx)): treated as a per-channel scalar
  ONLY when the shapes are not broadcast-compatible, so every valid numpy-style broadcast
  keeps its meaning and calls that would otherwise throw get the 4.x semantics

DNN (fallout of the stricter shape semantics, found by the new engine):
- dict.hpp: DictValue relied on fresh AutoBuffer having size()==fixed_size; allocate explicitly
- batch_norm: weights_/bias_ are 1-D [n] now; 0/1-D forward runs on exact-shape 1-D views
- net_impl2: extend the post-forward sanity check to non-temp outputs - a layer that
  reallocates its preallocated output tensor now fails loudly instead of silently
  detaching the result from the graph
- LSTM/LSTM2 batchwise (layout=1): getMemoryShapes now matches what forward() writes
  (ONNX: Y=(batch,seq,dirs,hid), Yh/Yc=(batch,dirs,hid)); forward assembles seq-major
  results in a local buffer and transposes INTO the preallocated outputs in place

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* u8/s8 multiply: exact integer SIMD path on non-FP16 builds (3-10x vs 5.x)

The unit-scale branch of vecBinaryKernel already supported a separate work-vector
type Wvec1 (used by the ARM f16 build and by u16/s16 everywhere), but on x86 the
u8/s8 same-type multiply still went through the f32 hub. Route it through
v_uint16/v_int16: products of 8-bit values fit exactly (255^2 < 2^16), the
saturating pack on store gives bit-exact results at half the vector traffic.

Also fix a latent kernel bug this exposed: the unit-scale branch stepped by
Wvec's lane count while loading/storing Wvec1 vectors. All previous Wvec1
instantiations had equal lane counts, but u8's v_uint16 has 2x the lanes of
v_float32 - the pairs overlapped (50% redundant work) and the tail backoff
could write VECSZ bytes past the row end. The branch now derives its step,
offsets and tail condition from Wvec1 itself.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* vecBinaryKernel: constexpr Op::useScalar instead of a runtime-only scale check

Every binary op functor now declares whether it consumes the scale scalar
(params[0]): true only for mul and the two div variants. Ops that ignore it
(add/sub/min/max/absdiff) take the fast 2-arg branch unconditionally - the
'scalar == 1' check used to fail for them (their params[0] is 0), sending them
through the preproc branch, and the condition now folds at compile time.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* restore cv::hal::mul8u as a wrapper over the element-wise engine

The symbol is still declared in core/hal/hal.hpp and called directly by external
code (the G-API fluid backend in opencv_contrib), but its implementation went
away with the old arithm kernels. Forward it to getMulFunc(CV_8U, CV_8U) - with
scale==1 it lands on the new exact integer SIMD path.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* silence every new-arithm warning reported by CI (ARM64/Mac) and gcc 15

- arithm.cpp: bitwise_op_ocl and the actualScalarDepth/coerceTypes helpers are
  consumed only by the OpenCL paths - guard them with HAVE_OPENCL; haveScalar in
  cv::compare is read only inside CV_OCL_RUN - CV_UNUSED for OpenCL-less builds
- arithm_expr.hpp: declare getBitwiseFunc/getNotFunc/getAddWeightedFunc next to
  the other per-op entry points (-Wmissing-prototypes in arithm.dispatch.cpp)
- arithm.simd.hpp: define CV_SIMD_16F to 0 when FP16 SIMD is absent (-Wundef);
  {}-init the expandScalar staging buffers (-Wmaybe-uninitialized: they are
  fully written before use, but the compiler cannot prove it with runtime
  vector widths); rename the compare kernel's lambda parameter (-Wshadow)
- arithm_expr.cpp: rename the exec tile-lambda's hot-field locals that shadowed
  TExpr members and outer locals (-Wshadow)
- test_new_arithm_extensive.cpp: rename the name-generator lambdas' parameter
  shadowing the INSTANTIATE macro's own (-Wshadow), drop an unused variable

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* restore 4.x scalar semantics for the bindings' 4x1 CV_64F Scalar columns

The python/java bindings materialize numbers and tuples as a 2-D 4x1 CV_64F
Mat - or UMat, when the call carries UMat arguments. Three CI-reported python
failures came from those pseudo-scalars reaching the engine as arrays:

- absdiff(int_arr, 0): the (4,1) column is broadcast-COMPATIBLE with a 1-D
  array, so numpy semantics silently won - an outer-product f64 result instead
  of the int per-channel-scalar one;
- subtract(u8 4x8x4, (40,)): same, by the rows==4 coincidence;
- multiply(UMat, 2., dst=UMat): the scalar arrives as a UMAT, which the
  scalar detection did not recognize at all.

isScalarArg now treats the exact bindings shape - 2-D 4x1 CV_64F single-channel
Mat/UMat against a <=4-channel array - as a scalar UNCONDITIONALLY (a 1-D [4]
array has dims==1 and still broadcasts). One exception, decided in arithm_op:
when the partner is itself a tiny scalar-shaped array, both are honest data and
ride the broadcast (compare(Mat 4x1, Mat 1x1) - issue #8999 - stays elementwise).

Small-array discipline, this all runs per engine call: the probes read Mat/UMat
fields directly (rows == 4 alone rejects almost everything, no _InputArray
getter dispatch), and a UMAT scalar's 32 bytes are copied into a caller-stack
buffer - no heap, no getMat mapping. Measured: no latency change on 4x4/16x16
element-wise calls.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* cv::texpr: std::string_view -> const std::string& in the public API

string_view in an exported signature breaks some CUDA toolchain builds, and for
short expression strings the difference is immaterial (SSO, parsed once). The
parser internals keep string_view - the argument converts implicitly. Also drop
the now-unused <string_view> include from cvstd.hpp, so the header does not
reach every nvcc TU.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* compare boundary-rewrite: fixed 4-slot kind/bound arrays instead of AutoBuffers

A CONST operand is capped at 4 channels (addConst), so the per-channel
kind/bound staging needs no dynamic buffers - plain int[4]/double[4], with a
CV_Assert on the contract. This is also what gcc's -Wmaybe-uninitialized was
flagging (it could not see the AutoBuffer's inline storage get filled).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* element-wise engine: unary math kernels (sqrt/exp/log/sin/cos/tanh/erf/relu) + select

New dispatched pair math.simd.hpp / math.dispatch.cpp - the unary/ternary sibling
of arithm.simd.hpp:

- vecUnaryKernel: T -> T over f16/bf16/f32/f64 on top of the intrin_math
  primitives (v_exp/v_log/v_sin/v_cos/v_sqrt/v_erf/v_max). f32/f64 compute
  natively, f16/bf16 ride the f32 hub inside the kernel (vx_load_pair_as /
  v_store_pair_as) - no materialized casts. Continuity collapse + the halide
  right-edge backoff, suppressed in-place (it would re-apply Op to
  already-written values). tanh = (e^2x-1)/(e^2x+1) with the input clamped to
  +/-10 (f32) / +/-20 (f64) - unclamped saturation hits inf/inf = NaN. erf has
  no f64 SIMD primitive: std::erf per lane.
- selectKernel(mask, x, y): 1-byte mask expanded to lane width and tested
  against zero in the INTEGER domain (immune to DAZ/FTZ), branches of any
  depth by element size, broadcast branches supported.
- emitUnary: math over a float input is T -> T now (f16 in -> f16 out, native
  kernel when input and result depths match); integer inputs still compute in
  the float domain and land in f32.
- emitTernary/select: literal branches are typed via typedConstFrom (an
  OP_CAST of a depth-less flex const crashed); a non-1-byte mask is normalized
  by an explicit "mask != 0" compare, never a value cast.

texpr already parsed the function names - they now execute. Tests: per-depth
accuracy of all 8 ops against the double std:: reference, integer input,
in-place, select over 4 depths / const branch / float mask.

Perf vs the classic kernels (1920x1080 f32, 16 threads, AVX2): exp 3.7x,
log 2.6x, sqrt 5.7x faster; polarToCart expressed as (r*cos(a), r*sin(a)) 4.0x.
Accuracy improves too (max rel err vs f64 reference): exp 8.1e-8 vs 2.1e-7,
log 8.0e-8 vs 1.5e-7.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* engine: OP_COPY_MASK folded into OP_SELECT; selectKernel moved to arithm.simd.hpp

copyMask(dst, mask, src) is select(mask, src, dst) - one masking primitive
instead of two. The compiler emits the masked-op tail as
addInsn(OP_SELECT, mask, r, out, out): the output slot rides as both arg2 and
the result, so unmasked elements are preserved by reading them back through
the b-branch. OP_COPY_MASK, copyMaskKernel and getCopyMaskFunc are gone.

selectKernel (moved from math.simd.hpp to arithm.simd.hpp) inherits every
copyMaskKernel optimization:
- the interleaved multichannel fast path (2..4 channels under a per-pixel
  mask: expand the mask once per VECSZ rows, v_store_interleave across lanes);
- the per-row scalar path with the row-skip when the selected source row IS
  dst (the "leave the output untouched" half of copyMask);
- plus the select-specific ones: branch broadcasts (stepx == 0) and the
  right-edge tail backoff under dst-aliases-a-branch - safe because re-running
  select over already-blended elements is idempotent; only dst == mask keeps
  the backoff off (the store would rewrite mask bytes before the re-read).

Masked-add perf is on par with the old copyMask (1280x720, 1 thread: 8UC3
204 -> 198 us, 32FC3 1395 -> 1344, 8UC1/32FC1 within noise). Full core suite
24117 green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* engine: dedicated vectorized pow kernel (moved from arithm to math.simd.hpp)

pow was the last scalar-only binary op (scalarBinaryKernel + std::pow, f32/f64
only). The new powKernel keeps exact std::pow semantics and is T x T -> T over
all four float depths (f16/bf16 via the f32 hub):

- scalar exponent (the dominant call shape - texpr literals ride as 0-dim
  broadcast consts) is dispatched PER ROW to the special cases:
  y==2 -> x*x, y==3 -> x*x*x, y==0.5 -> v_sqrt, y==1 -> copy, y==0 -> fill 1;
- everything else - including a per-element exponent array - runs the general
  vectorized exp(y * log(x)) path, valid for x > 0; a vector pair containing
  any x <= 0 lane falls back to scalar std::pow for that pair (v_check_any),
  which preserves every std::pow subtlety: signed results for integer y on
  negative bases, NaN for fractional y, the x == 0 family;
- no right-edge tail backoff: pow is not idempotent, in-place calls finish
  rows in the scalar tail.

Perf vs the classic cv::pow (1920x1080 f32, 16 threads, AVX2): p=2 1.4x
(classic special-cases it too), p=3 6.1x, p=0.5 6.3x, fractional p 4.5x with
slightly better accuracy (6.1e-7 vs 7.4e-7 max rel err). Tests: exponent
sweep 2/3/0.5/1/0/2.5/-1.5 vs the double std::pow reference on f32/f64,
negative bases (exact signed cubes, NaN for fractional), array exponent.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* powKernel: halide right-edge tail backoff in every SIMD loop

Same shape as vecBinaryKernel: the final partial vector re-processes
[width - VECSZ*2, width) instead of finishing scalar, suppressed when dst
aliases an input (pow is not idempotent - the overlap region must be
recomputed from an untouched source, which the no-alias case guarantees).

Modest measured win (~2% on ROI rows for the special-cased exponents; the
general path tail was already cheap - modern libm powf is fast), no
regressions; mainly aligns the kernel with the house style, where every
SIMD loop ends vector-wide.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix MSVC 2019 C2975: function-local constexpr as a template argument inside a lambda

MSVC 2019 loses the constexpr-ness of function-local constants (LOCAL_OPS,
MAX_DIMS, ...) when they are used as template arguments inside a lambda body
(AutoBuffer<Slice, LOCAL_OPS> / std::array<int, MAX_DIMS> in the parallel
bodies of BroadcastOp::run and TExpr::exec). Hoist them to namespace scope -
no behavior change.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* ocl_arithm_op: route 16U multiply to the CPU engine on Apple OpenCL

The Apple OpenCL driver miscompiles the 16U multiply kernel: products near
the top of the u16 range come back wrapped instead of saturated (CPU vs GPU
NORM_INF up to 65535 in OCL_Arithm/Mul.Mat CV_16U cases). The same arithm.cl
kernel is correct on Intel NEO and NVIDIA drivers - verified not to reproduce
on Linux/Intel iGPU - so gate the decline to __APPLE__ only; the CPU engine
computes 16u multiply exactly (integer SIMD path).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* engine: neg/abs as compositions, clamp kernel, ** and ?: operators, abs(a-b) peephole

- OP_NEG and OP_ABS need no kernels: neg = sub(0, a), abs = absdiff(a, 0) -
  including the engine absdiff auto-type rule (signed |a| lands in the
  UNSIGNED type of the same width: |SHRT_MIN| fits u16 exactly instead of
  saturating; NB the public cv::absdiff auto depth keeps the source type for
  4.x compatibility - values agree, the depth rule is the engine own).
- peephole: abs(x - y) rewrites to absdiff(x, y) ALWAYS. On integers the
  literal semantics differ (the subtract saturates first: u8 gives
  max(x-y, 0)), but whoever writes abs(a - b) means absdiff - we deliberately
  hand out the useful semantics instead of the saturation artifact. The just-
  emitted OP_SUB is retired via the moveToOutput manoeuvre, so the program
  shrinks to the single absdiff instruction. abs(x), abs(x - 0) and
  absdiff(x, 0) all give one result.
- OP_CLAMP kernel (arithm.simd.hpp): v_min(v_max(x, lo), hi) over
  u8/s8/u16/s16/u32/s32/f32 (+f64 with 64-bit SIMD), scalar f16/bf16/64-bit
  ints; lo/hi may broadcast (the common clamp(img, a, b) shape) or be full
  arrays; the tail backoff stays on under dst-aliases-x (clamp is idempotent).
  emitTernary types literal bounds via typedConstFrom (same flex-const crash
  select had) and keeps the auto result type pinned to x.
- parser: "a ** b" == pow(a, b), precedence above * /, RIGHT-associative
  (a ** 2 ** 3 == a ** 8); "cond ? a : b" == select(cond, a, b), precedence
  below everything, right-associative chains (f1 ? a : f2 ? b : c) work
  without parentheses. parseTernary() is the expression entry point now.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* cv::exp/log/sqrt on the engine via math_op; hal functions wrapped as engine kernels

math_op is the master function of the unary math family (the arithm_op
analogue): same-shape same-type output over f16/bf16/f32/f64 (classic
exp/log accepted f32/f64 only - the half floats are new), two tiers:
- small (<= 100000 elements) and continuous: call the kernel DIRECTLY over
  the flattened data - no TExpr, no broadcastOp, no parallel_for setup;
- everything else: the usual single-instruction program via compile()/exec()
  (parallelism for large arrays, real steps for ROIs).

getMathFunc routes OP_EXP/OP_LOG at f32/f64 through the full cv::hal stack -
an external vendor HAL (CALL_HAL), IPP, or the built-in table kernels,
whichever is installed - by wrapping hal::exp32f/exp64f/log32f/log64f as
engine kernels with the function pointer in TKernel::userdata, the same
mechanism castKernel uses for core BinaryFuncs. The engine adds tiling and
parallelism on top, so every tier gets the best available scalar-span
implementation. v_exp/v_log remain for f16/bf16 (the f32 hub) and the ops
hal has no entry points for.

v_log_default_32f: the degree-8 polynomial is evaluated by Estrin pairing
(4 dependent levels) instead of an 8-FMA Horner chain (~5% on the f16 hub
path). An exp64 Taylor-without-division rewrite was tried and benched SLOWER
than the Cephes Pade scheme (the evaluation is FMA-throughput-bound, and
vdivpd pipelines well enough) - reverted; a table-based reduction is the only
way further there.

cv::exp f32 (16 threads, AVX2+IPP build), old -> new: 640 elements
0.16 -> 0.15 us, 16k 2.79 -> 2.49, 640x480 47 -> 20, 1920x1080 452 -> 60 us
(the old CPU loops were single-threaded); f64 exp 1080p 1295 -> 161 us.
No size regresses; small arrays now run at installed-HAL speed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* getMathFunc: IPP tier + raw-HAL probing; the exp/log table kernels are deleted

The raw cv_hal_* entry points return int for a reason: without an installed
HAL they are stubs returning CV_HAL_ERROR_NOT_IMPLEMENTED. getMathFunc now
selects the exp/log implementation in three tiers:
 1. HAVE_IPP && ipp::useIPP(): ippsExp/ippsLn through thin int adapters (IPP
    is not routed through the cv_hal_ hooks, so it needs its own tier);
 2. the raw cv_hal_exp32f/... hook, PROBED once with a 1-element call on the
    safe input 1.0 (cached in magic statics): implemented -> wrapped as an
    engine kernel with the function pointer in TKernel::userdata;
 3. the engine own v_exp/v_log kernels.
Whichever wins, the engine adds tiling and parallelism on top.

The EXPTAB/LOGTAB table kernels and their tables (~790 lines in
mathfuncs_core.simd.hpp + mathfuncs.cpp) are DELETED: they benched within
~15% of v_exp/v_log, not worth a second implementation. The public
cv::hal::exp32f/exp64f/log32f/log64f keep their contract - CALL_HAL, then
IPP, then the built-in implementation - but the built-in is now the engine
vector kernel via ew::mathSpanEngine (one contiguous span, exported from
math.dispatch.cpp).

All unary math kernels (vec/scalar/hal wrappers, pow) also handle the
vertical-broadcast tile (s0y == 0, a row expanded into a matrix): the first
row is computed, the rest are memcpy of it - transcendentals cost far more
than a row copy.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* texpr: hypot(x, y) binary op (alias: mag)

hypot = sqrt(x^2 + y^2), NAIVE like cv::magnitude (not the overflow-safe
std::hypot), computed in the float work type; kernels for the four float
depths only (T x T -> T; integer inputs ride the usual f32-compute + cast).
A 10-line EwHypot functor on top of vecBinaryKernel in arithm.simd.hpp -
broadcast branches, continuity collapse and the tail backoff come for free.
Registered in the parser as both "hypot" (the C/numpy name) and "mag" (the
cv::magnitude-flavored alias). A building block for the future cartToPolar.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* texpr: atan2(y, x) binary op - radians, standard C range

v_atan2 (arithm.simd.hpp, generic over the universal-intrinsic float vector):
the fastAtan2 minimax polynomial from mathfuncs_core v_atan_f32 reworked to
plain radians - the 180/pi factor dropped from the coefficients and the C
quadrant logic instead of the [0, 360) wrap, so the result matches std::atan2
over (-pi, pi]. Measured absolute accuracy ~1.6e-4 rad. (v_atan_f32 itself is
untouched - cv::phase/fastAtan2 keep their degree semantics.)

EwAtan2 rides vecBinaryKernel: f16/bf16/f32 through v_atan2 (the f32 hub),
f64 through exact scalar std::atan2. arg0 = y, arg1 = x, like std::atan2;
float depths only, same emitBinary policy as pow/hypot. Parser name "atan2".
Together with hypot this completes the cartToPolar building blocks.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix the RISC-V RVV build and two ARM64 warnings

The new f64 kernel registrations (hypot, pow, the unary math family) gate on
CV_SIMD_64F || CV_SIMD_SCALABLE_64F, but the vx_setall_as(const double*,
v_float64&) helper family in arithm.simd.hpp was still CV_SIMD_64F-only -
scalable platforms (RVV) have v_float64 with CV_SIMD_64F == 0, so
vecBinaryKernel<double, ...> failed to instantiate there. Widen the helper
gate to match (verified with a riscv64 rv64gcv cross-build of opencv_core -
the engine f64 paths now vectorize on RVV instead of not compiling).

cv::exp/cv::log: the depth local is consumed by CV_OCL_RUN only - CV_UNUSED
for OpenCL-less builds (ARM64 -Wunused-variable).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* silence the remaining ARM64 gcc warnings

- compare boundary-rewrite: {}-init the fixed kind/bound arrays (filled for
  every channel used below, but gcc cannot prove it across the cn <= 4 loop);
- cv::exp/log: [[maybe_unused]] on the depth local (consumed by CV_OCL_RUN
  only), instead of the CV_UNUSED idiom;
- AutoBuffer::reserve: a targeted -Wmaybe-uninitialized suppression around
  the live-element copy loop - only [0, sz) is read, all written before, but
  gcc inlining a grow-from-inline-storage chain cannot see that. An
  annotation for the analyzer, no behavior change.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* saturating 32-bit add/sub kernels; cv::texpr python binding; two CI warnings

- v_add_sat/v_sub_sat for v_int32/v_uint32, local to arithm.simd.hpp for now
  (the plan is to grow them into proper universal intrinsics later): NEON
  single-instruction vqadd/vqsub, elsewhere the Hacker Delight bit tricks
  over universal intrinsics (u32 add is 2 ops: or with the wrapped-compare
  mask). EwAdd/EwSub overload vec() for the 32-bit lanes and getAddSubFunc
  routes 32S/32U T->T through vecBinaryKernel instead of the former pure
  scalar kernel. Semantics unchanged - the scalar int64 tail already
  saturated; directed boundary tests added (both rails, 0 - INT_MIN, u32
  cases, a full-range random block vs an exact int64 reference).
  640x480 32S add: 0.48x of 5.x -> parity (memory-bound); 1080p: 6-8x.

- cv::texpr becomes CV_EXPORTS_W: python gets cv.texpr(expr, [inputs]) ->
  tuple of ndarrays, so `res, = cv.texpr(...)` and `mag, ang = cv.texpr(...)`
  unpacking both work. modules/python/test/test_expr.py covers arithmetic,
  the fused abs(a-b), casts, broadcasting, ?: and ** operators, math
  functions vs numpy, clamp, named temporaries, tuple outputs, the one-line
  cartToPolar and the int32 saturation cases.

- warnings: {}-init the parser args array (gcc -Wmaybe-uninitialized on
  Ubuntu 20/22); the compare short-row block gates sizeof(T) <= 4 as
  constexpr so the f64 instantiation does not leave set-but-unused locals
  (gcc 9 -Wunused-but-set-variable).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* arithm_op: direct-kernel fast path for small continuous arrays

Building and compiling the 1-instruction program plus the BroadcastOp setup
costs ~40-250ns per call - negligible on big images, dominant at 127x61-class
sizes where the classic 5.x functions were 1.3-2x faster. Mirror math_op two
tiers in arithm_op: two same-type same-shape continuous arrays, no mask, no
scalar, result depth == input depth, <= 100k elements -> call the T x T -> T
kernel directly over the flattened elements (checks ordered cheapest-first).
Applies to add/subtract/min/max/absdiff/multiply/addWeighted/and/or/xor;
compare and divide lower to more than a single kernel (boundary rewrites, int
guards) and keep the ordinary path. addWeighted falls through automatically
for the 32/64-bit int types whose lowering is wide-compute + cast
(getElemwiseFunc returns no direct kernel there).

127x61 vs 5.x, was -> now: add/subtract 8UC1 0.76x -> 1.3x, min/max u8
0.6x -> ~1x, addWeighted 1.0x -> 1.1-1.4x (32SC1 stays 4.5x); the one
remaining laggard is add/sub 32SC1 (0.74-0.82x) - the price of the new
SATURATING semantics (7-instruction AVX2 emulation vs the wrapping single
add of 5.x; single-instruction on NEON).

The 127x61 size is ADDED PERMANENTLY to the arithmetic/addWeighted/compare
perf grids: per-call overhead regressions in these base functions must be
caught by CI, not discovered by users.

dst creation goes through createSameSize (whole-shape transfer including
layout and future metadata, not piecemeal dims+sizes) here and in math_op.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* cv::pow rebuilt on the engine; integer-exponent and 1/sqrt(x) kernel branches

Routing: p = 0/1/2 keep their early special cases (fill/copy/multiply); an
INTEGER array with an INTEGER power keeps the classic iPow multiply chain -
bit-exact compatibility, including its wrap-around quirks (iPow squares in
int, so e.g. pow(255,4) on u8 wraps negative and saturates to 0 - somebody
may rely on that). Everything else goes through the engine with the math_op
two-tier scheme: small continuous arrays call powKernel directly (the
exponent rides as a broadcast T scalar), the rest run the tiled parallel
program. Integer arrays with fractional powers compute in the float domain
and saturate back; the 32U/64-bit depths (classic iPow asserted on them) and
f16/bf16 (the classic float path misread them) now just work.

powKernel gets two new per-row exponent branches:
- p == -0.5: 1/v_sqrt(x) (the classic path used IPP ippsInvSqrt_A21, a
  21-bit approximation; ours is exact - slightly slower on small arrays,
  4.5x faster at 1080p via parallelism);
- any other INTEGER p (|p| <= 65536): LSB-first binary exponentiation, the
  same multiply chain and order as iPow, fully vectorized - a few ulp
  accurate vs ~2e-7 of exp(p*log x), and exact on non-positive bases (the
  sign falls out of the multiplies, 0^negative divides to inf) - no scalar
  patching.

cv::pow f32 vs 5.x: p=0.5 365 -> 61 us at 1080p (6x), p=3 7.7x, p=5 7x AND
faster at every size (the old scalar chain: 0.81 -> 0.47 us at 127x61),
p=2.5 5.3x. The s16^5 iPow path is untouched (118.7 == 118.5 us).
pow_exponents accuracy tests extended to 11 exponents x f32/f64 against the
double std::pow reference.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* perf: SANITY_CHECK_NOTHING for the tests whose grids got the 127x61 size

The 127x61 entry added to guard per-call overhead has no regression data in
opencv_extra, so the legacy SANITY_CHECK in addWeighted/compare failed on CI
(locally it passes silently without the test-data path). Accuracy of both
functions is covered by the accuracy suite; the perf tests should measure
time. PatchNaNs/finiteMask keep their SANITY_CHECK - their grids are
untouched.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix a temp-buffer double release in the liveness pass ("d*d" crash)

When the same temp is passed as SEVERAL arguments of its last-use
instruction (e.g. the named-intermediate expression "d = {0} - {1}; d*d",
where the MUL consumes slot d twice), the buffer-reuse scan pushed the
temp's physical buffer onto the free list once per argument. That
overflows the ntemps-sized freeBufs array (caught by the AutoBuffer range
check in Debug: python test_expr.py::test_named_temporary) and, in larger
programs, would hand the same physical buffer to two live temps.

Release the buffer once by retiring lastUse[t] after the first hit.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* executor: recalibrate opCost to vectorized cycles + clamp the stripe count

The per-element op costs fed into the parallel_for_ stripe hint were
scalar-era estimates (~20x above the vectorized reality: the atan2/exp
polynomials run at ~1.5 cycles/element, not 30). The hint therefore split
transcendental/divide work into hundreds of ~1 us jobs, which the
macOS/GCD backend dispatches poorly under sustained load, on top of the
P/E-core equal-share straggler effect. Measured on M4 Max (12P+4E),
sustained medians @1920x1080 f32: texpr atan2 320 -> 133 us, cv::exp
280 -> 141 us, cv::log 301 -> ~200 us, cv::pow(x,2.5) 388 -> 376 us;
the PR tables' math rows improved ~1.5-2x across the board.

- opCost is now in units of ~1/4 cycle/element of the SIMD kernels:
  cheap ops 1 (unchanged), div/sqrt/hypot/convert_scale 10 -> 3,
  transcendentals 30 -> 6.
- the stripe hint is clamped by min(4*nthreads, max(32, 3*nthreads)):
  ~4 stripes/thread is plenty of granularity for element-wise work, and
  the ceiling is 32 pieces except on machines with many (heterogeneous)
  cores, where anything coarser than ~3 pieces/worker turns the slow
  cores into equal-share bottlenecks (measured: 32 stripes on 16 threads
  is the worst point of the curve - 193 us vs 137 us at 48 for atan2).
  getNumThreads() is clamped from below (WINRT/plugin backends may
  report 0).

Not addressed here (needs cross-machine data, M2/M3 Ultra): streaming
memory-bound ops saturate the M4 Max fabric at ~8 fat stripes and E-core
participation only adds contention - a cost model cannot express that;
candidate follow-up is a bytes-aware clamp or a GCD-backend-level fix.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* multiply: v_mul_sat integer kernels (full product clamped to the type)

v_mul_sat(V, V) -> V for u8/s8/u16/s16/u32/s32 - the full-precision
product clamped to the lane type, which is exactly cv::multiply's integer
semantics at scale == 1. Local to arithm.simd.hpp for now, next to
v_add_sat/v_sub_sat, to be promoted into proper universal intrinsics
later. NEON: widening vmull + saturating narrow (vqmovn); other backends:
the portable v_mul_expand + saturating v_pack composition for 8/16-bit
lanes. 32-bit lanes have no universal widening multiply (no v_mul_expand
for s32), so the 32-bit integer fast path is NEON-only for now and the
other backends keep the previous f64 work-vector kernels (which measure
well on x86 with IPP-free AVX2).

EwMul::vec() now routes the integer lane types through v_mul_sat, and
getMulFunc_ passes the NATIVE lane vector as the scale==1 fast-path type:
whole-register loads/stores, the widening happens inside the multiply.
Replaces both the half-register widening loads (u8/s8/u16/s16) and the
scalar-equivalent f64 path for 32S/32U on NEON.

M4 Max, 640x480 (the sizes where the old kernels lost to carotene):
8U 22.0 -> 13.6 us, 8S 15.0 -> 11.1, 16S 21.2 -> 17.4, 32S 84.8 -> 30.5
(parity with the classic path everywhere, 32S was 0.38x). 1920x1080:
8S 1.30x -> 1.78x, 16S 2.57x -> 2.98x, 32S 2.20x -> 4.02x vs 5.x.
Correctness: exhaustive 8-bit (all 65536 pairs per sign), directed
saturation corners for 16/32-bit (46341^2, INT_MIN*-1, 65536*65536, all
sign combinations) against an exact int64 reference.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* NEON: make v_cvt_f64(v_int32) exact (was via f32, losing bits > 2^24)

The NEON implementations of v_cvt_f64/v_cvt_f64_high for v_int32 did
s32 -> f32 -> f64 (vcvt_f32_s32 + vcvt_f64_f32), silently rounding any
|x| > 2^24. Every vectorized f64 work path with int32 inputs on AArch64
was affected: the engine's addWeighted/divide 32S kernels, convertTo
32S -> 64F, etc. Found via addWeighted 32SC1 on values ~1e9: max error
was 32 vs the exact double reference (the classic carotene path is worse
still - it computes in f32 end-to-end with f32-truncated weights, max
error 96 on the same data).

The exact sequence sxtl + scvtf (vmovl_s32 + vcvtq_f64_s64) is the same
2 instructions, so there is no cost. addWeighted 32SC1 on the engine now
matches the exact-double reference bit-for-bit and stays at parity/1.4x
vs the classic path (640x480/1920x1080).

Pre-existing upstream bug (same code in 4.x) - worth a standalone
backport with directed large-value tests.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* math_op: drop the temporary direct-IPP tier for exp/log

Upstream moved the IPP math wrappers into the hal/ipp HAL module (cv_hal_exp32f/
log32f & co now resolve to ipp_hal_* which honor cv::ipp::useIPP via
CV_HAL_CHECK_USE_IPP). The engine's single probeHalUnary(cv_hal_*) probe already
picks that up uniformly, so the stopgap #ifdef HAVE_IPP ippExp/ippLog tier and its
ipp::useIPP() branch in getMathFunc are now redundant - removed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* arithm: restore cv::hal::and8u/or8u/xor8u/not8u as engine wrappers

These public CV_EXPORTS entry points (core/hal/hal.hpp) lost their definitions when
the bitwise ops moved to the element-wise engine, but they are still declared and called
by other modules (opencv_objdetect's aruco) and external code - the link broke with
undefined references to cv::hal::and8u/xor8u. Restore them as thin forwarders over the
engine's byte-wise bitwise kernels (getBitwiseFunc / getNotFunc), mirroring the existing
mul8u wrapper. CV_Assert guards the kernel lookup.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* blobdetector: guard empty contour when computing blob radius

The new AutoBuffer leaves its tail uninitialized for trivial types, which surfaced a
-Wmaybe-uninitialized in findBlobs where the median of per-point distances is read. Use a
std::vector, default the radius to 0, and compute the median only for a non-empty contour -
no unproven size invariant.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-18 01:26:36 +03:00

1659 lines
57 KiB
C++

/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "test_precomp.hpp"
#include "opencv2/ts/ocl_test.hpp" // T-API like tests
#include <fenv.h>
namespace opencv_test {
namespace {
class CV_OperationsTest : public cvtest::BaseTest
{
public:
CV_OperationsTest();
~CV_OperationsTest();
protected:
void run(int);
struct test_excep
{
test_excep(const string& _s=string("")) : s(_s) { }
string s;
};
bool SomeMatFunctions();
bool TestMat();
template<typename _Tp> void TestType(Size sz, _Tp value);
bool TestTemplateMat();
bool TestMatND();
bool TestSparseMat();
bool TestVec();
bool TestMatxMultiplication();
bool TestMatxElementwiseDivision();
bool TestDivisionByValue();
bool TestInplaceDivisionByValue();
bool TestMatMatxCastSum();
bool TestSubMatAccess();
bool TestExp();
bool TestSVD();
bool operations1();
void checkDiff(const Mat& m1, const Mat& m2, const string& s)
{
if (cvtest::norm(m1, m2, NORM_INF) != 0) throw test_excep(s);
}
void checkDiffF(const Mat& m1, const Mat& m2, const string& s)
{
if (cvtest::norm(m1, m2, NORM_INF) > 1e-5) throw test_excep(s);
}
};
CV_OperationsTest::CV_OperationsTest()
{
}
CV_OperationsTest::~CV_OperationsTest() {}
#define STR(a) STR2(a)
#define STR2(a) #a
#define CHECK_DIFF(a, b) checkDiff(a, b, "(" #a ") != (" #b ") at l." STR(__LINE__))
#define CHECK_DIFF_FLT(a, b) checkDiffF(a, b, "(" #a ") !=(eps) (" #b ") at l." STR(__LINE__))
#if defined _MSC_VER && _MSC_VER < 1400
#define MSVC_OLD 1
#else
#define MSVC_OLD 0
#endif
template<typename _Tp> void CV_OperationsTest::TestType(Size sz, _Tp value)
{
cv::Mat_<_Tp> m(sz);
CV_Assert(m.cols == sz.width && m.rows == sz.height && m.depth() == cv::traits::Depth<_Tp>::value &&
m.channels() == DataType<_Tp>::channels &&
m.elemSize() == sizeof(_Tp) && m.step == m.elemSize()*m.cols);
for( int y = 0; y < sz.height; y++ )
for( int x = 0; x < sz.width; x++ )
{
m(y,x) = value;
}
double s = sum(Mat(m).reshape(1))[0];
CV_Assert( s == (double)sz.width*sz.height );
}
bool CV_OperationsTest::TestMat()
{
try
{
Mat one_3x1(3, 1, CV_32F, Scalar(1.0));
Mat shi_3x1(3, 1, CV_32F, Scalar(1.2));
Mat shi_2x1(2, 1, CV_32F, Scalar(-1));
Scalar shift = Scalar::all(15);
float data[] = { sqrt(2.f)/2, -sqrt(2.f)/2, 1.f, sqrt(2.f)/2, sqrt(2.f)/2, 10.f };
Mat rot_2x3(2, 3, CV_32F, data);
Mat res = one_3x1 + shi_3x1 + shi_3x1 + shi_3x1;
res = Mat(Mat(2 * rot_2x3) * res - shi_2x1) + shift;
Mat tmp, res2;
cv::add(one_3x1, shi_3x1, tmp);
cv::add(tmp, shi_3x1, tmp);
cv::add(tmp, shi_3x1, tmp);
cv::gemm(rot_2x3, tmp, 2, shi_2x1, -1, res2, 0);
cv::add(res2, Mat(2, 1, CV_32F, shift), res2);
CHECK_DIFF(res, res2);
Mat mat4x4(4, 4, CV_32F);
cv::randu(mat4x4, Scalar(0), Scalar(10));
Mat roi1 = mat4x4(Rect(Point(1, 1), Size(2, 2)));
Mat roi2 = mat4x4(Range(1, 3), Range(1, 3));
CHECK_DIFF(roi1, roi2);
CHECK_DIFF(mat4x4, mat4x4(Rect(Point(0,0), mat4x4.size())));
Mat intMat10(3, 3, CV_32S, Scalar(10));
Mat intMat11(3, 3, CV_32S, Scalar(11));
Mat resMat(3, 3, CV_8U, Scalar(255));
CHECK_DIFF(resMat, intMat10 == intMat10);
CHECK_DIFF(resMat, intMat10 < intMat11);
CHECK_DIFF(resMat, intMat11 > intMat10);
CHECK_DIFF(resMat, intMat10 <= intMat11);
CHECK_DIFF(resMat, intMat11 >= intMat10);
CHECK_DIFF(resMat, intMat11 != intMat10);
CHECK_DIFF(resMat, intMat10 == 10.0);
CHECK_DIFF(resMat, 10.0 == intMat10);
CHECK_DIFF(resMat, intMat10 < 11.0);
CHECK_DIFF(resMat, 11.0 > intMat10);
CHECK_DIFF(resMat, 10.0 < intMat11);
CHECK_DIFF(resMat, 11.0 >= intMat10);
CHECK_DIFF(resMat, 10.0 <= intMat11);
CHECK_DIFF(resMat, 10.0 != intMat11);
CHECK_DIFF(resMat, intMat11 != 10.0);
Mat eye = Mat::eye(3, 3, CV_16S);
Mat maskMat4(3, 3, CV_16S, Scalar(4));
Mat maskMat1(3, 3, CV_16S, Scalar(1));
Mat maskMat5(3, 3, CV_16S, Scalar(5));
Mat maskMat0(3, 3, CV_16S, Scalar(0));
CHECK_DIFF(maskMat0, maskMat4 & maskMat1);
CHECK_DIFF(maskMat0, Scalar(1) & maskMat4);
CHECK_DIFF(maskMat0, maskMat4 & Scalar(1));
Mat m;
m = maskMat4.clone(); m &= maskMat1; CHECK_DIFF(maskMat0, m);
m = maskMat4.clone(); m &= maskMat1 | maskMat1; CHECK_DIFF(maskMat0, m);
m = maskMat4.clone(); m &= (2* maskMat1 - maskMat1); CHECK_DIFF(maskMat0, m);
m = maskMat4.clone(); m &= Scalar(1); CHECK_DIFF(maskMat0, m);
m = maskMat4.clone(); m |= maskMat1; CHECK_DIFF(maskMat5, m);
m = maskMat5.clone(); m ^= maskMat1; CHECK_DIFF(maskMat4, m);
m = maskMat4.clone(); m |= (2* maskMat1 - maskMat1); CHECK_DIFF(maskMat5, m);
m = maskMat5.clone(); m ^= (2* maskMat1 - maskMat1); CHECK_DIFF(maskMat4, m);
m = maskMat4.clone(); m |= Scalar(1); CHECK_DIFF(maskMat5, m);
m = maskMat5.clone(); m ^= Scalar(1); CHECK_DIFF(maskMat4, m);
CHECK_DIFF(maskMat0, (maskMat4 | maskMat4) & (maskMat1 | maskMat1));
CHECK_DIFF(maskMat0, (maskMat4 | maskMat4) & maskMat1);
CHECK_DIFF(maskMat0, maskMat4 & (maskMat1 | maskMat1));
CHECK_DIFF(maskMat0, (maskMat1 | maskMat1) & Scalar(4));
CHECK_DIFF(maskMat0, Scalar(4) & (maskMat1 | maskMat1));
CHECK_DIFF(maskMat0, maskMat5 ^ (maskMat4 | maskMat1));
CHECK_DIFF(maskMat0, (maskMat4 | maskMat1) ^ maskMat5);
CHECK_DIFF(maskMat0, (maskMat4 + maskMat1) ^ (maskMat4 + maskMat1));
CHECK_DIFF(maskMat0, Scalar(5) ^ (maskMat4 | Scalar(1)));
CHECK_DIFF(maskMat1, Scalar(5) ^ maskMat4);
CHECK_DIFF(maskMat0, Scalar(5) ^ (maskMat4 + maskMat1));
CHECK_DIFF(maskMat5, Scalar(5) | (maskMat4 + maskMat1));
CHECK_DIFF(maskMat0, (maskMat4 + maskMat1) ^ Scalar(5));
CHECK_DIFF(maskMat5, maskMat5 | (maskMat4 ^ maskMat1));
CHECK_DIFF(maskMat5, (maskMat4 ^ maskMat1) | maskMat5);
CHECK_DIFF(maskMat5, maskMat5 | (maskMat4 ^ Scalar(1)));
CHECK_DIFF(maskMat5, (maskMat4 | maskMat4) | Scalar(1));
CHECK_DIFF(maskMat5, Scalar(1) | (maskMat4 | maskMat4));
CHECK_DIFF(maskMat5, Scalar(1) | maskMat4);
CHECK_DIFF(maskMat5, (maskMat5 | maskMat5) | (maskMat4 ^ maskMat1));
CHECK_DIFF(maskMat1, min(maskMat1, maskMat5));
CHECK_DIFF(maskMat1, min(Mat(maskMat1 | maskMat1), maskMat5 | maskMat5));
CHECK_DIFF(maskMat5, max(maskMat1, maskMat5));
CHECK_DIFF(maskMat5, max(Mat(maskMat1 | maskMat1), maskMat5 | maskMat5));
CHECK_DIFF(maskMat1, min(maskMat1, maskMat5 | maskMat5));
CHECK_DIFF(maskMat1, min(maskMat1 | maskMat1, maskMat5));
CHECK_DIFF(maskMat5, max(maskMat1 | maskMat1, maskMat5));
CHECK_DIFF(maskMat5, max(maskMat1, maskMat5 | maskMat5));
CHECK_DIFF(~maskMat1, maskMat1 ^ -1);
CHECK_DIFF(~(maskMat1 | maskMat1), maskMat1 ^ -1);
CHECK_DIFF(maskMat1, maskMat4/4.0);
/////////////////////////////
CHECK_DIFF(1.0 - (maskMat5 | maskMat5), -maskMat4);
CHECK_DIFF((maskMat4 | maskMat4) * 1.0 + 1.0, maskMat5);
CHECK_DIFF(1.0 + (maskMat4 | maskMat4) * 1.0, maskMat5);
CHECK_DIFF((maskMat5 | maskMat5) * 1.0 - 1.0, maskMat4);
CHECK_DIFF(5.0 - (maskMat4 | maskMat4) * 1.0, maskMat1);
CHECK_DIFF((maskMat4 | maskMat4) * 1.0 + 0.5 + 0.5, maskMat5);
CHECK_DIFF(0.5 + ((maskMat4 | maskMat4) * 1.0 + 0.5), maskMat5);
CHECK_DIFF(((maskMat4 | maskMat4) * 1.0 + 2.0) - 1.0, maskMat5);
CHECK_DIFF(5.0 - ((maskMat1 | maskMat1) * 1.0 + 3.0), maskMat1);
CHECK_DIFF( ( (maskMat1 | maskMat1) * 2.0 + 2.0) * 1.25, maskMat5);
CHECK_DIFF( 1.25 * ( (maskMat1 | maskMat1) * 2.0 + 2.0), maskMat5);
CHECK_DIFF( -( (maskMat1 | maskMat1) * (-2.0) + 1.0), maskMat1);
CHECK_DIFF( maskMat1 * 1.0 + maskMat4 * 0.5 + 2.0, maskMat5);
CHECK_DIFF( 1.0 + (maskMat1 * 1.0 + maskMat4 * 0.5 + 1.0), maskMat5);
CHECK_DIFF( (maskMat1 * 1.0 + maskMat4 * 0.5 + 2.0) - 1.0, maskMat4);
CHECK_DIFF(5.0 - (maskMat1 * 1.0 + maskMat4 * 0.5 + 1.0), maskMat1);
CHECK_DIFF((maskMat1 * 1.0 + maskMat4 * 0.5 + 1.0)*1.25, maskMat5);
CHECK_DIFF(1.25 * (maskMat1 * 1.0 + maskMat4 * 0.5 + 1.0), maskMat5);
CHECK_DIFF(-(maskMat1 * 2.0 + maskMat4 * (-1) + 1.0), maskMat1);
CHECK_DIFF((maskMat1 * 1.0 + maskMat4), maskMat5);
CHECK_DIFF((maskMat4 + maskMat1 * 1.0), maskMat5);
CHECK_DIFF((maskMat1 * 3.0 + 1.0) + maskMat1, maskMat5);
CHECK_DIFF(maskMat1 + (maskMat1 * 3.0 + 1.0), maskMat5);
CHECK_DIFF(maskMat1*4.0 + (maskMat1 | maskMat1), maskMat5);
CHECK_DIFF((maskMat1 | maskMat1) + maskMat1*4.0, maskMat5);
CHECK_DIFF((maskMat1*3.0 + 1.0) + (maskMat1 | maskMat1), maskMat5);
CHECK_DIFF((maskMat1 | maskMat1) + (maskMat1*3.0 + 1.0), maskMat5);
CHECK_DIFF(maskMat1*4.0 + maskMat4*2.0, maskMat1 * 12);
CHECK_DIFF((maskMat1*3.0 + 1.0) + maskMat4*2.0, maskMat1 * 12);
CHECK_DIFF(maskMat4*2.0 + (maskMat1*3.0 + 1.0), maskMat1 * 12);
CHECK_DIFF((maskMat1*3.0 + 1.0) + (maskMat1*2.0 + 2.0), maskMat1 * 8);
CHECK_DIFF(maskMat5*1.0 - maskMat4, maskMat1);
CHECK_DIFF(maskMat5 - maskMat1 * 4.0, maskMat1);
CHECK_DIFF((maskMat4 * 1.0 + 4.0)- maskMat4, maskMat4);
CHECK_DIFF(maskMat5 - (maskMat1 * 2.0 + 2.0), maskMat1);
CHECK_DIFF(maskMat5*1.0 - (maskMat4 | maskMat4), maskMat1);
CHECK_DIFF((maskMat5 | maskMat5) - maskMat1 * 4.0, maskMat1);
CHECK_DIFF((maskMat4 * 1.0 + 4.0)- (maskMat4 | maskMat4), maskMat4);
CHECK_DIFF((maskMat5 | maskMat5) - (maskMat1 * 2.0 + 2.0), maskMat1);
CHECK_DIFF(maskMat1*5.0 - maskMat4 * 1.0, maskMat1);
CHECK_DIFF((maskMat1*5.0 + 3.0)- maskMat4 * 1.0, maskMat4);
CHECK_DIFF(maskMat4 * 2.0 - (maskMat1*4.0 + 3.0), maskMat1);
CHECK_DIFF((maskMat1 * 2.0 + 3.0) - (maskMat1*3.0 + 1.0), maskMat1);
CHECK_DIFF((maskMat5 - maskMat4)* 4.0, maskMat4);
CHECK_DIFF(4.0 * (maskMat5 - maskMat4), maskMat4);
CHECK_DIFF(-((maskMat4 | maskMat4) - (maskMat5 | maskMat5)), maskMat1);
CHECK_DIFF(4.0 * (maskMat1 | maskMat1), maskMat4);
CHECK_DIFF((maskMat4 | maskMat4)/4.0, maskMat1);
#if !MSVC_OLD
CHECK_DIFF(2.0 * (maskMat1 * 2.0) , maskMat4);
#endif
CHECK_DIFF((maskMat4 / 2.0) / 2.0 , maskMat1);
CHECK_DIFF(-(maskMat4 - maskMat5) , maskMat1);
CHECK_DIFF(-((maskMat4 - maskMat5) * 1.0), maskMat1);
/////////////////////////////
CHECK_DIFF(maskMat4 / maskMat4, maskMat1);
///// Element-wise multiplication
CHECK_DIFF(maskMat4.mul(maskMat4, 0.25), maskMat4);
CHECK_DIFF(maskMat4.mul(maskMat1 * 4, 0.25), maskMat4);
CHECK_DIFF(maskMat4.mul(maskMat4 / 4), maskMat4);
CHECK_DIFF(maskMat4.mul(maskMat4 / 4), maskMat4);
CHECK_DIFF(maskMat4.mul(maskMat4) * 0.25, maskMat4);
CHECK_DIFF(0.25 * maskMat4.mul(maskMat4), maskMat4);
////// Element-wise division
CHECK_DIFF(maskMat4 / maskMat4, maskMat1);
CHECK_DIFF((maskMat4 & maskMat4) / (maskMat1 * 4), maskMat1);
CHECK_DIFF((maskMat4 & maskMat4) / maskMat4, maskMat1);
CHECK_DIFF(maskMat4 / (maskMat4 & maskMat4), maskMat1);
CHECK_DIFF((maskMat1 * 4) / maskMat4, maskMat1);
CHECK_DIFF(maskMat4 / (maskMat1 * 4), maskMat1);
CHECK_DIFF((maskMat4 * 0.5 )/ (maskMat1 * 2), maskMat1);
CHECK_DIFF(maskMat4 / maskMat4.mul(maskMat1), maskMat1);
CHECK_DIFF((maskMat4 & maskMat4) / maskMat4.mul(maskMat1), maskMat1);
CHECK_DIFF(4.0 / maskMat4, maskMat1);
CHECK_DIFF(4.0 / (maskMat4 | maskMat4), maskMat1);
CHECK_DIFF(4.0 / (maskMat1 * 4.0), maskMat1);
CHECK_DIFF(4.0 / (maskMat4 / maskMat1), maskMat1);
m = maskMat4.clone(); m/=4.0; CHECK_DIFF(m, maskMat1);
m = maskMat4.clone(); m/=maskMat4; CHECK_DIFF(m, maskMat1);
m = maskMat4.clone(); m/=(maskMat1 * 4.0); CHECK_DIFF(m, maskMat1);
m = maskMat4.clone(); m/=(maskMat4 / maskMat1); CHECK_DIFF(m, maskMat1);
/////////////////////////////
float matrix_data[] = { 3, 1, -4, -5, 1, 0, 0, 1.1f, 1.5f};
Mat mt(3, 3, CV_32F, matrix_data);
Mat mi = mt.inv();
Mat d1 = Mat::eye(3, 3, CV_32F);
Mat d2 = d1 * 2;
MatExpr mt_tr = mt.t();
MatExpr mi_tr = mi.t();
Mat mi2 = mi * 2;
CHECK_DIFF_FLT( mi2 * mt, d2 );
CHECK_DIFF_FLT( mi * mt, d1 );
CHECK_DIFF_FLT( mt_tr * mi_tr, d1 );
m = mi.clone(); m*=mt; CHECK_DIFF_FLT(m, d1);
m = mi.clone(); m*= (2 * mt - mt) ; CHECK_DIFF_FLT(m, d1);
m = maskMat4.clone(); m+=(maskMat1 * 1.0); CHECK_DIFF(m, maskMat5);
m = maskMat5.clone(); m-=(maskMat1 * 4.0); CHECK_DIFF(m, maskMat1);
m = maskMat1.clone(); m+=(maskMat1 * 3.0 + 1.0); CHECK_DIFF(m, maskMat5);
m = maskMat5.clone(); m-=(maskMat1 * 3.0 + 1.0); CHECK_DIFF(m, maskMat1);
#if !MSVC_OLD
m = mi.clone(); m+=(3.0 * mi * mt + d1); CHECK_DIFF_FLT(m, mi + d1 * 4);
m = mi.clone(); m-=(3.0 * mi * mt + d1); CHECK_DIFF_FLT(m, mi - d1 * 4);
m = mi.clone(); m*=(mt * 1.0); CHECK_DIFF_FLT(m, d1);
m = mi.clone(); m*=(mt * 1.0 + Mat::eye(m.size(), m.type())); CHECK_DIFF_FLT(m, d1 + mi);
m = mi.clone(); m*=mt_tr.t(); CHECK_DIFF_FLT(m, d1);
CHECK_DIFF_FLT( (mi * 2) * mt, d2);
CHECK_DIFF_FLT( mi * (2 * mt), d2);
CHECK_DIFF_FLT( mt.t() * mi_tr, d1 );
CHECK_DIFF_FLT( mt_tr * mi.t(), d1 );
CHECK_DIFF_FLT( (mi * 0.4) * (mt * 5), d2);
CHECK_DIFF_FLT( mt.t() * (mi_tr * 2), d2 );
CHECK_DIFF_FLT( (mt_tr * 2) * mi.t(), d2 );
CHECK_DIFF_FLT(mt.t() * mi.t(), d1);
CHECK_DIFF_FLT( (mi * mt) * 2.0, d2);
CHECK_DIFF_FLT( 2.0 * (mi * mt), d2);
CHECK_DIFF_FLT( -(mi * mt), -d1);
CHECK_DIFF_FLT( (mi * mt) / 2.0, d1 / 2);
Mat mt_mul_2_plus_1;
gemm(mt, d1, 2, Mat::ones(3, 3, CV_32F), 1, mt_mul_2_plus_1);
CHECK_DIFF( (mt * 2.0 + 1.0) * mi, mt_mul_2_plus_1 * mi); // (A*alpha + beta)*B
CHECK_DIFF( mi * (mt * 2.0 + 1.0), mi * mt_mul_2_plus_1); // A*(B*alpha + beta)
CHECK_DIFF( (mt * 2.0 + 1.0) * (mi * 2), mt_mul_2_plus_1 * mi2); // (A*alpha + beta)*(B*gamma)
CHECK_DIFF( (mi *2)* (mt * 2.0 + 1.0), mi2 * mt_mul_2_plus_1); // (A*gamma)*(B*alpha + beta)
CHECK_DIFF_FLT( (mt * 2.0 + 1.0) * mi.t(), mt_mul_2_plus_1 * mi_tr); // (A*alpha + beta)*B^t
CHECK_DIFF_FLT( mi.t() * (mt * 2.0 + 1.0), mi_tr * mt_mul_2_plus_1); // A^t*(B*alpha + beta)
CHECK_DIFF_FLT( (mi * mt + d2)*5, d1 * 3 * 5);
CHECK_DIFF_FLT( mi * mt + d2, d1 * 3);
CHECK_DIFF_FLT( -(mi * mt) + d2, d1);
CHECK_DIFF_FLT( (mi * mt) + d1, d2);
CHECK_DIFF_FLT( d1 + (mi * mt), d2);
CHECK_DIFF_FLT( (mi * mt) - d2, -d1);
CHECK_DIFF_FLT( d2 - (mi * mt), d1);
CHECK_DIFF_FLT( (mi * mt) + d2 * 0.5, d2);
CHECK_DIFF_FLT( d2 * 0.5 + (mi * mt), d2);
CHECK_DIFF_FLT( (mi * mt) - d1 * 2, -d1);
CHECK_DIFF_FLT( d1 * 2 - (mi * mt), d1);
CHECK_DIFF_FLT( (mi * mt) + mi.t(), mi_tr + d1);
CHECK_DIFF_FLT( mi.t() + (mi * mt), mi_tr + d1);
CHECK_DIFF_FLT( (mi * mt) - mi.t(), d1 - mi_tr);
CHECK_DIFF_FLT( mi.t() - (mi * mt), mi_tr - d1);
CHECK_DIFF_FLT( 2.0 *(mi * mt + d2), d1 * 6);
CHECK_DIFF_FLT( -(mi * mt + d2), d1 * -3);
CHECK_DIFF_FLT(mt.inv() * mt, d1);
CHECK_DIFF_FLT(mt.inv() * (2*mt - mt), d1);
#endif
}
catch (const test_excep& e)
{
ts->printf(cvtest::TS::LOG, "%s\n", e.s.c_str());
ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
return false;
}
return true;
}
bool CV_OperationsTest::SomeMatFunctions()
{
try
{
Mat rgba( 10, 10, CV_8UC4, Scalar(1,2,3,4) );
Mat bgr( rgba.rows, rgba.cols, CV_8UC3 );
Mat alpha( rgba.rows, rgba.cols, CV_8UC1 );
Mat out[] = { bgr, alpha };
// rgba[0] -> bgr[2], rgba[1] -> bgr[1],
// rgba[2] -> bgr[0], rgba[3] -> alpha[0]
int from_to[] = { 0,2, 1,1, 2,0, 3,3 };
mixChannels( &rgba, 1, out, 2, from_to, 4 );
Mat bgr_exp( rgba.size(), CV_8UC3, Scalar(3,2,1));
Mat alpha_exp( rgba.size(), CV_8UC1, Scalar(4));
CHECK_DIFF(bgr_exp, bgr);
CHECK_DIFF(alpha_exp, alpha);
}
catch (const test_excep& e)
{
ts->printf(cvtest::TS::LOG, "%s\n", e.s.c_str());
ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
return false;
}
return true;
}
bool CV_OperationsTest::TestSubMatAccess()
{
try
{
Mat_<float> T_bs(4,4);
Vec3f cdir(1.f, 1.f, 0.f);
Vec3f ydir(1.f, 0.f, 1.f);
Vec3f fpt(0.1f, 0.7f, 0.2f);
T_bs.setTo(0);
T_bs(Range(0,3),Range(2,3)) = 1.0*Mat(cdir); // weird OpenCV stuff, need to do multiply
T_bs(Range(0,3),Range(1,2)) = 1.0*Mat(ydir);
T_bs(Range(0,3),Range(0,1)) = 1.0*Mat(cdir.cross(ydir));
T_bs(Range(0,3),Range(3,4)) = 1.0*Mat(fpt);
T_bs(3,3) = 1.0;
//std::cout << "[Nav Grok] S frame =" << std::endl << T_bs << std::endl;
// set up display coords, really just the S frame
std::vector<float>coords;
for (int i=0; i<16; i++)
{
coords.push_back(T_bs(i));
//std::cout << T_bs1(i) << std::endl;
}
int sz=(int)T_bs.total();
CV_Assert( cvtest::norm(coords, T_bs.reshape(1,1,&sz), NORM_INF) == 0 );
}
catch (const test_excep& e)
{
ts->printf(cvtest::TS::LOG, "%s\n", e.s.c_str());
ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
return false;
}
return true;
}
bool CV_OperationsTest::TestTemplateMat()
{
try
{
Mat_<float> one_3x1(3, 1, 1.0f);
Mat_<float> shi_3x1(3, 1, 1.2f);
Mat_<float> shi_2x1(2, 1, -2);
Scalar shift = Scalar::all(15);
float data[] = { sqrt(2.f)/2, -sqrt(2.f)/2, 1.f, sqrt(2.f)/2, sqrt(2.f)/2, 10.f };
Mat_<float> rot_2x3(2, 3, data);
Mat_<float> res = Mat(Mat(2 * rot_2x3) * Mat(one_3x1 + shi_3x1 + shi_3x1 + shi_3x1) - shi_2x1) + shift;
Mat_<float> resS = rot_2x3 * one_3x1;
Mat_<float> tmp, res2, resS2;
cv::add(one_3x1, shi_3x1, tmp);
cv::add(tmp, shi_3x1, tmp);
cv::add(tmp, shi_3x1, tmp);
cv::gemm(rot_2x3, tmp, 2, shi_2x1, -1, res2, 0);
cv::add(res2, Mat(2, 1, CV_32F, shift), res2);
cv::gemm(rot_2x3, one_3x1, 1, shi_2x1, 0, resS2, 0);
CHECK_DIFF(res, res2);
CHECK_DIFF(resS, resS2);
Mat_<float> mat4x4(4, 4);
cv::randu(mat4x4, Scalar(0), Scalar(10));
Mat_<float> roi1 = mat4x4(Rect(Point(1, 1), Size(2, 2)));
Mat_<float> roi2 = mat4x4(Range(1, 3), Range(1, 3));
CHECK_DIFF(roi1, roi2);
CHECK_DIFF(mat4x4, mat4x4(Rect(Point(0,0), mat4x4.size())));
Mat_<int> intMat10(3, 3, 10);
Mat_<int> intMat11(3, 3, 11);
Mat_<uchar> resMat(3, 3, 255);
CHECK_DIFF(resMat, intMat10 == intMat10);
CHECK_DIFF(resMat, intMat10 < intMat11);
CHECK_DIFF(resMat, intMat11 > intMat10);
CHECK_DIFF(resMat, intMat10 <= intMat11);
CHECK_DIFF(resMat, intMat11 >= intMat10);
CHECK_DIFF(resMat, intMat10 == 10.0);
CHECK_DIFF(resMat, intMat10 < 11.0);
CHECK_DIFF(resMat, intMat11 > 10.0);
CHECK_DIFF(resMat, intMat10 <= 11.0);
CHECK_DIFF(resMat, intMat11 >= 10.0);
Mat_<uchar> maskMat4(3, 3, 4);
Mat_<uchar> maskMat1(3, 3, 1);
Mat_<uchar> maskMat5(3, 3, 5);
Mat_<uchar> maskMat0(3, 3, (uchar)0);
CHECK_DIFF(maskMat0, maskMat4 & maskMat1);
CHECK_DIFF(maskMat0, Scalar(1) & maskMat4);
CHECK_DIFF(maskMat0, maskMat4 & Scalar(1));
Mat_<uchar> m;
m = maskMat4.clone(); m&=maskMat1; CHECK_DIFF(maskMat0, m);
m = maskMat4.clone(); m&=Scalar(1); CHECK_DIFF(maskMat0, m);
m = maskMat4.clone(); m|=maskMat1; CHECK_DIFF(maskMat5, m);
m = maskMat4.clone(); m^=maskMat1; CHECK_DIFF(maskMat5, m);
CHECK_DIFF(maskMat0, (maskMat4 | maskMat4) & (maskMat1 | maskMat1));
CHECK_DIFF(maskMat0, (maskMat4 | maskMat4) & maskMat1);
CHECK_DIFF(maskMat0, maskMat4 & (maskMat1 | maskMat1));
CHECK_DIFF(maskMat0, maskMat5 ^ (maskMat4 | maskMat1));
CHECK_DIFF(maskMat0, Scalar(5) ^ (maskMat4 | Scalar(1)));
CHECK_DIFF(maskMat5, maskMat5 | (maskMat4 ^ maskMat1));
CHECK_DIFF(maskMat5, maskMat5 | (maskMat4 ^ Scalar(1)));
CHECK_DIFF(~maskMat1, maskMat1 ^ 0xFF);
CHECK_DIFF(~(maskMat1 | maskMat1), maskMat1 ^ 0xFF);
CHECK_DIFF(maskMat1 + maskMat4, maskMat5);
CHECK_DIFF(maskMat1 + Scalar(4), maskMat5);
CHECK_DIFF(Scalar(4) + maskMat1, maskMat5);
CHECK_DIFF(Scalar(4) + (maskMat1 & maskMat1), maskMat5);
CHECK_DIFF(maskMat1 + 4.0, maskMat5);
CHECK_DIFF((maskMat1 & 0xFF) + 4.0, maskMat5);
CHECK_DIFF(4.0 + maskMat1, maskMat5);
m = maskMat4.clone(); m+=Scalar(1); CHECK_DIFF(m, maskMat5);
m = maskMat4.clone(); m+=maskMat1; CHECK_DIFF(m, maskMat5);
m = maskMat4.clone(); m+=(maskMat1 | maskMat1); CHECK_DIFF(m, maskMat5);
CHECK_DIFF(maskMat5 - maskMat1, maskMat4);
CHECK_DIFF(maskMat5 - Scalar(1), maskMat4);
CHECK_DIFF((maskMat5 | maskMat5) - Scalar(1), maskMat4);
CHECK_DIFF(maskMat5 - 1, maskMat4);
CHECK_DIFF((maskMat5 | maskMat5) - 1, maskMat4);
CHECK_DIFF((maskMat5 | maskMat5) - (maskMat1 | maskMat1), maskMat4);
CHECK_DIFF(maskMat1, min(maskMat1, maskMat5));
CHECK_DIFF(maskMat5, max(maskMat1, maskMat5));
m = maskMat5.clone(); m-=Scalar(1); CHECK_DIFF(m, maskMat4);
m = maskMat5.clone(); m-=maskMat1; CHECK_DIFF(m, maskMat4);
m = maskMat5.clone(); m-=(maskMat1 | maskMat1); CHECK_DIFF(m, maskMat4);
m = maskMat4.clone(); m |= Scalar(1); CHECK_DIFF(maskMat5, m);
m = maskMat5.clone(); m ^= Scalar(1); CHECK_DIFF(maskMat4, m);
CHECK_DIFF(maskMat1, maskMat4/4.0);
Mat_<float> negf(3, 3, -3.0);
Mat_<float> posf = -negf;
Mat_<float> posf2 = posf * 2;
Mat_<int> negi(3, 3, -3);
CHECK_DIFF(abs(negf), -negf);
CHECK_DIFF(abs(posf - posf2), -negf);
CHECK_DIFF(abs(negi), -(negi & negi));
CHECK_DIFF(5.0 - maskMat4, maskMat1);
CHECK_DIFF(maskMat4.mul(maskMat4, 0.25), maskMat4);
CHECK_DIFF(maskMat4.mul(maskMat1 * 4, 0.25), maskMat4);
CHECK_DIFF(maskMat4.mul(maskMat4 / 4), maskMat4);
////// Element-wise division
CHECK_DIFF(maskMat4 / maskMat4, maskMat1);
CHECK_DIFF(4.0 / maskMat4, maskMat1);
m = maskMat4.clone(); m/=4.0; CHECK_DIFF(m, maskMat1);
////////////////////////////////
typedef Mat_<int> TestMat_t;
const TestMat_t cnegi = negi.clone();
TestMat_t::iterator beg = negi.begin();
TestMat_t::iterator end = negi.end();
TestMat_t::const_iterator cbeg = cnegi.begin();
TestMat_t::const_iterator cend = cnegi.end();
int sum = 0;
for(; beg!=end; ++beg)
sum+=*beg;
for(; cbeg!=cend; ++cbeg)
sum-=*cbeg;
if (sum != 0) throw test_excep();
CHECK_DIFF(negi.col(1), negi.col(2));
CHECK_DIFF(negi.row(1), negi.row(2));
CHECK_DIFF(negi.col(1), negi.diag());
if (Mat_<Point2f>(1, 1).elemSize1() != sizeof(float)) throw test_excep();
if (Mat_<Point2f>(1, 1).elemSize() != 2 * sizeof(float)) throw test_excep();
if (Mat_<Point2f>(1, 1).depth() != CV_32F) throw test_excep();
if (Mat_<float>(1, 1).depth() != CV_32F) throw test_excep();
if (Mat_<int>(1, 1).depth() != CV_32S) throw test_excep();
if (Mat_<double>(1, 1).depth() != CV_64F) throw test_excep();
if (Mat_<Point3d>(1, 1).depth() != CV_64F) throw test_excep();
if (Mat_<signed char>(1, 1).depth() != CV_8S) throw test_excep();
if (Mat_<unsigned short>(1, 1).depth() != CV_16U) throw test_excep();
if (Mat_<unsigned short>(1, 1).channels() != 1) throw test_excep();
if (Mat_<Point2f>(1, 1).channels() != 2) throw test_excep();
if (Mat_<Point3f>(1, 1).channels() != 3) throw test_excep();
if (Mat_<Point3d>(1, 1).channels() != 3) throw test_excep();
Mat_<uchar> eye = Mat_<uchar>::zeros(2, 2); CHECK_DIFF(Mat_<uchar>::zeros(Size(2, 2)), eye);
eye.at<uchar>(Point(0,0)) = 1; eye.at<uchar>(1, 1) = 1;
CHECK_DIFF(Mat_<uchar>::eye(2, 2), eye);
CHECK_DIFF(eye, Mat_<uchar>::eye(Size(2,2)));
Mat_<uchar> ones(2, 2, (uchar)1);
CHECK_DIFF(ones, Mat_<uchar>::ones(Size(2,2)));
CHECK_DIFF(Mat_<uchar>::ones(2, 2), ones);
Mat_<Point2f> pntMat(2, 2, Point2f(1, 0));
if(pntMat.stepT() != 2) throw test_excep();
uchar uchar_data[] = {1, 0, 0, 1};
Mat_<uchar> matFromData(1, 4, uchar_data);
const Mat_<uchar> mat2 = matFromData.clone();
CHECK_DIFF(matFromData, eye.reshape(1, 1));
if (matFromData(Point(0,0)) != uchar_data[0])throw test_excep();
if (mat2(Point(0,0)) != uchar_data[0]) throw test_excep();
if (matFromData(0,0) != uchar_data[0])throw test_excep();
if (mat2(0,0) != uchar_data[0]) throw test_excep();
Mat_<uchar> rect(eye, Rect(0, 0, 1, 1));
if (rect.cols != 1 || rect.rows != 1 || rect(0,0) != uchar_data[0]) throw test_excep();
//cv::Mat_<_Tp>::adjustROI(int,int,int,int)
//cv::Mat_<_Tp>::cross(const Mat_&) const
//cv::Mat_<_Tp>::Mat_(const vector<_Tp>&,bool)
//cv::Mat_<_Tp>::Mat_(int,int,_Tp*,size_t)
//cv::Mat_<_Tp>::Mat_(int,int,const _Tp&)
//cv::Mat_<_Tp>::Mat_(Size,const _Tp&)
//cv::Mat_<_Tp>::mul(const Mat_<_Tp>&,double) const
//cv::Mat_<_Tp>::mul(const MatExpr_<MatExpr_Op2_<Mat_<_Tp>,double,Mat_<_Tp>,MatOp_DivRS_<Mat> >,Mat_<_Tp> >&,double) const
//cv::Mat_<_Tp>::mul(const MatExpr_<MatExpr_Op2_<Mat_<_Tp>,double,Mat_<_Tp>,MatOp_Scale_<Mat> >,Mat_<_Tp> >&,double) const
//cv::Mat_<_Tp>::operator Mat_<T2>() const
//cv::Mat_<_Tp>::operator MatExpr_<Mat_<_Tp>,Mat_<_Tp> >() const
//cv::Mat_<_Tp>::operator()(const Range&,const Range&) const
//cv::Mat_<_Tp>::operator()(const Rect&) const
//cv::Mat_<_Tp>::operator=(const MatExpr_Base&)
//cv::Mat_<_Tp>::operator[](int) const
///////////////////////////////
float matrix_data[] = { 3, 1, -4, -5, 1, 0, 0, 1.1f, 1.5f};
Mat_<float> mt(3, 3, matrix_data);
Mat_<float> mi = mt.inv();
Mat_<float> d1 = Mat_<float>::eye(3, 3);
Mat_<float> d2 = d1 * 2;
Mat_<float> mt_tr = mt.t();
Mat_<float> mi_tr = mi.t();
Mat_<float> mi2 = mi * 2;
CHECK_DIFF_FLT( mi2 * mt, d2 );
CHECK_DIFF_FLT( mi * mt, d1 );
CHECK_DIFF_FLT( mt_tr * mi_tr, d1 );
Mat_<float> mf;
mf = mi.clone(); mf*=mt; CHECK_DIFF_FLT(mf, d1);
////// typedefs //////
if (Mat1b(1, 1).elemSize() != sizeof(uchar)) throw test_excep();
if (Mat2b(1, 1).elemSize() != 2 * sizeof(uchar)) throw test_excep();
if (Mat3b(1, 1).elemSize() != 3 * sizeof(uchar)) throw test_excep();
if (Mat1f(1, 1).elemSize() != sizeof(float)) throw test_excep();
if (Mat2f(1, 1).elemSize() != 2 * sizeof(float)) throw test_excep();
if (Mat3f(1, 1).elemSize() != 3 * sizeof(float)) throw test_excep();
if (Mat1f(1, 1).depth() != CV_32F) throw test_excep();
if (Mat3f(1, 1).depth() != CV_32F) throw test_excep();
if (Mat3f(1, 1).type() != CV_32FC3) throw test_excep();
if (Mat1i(1, 1).depth() != CV_32S) throw test_excep();
if (Mat1d(1, 1).depth() != CV_64F) throw test_excep();
if (Mat1b(1, 1).depth() != CV_8U) throw test_excep();
if (Mat3b(1, 1).type() != CV_8UC3) throw test_excep();
if (Mat1w(1, 1).depth() != CV_16U) throw test_excep();
if (Mat1s(1, 1).depth() != CV_16S) throw test_excep();
if (Mat1f(1, 1).channels() != 1) throw test_excep();
if (Mat1b(1, 1).channels() != 1) throw test_excep();
if (Mat1i(1, 1).channels() != 1) throw test_excep();
if (Mat1w(1, 1).channels() != 1) throw test_excep();
if (Mat1s(1, 1).channels() != 1) throw test_excep();
if (Mat2f(1, 1).channels() != 2) throw test_excep();
if (Mat2b(1, 1).channels() != 2) throw test_excep();
if (Mat2i(1, 1).channels() != 2) throw test_excep();
if (Mat2w(1, 1).channels() != 2) throw test_excep();
if (Mat2s(1, 1).channels() != 2) throw test_excep();
if (Mat3f(1, 1).channels() != 3) throw test_excep();
if (Mat3b(1, 1).channels() != 3) throw test_excep();
if (Mat3i(1, 1).channels() != 3) throw test_excep();
if (Mat3w(1, 1).channels() != 3) throw test_excep();
if (Mat3s(1, 1).channels() != 3) throw test_excep();
vector<Mat_<float> > mvf, mvf2;
Mat_<Vec2f> mf2;
mvf.push_back(Mat_<float>::ones(4, 3));
mvf.push_back(Mat_<float>::zeros(4, 3));
merge(mvf, mf2);
split(mf2, mvf2);
CV_Assert( cvtest::norm(mvf2[0], mvf[0], NORM_INF) == 0 &&
cvtest::norm(mvf2[1], mvf[1], NORM_INF) == 0 );
{
Mat a(2,2,CV_32F,1.f);
Mat b(1,2,CV_32F,1.f);
Mat c = (a*b.t()).t();
CV_Assert( cvtest::norm(c, NORM_L1) == 4. );
}
bool badarg_catched = false;
try
{
Mat m1 = Mat::zeros(1, 10, CV_8UC1);
Mat m2 = Mat::zeros(10, 10, CV_8UC3);
m1.copyTo(m2.row(1));
}
catch(const Exception&)
{
badarg_catched = true;
}
CV_Assert( badarg_catched );
Size size(2, 5);
TestType<float>(size, 1.f);
cv::Vec3f val1(1.f);
TestType<cv::Vec3f>(size, val1);
cv::Matx31f val2(1.f);
TestType<cv::Matx31f>(size, val2);
cv::Matx41f val3(1.f);
TestType<cv::Matx41f>(size, val3);
cv::Matx32f val4(1.f);
TestType<cv::Matx32f>(size, val4);
}
catch (const test_excep& e)
{
ts->printf(cvtest::TS::LOG, "%s\n", e.s.c_str());
ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
return false;
}
return true;
}
bool CV_OperationsTest::TestMatND()
{
int sizes[] = { 3, 3, 3};
cv::MatND nd(3, sizes, CV_32F);
return true;
}
bool CV_OperationsTest::TestSparseMat()
{
try
{
int sizes[] = { 10, 10, 10};
int dims = sizeof(sizes)/sizeof(sizes[0]);
SparseMat mat(dims, sizes, CV_32FC2);
if (mat.dims() != dims) throw test_excep();
if (mat.channels() != 2) throw test_excep();
if (mat.depth() != CV_32F) throw test_excep();
SparseMat mat2 = mat.clone();
}
catch (const test_excep&)
{
ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
return false;
}
return true;
}
bool CV_OperationsTest::TestMatxMultiplication()
{
try
{
Matx33f mat(1, 1, 1, 0, 1, 1, 0, 0, 1); // Identity matrix
Point2f pt(3, 4);
Point3f res = mat * pt; // Correctly assumes homogeneous coordinates
Vec3f res2 = mat*Vec3f(res.x, res.y, res.z);
if(res.x != 8.0) throw test_excep();
if(res.y != 5.0) throw test_excep();
if(res.z != 1.0) throw test_excep();
if(res2[0] != 14.0) throw test_excep();
if(res2[1] != 6.0) throw test_excep();
if(res2[2] != 1.0) throw test_excep();
Matx44f mat44f(1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1);
Matx44d mat44d(1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1);
Scalar s(4, 3, 2, 1);
Scalar sf = mat44f*s;
Scalar sd = mat44d*s;
if(sf[0] != 10.0) throw test_excep();
if(sf[1] != 6.0) throw test_excep();
if(sf[2] != 3.0) throw test_excep();
if(sf[3] != 1.0) throw test_excep();
if(sd[0] != 10.0) throw test_excep();
if(sd[1] != 6.0) throw test_excep();
if(sd[2] != 3.0) throw test_excep();
if(sd[3] != 1.0) throw test_excep();
}
catch(const test_excep&)
{
ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);
return false;
}
return true;
}
bool CV_OperationsTest::TestMatMatxCastSum()
{
try
{
Mat ref1 = (Mat_<double>(3, 1) << 1, 2, 3);
Mat ref2 = (Mat_<double>(3, 1) << 3, 4, 5);
Mat ref3 = Mat::ones(3, 1, CV_64FC1);
Mat mat = Mat::zeros(3, 1, CV_64FC1);
Mat tst1 = ref1.clone();
Mat_<double> tst2 = ref2.clone();
Matx<double, 3, 1> tst3(1, 2, 3);
Vec3d tst4(3, 4, 5);
Scalar tst5(1, 2, 3);
Mat res;
res = mat + tst1;
CHECK_DIFF_FLT(res, ref1);
res = mat + tst2;
CHECK_DIFF_FLT(res, ref2);
res = mat + tst3;
CHECK_DIFF_FLT(res, ref1);
res = mat + tst4;
CHECK_DIFF_FLT(res, ref2);
res = mat + tst5;
CHECK_DIFF_FLT(res, ref3);
res = mat + 1;
CHECK_DIFF_FLT(res, ref3);
cv::add(mat, tst1, res);
CHECK_DIFF_FLT(res, ref1);
cv::add(mat, tst2, res);
CHECK_DIFF_FLT(res, ref2);
cv::add(mat, tst3, res);
CHECK_DIFF_FLT(res, ref1);
cv::add(mat, tst4, res);
CHECK_DIFF_FLT(res, ref2);
cv::add(mat, tst5, res);
CHECK_DIFF_FLT(res, ref3);
cv::add(mat, 1, res);
CHECK_DIFF_FLT(res, ref3);
res = mat.clone(); res += tst1;
CHECK_DIFF_FLT(res, ref1);
res = mat.clone(); res += tst2;
CHECK_DIFF_FLT(res, ref2);
res = mat.clone(); res += tst3;
CHECK_DIFF_FLT(res, ref1);
res = mat.clone(); res += tst4;
CHECK_DIFF_FLT(res, ref2);
res = mat.clone(); res += tst5;
CHECK_DIFF_FLT(res, ref3);
res = mat.clone(); res += 1;
CHECK_DIFF_FLT(res, ref3);
}
catch (const test_excep& e)
{
ts->printf(cvtest::TS::LOG, "%s\n", e.s.c_str());
ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
return false;
}
return true;
}
bool CV_OperationsTest::TestMatxElementwiseDivision()
{
try
{
Matx22f mat(2, 4, 6, 8);
Matx22f mat2(2, 2, 2, 2);
Matx22f res = mat.div(mat2);
if(res(0, 0) != 1.0) throw test_excep();
if(res(0, 1) != 2.0) throw test_excep();
if(res(1, 0) != 3.0) throw test_excep();
if(res(1, 1) != 4.0) throw test_excep();
}
catch(const test_excep&)
{
ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);
return false;
}
return true;
}
bool CV_OperationsTest::TestDivisionByValue()
{
try
{
Matx22f mat(2, 4, 6, 8);
float alpha = 2.f;
Matx22f res = mat / alpha;
if(res(0, 0) != 1.0) throw test_excep();
if(res(0, 1) != 2.0) throw test_excep();
if(res(1, 0) != 3.0) throw test_excep();
if(res(1, 1) != 4.0) throw test_excep();
}
catch(const test_excep&)
{
ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);
return false;
}
return true;
}
bool CV_OperationsTest::TestInplaceDivisionByValue()
{
try
{
Matx22f mat(2, 4, 6, 8);
float alpha = 2.f;
mat /= alpha;
if(mat(0, 0) != 1.0) throw test_excep();
if(mat(0, 1) != 2.0) throw test_excep();
if(mat(1, 0) != 3.0) throw test_excep();
if(mat(1, 1) != 4.0) throw test_excep();
}
catch(const test_excep&)
{
ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);
return false;
}
return true;
}
bool CV_OperationsTest::TestVec()
{
try
{
cv::Mat hsvImage_f(5, 5, CV_32FC3), hsvImage_b(5, 5, CV_8UC3);
int i = 0,j = 0;
cv::Vec3f a;
//these compile
cv::Vec3b b = a;
hsvImage_f.at<cv::Vec3f>(i,j) = cv::Vec3f((float)i,0,1);
hsvImage_b.at<cv::Vec3b>(i,j) = cv::Vec3b(cv::Vec3f((float)i,0,1));
//these don't
b = cv::Vec3f(1,0,0);
cv::Vec3b c;
c = cv::Vec3f(0,0,1);
hsvImage_b.at<cv::Vec3b>(i,j) = cv::Vec3f((float)i,0,1);
hsvImage_b.at<cv::Vec3b>(i,j) = a;
hsvImage_b.at<cv::Vec3b>(i,j) = cv::Vec3f(1,2,3);
}
catch(const test_excep&)
{
ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);
return false;
}
return true;
}
bool CV_OperationsTest::operations1()
{
try
{
Point3d p1(1, 1, 1), p2(2, 2, 2), p4(4, 4, 4);
p1*=2;
if (!(p1 == p2)) throw test_excep();
if (!(p2 * 2 == p4)) throw test_excep();
if (!(p2 * 2.f == p4)) throw test_excep();
if (!(p2 * 2.f == p4)) throw test_excep();
Point2d pi1(1, 1), pi2(2, 2), pi4(4, 4);
pi1*=2;
if (!(pi1 == pi2)) throw test_excep();
if (!(pi2 * 2 == pi4)) throw test_excep();
if (!(pi2 * 2.f == pi4)) throw test_excep();
if (!(pi2 * 2.f == pi4)) throw test_excep();
Vec2d v12(1, 1), v22(2, 2);
v12*=2.0;
if (!(v12 == v22)) throw test_excep();
Vec3d v13(1, 1, 1), v23(2, 2, 2);
v13*=2.0;
if (!(v13 == v23)) throw test_excep();
Vec4d v14(1, 1, 1, 1), v24(2, 2, 2, 2);
v14*=2.0;
if (!(v14 == v24)) throw test_excep();
Size sz(10, 20);
if (sz.area() != 200) throw test_excep();
if (sz.width != 10 || sz.height != 20) throw test_excep();
Rect r1(0, 0, 10, 20);
Size sz1(5, 10);
r1 -= sz1;
if (r1.size().width != 5 || r1.size().height != 10) throw test_excep();
Rect r2 = r1 - sz1;
if (r2.size().width != 0 || r2.size().height != 0) throw test_excep();
Vec<double, 5> v5d(1, 1, 1, 1, 1);
Vec<double, 6> v6d(1, 1, 1, 1, 1, 1);
Vec<double, 7> v7d(1, 1, 1, 1, 1, 1, 1);
Vec<double, 8> v8d(1, 1, 1, 1, 1, 1, 1, 1);
Vec<double, 9> v9d(1, 1, 1, 1, 1, 1, 1, 1, 1);
Vec<double,10> v10d(1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
Vec<double,10> v10dzero;
for (int ii = 0; ii < 10; ++ii) {
if (v10dzero[ii] != 0.0)
throw test_excep();
}
Mat A(1, 32, CV_32F), B;
for( int i = 0; i < A.cols; i++ )
A.at<float>(i) = (float)(i <= 12 ? i : 24 - i);
cv::transpose(A, B);
int minidx[2] = {0, 0}, maxidx[2] = {0, 0};
double minval = 0, maxval = 0;
cv::minMaxIdx(A, &minval, &maxval, minidx, maxidx);
if( !(minidx[0] == 0 && minidx[1] == 31 && maxidx[0] == 0 && maxidx[1] == 12 &&
minval == -7 && maxval == 12))
throw test_excep();
cv::minMaxIdx(B, &minval, &maxval, minidx, maxidx);
if( !(minidx[0] == 31 && minidx[1] == 0 && maxidx[0] == 12 && maxidx[1] == 0 &&
minval == -7 && maxval == 12))
throw test_excep();
Matx33f b(1.f, 2.f, 3.f, 4.f, 5.f, 6.f, 7.f, 8.f, 9.f);
Mat c;
cv::add(Mat::zeros(3, 3, CV_32F), b, c);
CV_Assert( cvtest::norm(b, c, NORM_INF) == 0 );
cv::add(Mat::zeros(3, 3, CV_64F), b, c, noArray(), c.type());
CV_Assert( cvtest::norm(b, c, NORM_INF) == 0 );
cv::add(Mat::zeros(6, 1, CV_64F), 1, c, noArray(), c.type());
CV_Assert( cvtest::norm(Matx61f(1.f, 1.f, 1.f, 1.f, 1.f, 1.f), c, NORM_INF) == 0 );
vector<Point2f> pt2d(3);
vector<Point3d> pt3d(2);
CV_Assert( Mat(pt2d).checkVector(2) == 3 && Mat(pt2d).checkVector(3) < 0 &&
Mat(pt3d).checkVector(2) < 0 && Mat(pt3d).checkVector(3) == 2 );
Matx44f m44(0.8147f, 0.6324f, 0.9575f, 0.9572f,
0.9058f, 0.0975f, 0.9649f, 0.4854f,
0.1270f, 0.2785f, 0.1576f, 0.8003f,
0.9134f, 0.5469f, 0.9706f, 0.1419f);
double d = cv::determinant(m44);
CV_Assert( fabs(d - (-0.0262)) <= 0.001 );
Cv32suf z;
z.i = 0x80000000;
CV_Assert( cvFloor(z.f) == 0 && cvCeil(z.f) == 0 && cvRound(z.f) == 0 );
}
catch(const test_excep&)
{
ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
return false;
}
return true;
}
bool CV_OperationsTest::TestExp()
{
Mat1f tt = Mat1f::ones(4,2);
Mat1f outs;
exp(-tt, outs);
Mat1f tt2 = Mat1f::ones(4,1), outs2;
exp(-tt2, outs2);
return true;
}
bool CV_OperationsTest::TestSVD()
{
try
{
Mat A = (Mat_<double>(3,4) << 1, 2, -1, 4, 2, 4, 3, 5, -1, -2, 6, 7);
Mat x;
SVD::solveZ(A,x);
if( cvtest::norm(A*x, NORM_INF) > FLT_EPSILON )
throw test_excep();
SVD svd(A, SVD::FULL_UV);
if( cvtest::norm(A*svd.vt.row(3).t(), NORM_INF) > FLT_EPSILON )
throw test_excep();
Mat Dp(3,3,CV_32FC1);
Mat Dc(3,3,CV_32FC1);
Mat Q(3,3,CV_32FC1);
Mat U,Vt,R,T,W;
Dp.at<float>(0,0)=0.86483884f; Dp.at<float>(0,1)= -0.3077251f; Dp.at<float>(0,2)=-0.55711365f;
Dp.at<float>(1,0)=0.49294353f; Dp.at<float>(1,1)=-0.24209651f; Dp.at<float>(1,2)=-0.25084701f;
Dp.at<float>(2,0)=0; Dp.at<float>(2,1)=0; Dp.at<float>(2,2)=0;
Dc.at<float>(0,0)=0.75632739f; Dc.at<float>(0,1)= -0.38859656f; Dc.at<float>(0,2)=-0.36773083f;
Dc.at<float>(1,0)=0.9699229f; Dc.at<float>(1,1)=-0.49858192f; Dc.at<float>(1,2)=-0.47134098f;
Dc.at<float>(2,0)=0.10566688f; Dc.at<float>(2,1)=-0.060333252f; Dc.at<float>(2,2)=-0.045333147f;
Q=Dp*Dc.t();
SVD decomp;
decomp=SVD(Q);
U=decomp.u;
Vt=decomp.vt;
W=decomp.w;
Mat I = Mat::eye(3, 3, CV_32F);
if( cvtest::norm(U*U.t(), I, NORM_INF) > FLT_EPSILON ||
cvtest::norm(Vt*Vt.t(), I, NORM_INF) > FLT_EPSILON ||
W.at<float>(2) < 0 || W.at<float>(1) < W.at<float>(2) ||
W.at<float>(0) < W.at<float>(1) ||
cvtest::norm(U*Mat::diag(W)*Vt, Q, NORM_INF) > FLT_EPSILON*2 )
throw test_excep();
}
catch(const test_excep&)
{
ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
return false;
}
return true;
}
void CV_OperationsTest::run( int /* start_from */)
{
if (!TestMat())
return;
if (!SomeMatFunctions())
return;
if (!TestTemplateMat())
return;
if (!TestMatND())
return;
if (!TestSparseMat())
return;
if (!TestVec())
return;
if (!TestMatxMultiplication())
return;
if (!TestMatxElementwiseDivision())
return;
if (!TestDivisionByValue())
return;
if (!TestInplaceDivisionByValue())
return;
if (!TestMatMatxCastSum())
return;
if (!TestSubMatAccess())
return;
if (!TestExp())
return;
if (!TestSVD())
return;
if (!operations1())
return;
ts->set_failed_test_info(cvtest::TS::OK);
}
TEST(Core_Array, expressions) { CV_OperationsTest test; test.safe_run(); }
class CV_SparseMatTest : public cvtest::BaseTest
{
public:
CV_SparseMatTest() {}
~CV_SparseMatTest() {}
protected:
void run(int)
{
try
{
RNG& rng = theRNG();
const int MAX_DIM=3;
int sizes[MAX_DIM], idx[MAX_DIM];
for( int iter = 0; iter < 100; iter++ )
{
ts->printf(cvtest::TS::LOG, ".");
ts->update_context(this, iter, true);
int k, dims = rng.uniform(1, MAX_DIM+1), p = 1;
for( k = 0; k < dims; k++ )
{
sizes[k] = rng.uniform(1, 30);
p *= sizes[k];
}
int j, nz = rng.uniform(0, (p+2)/2), nz0 = 0;
SparseMat_<int> v(dims,sizes);
CV_Assert( (int)v.nzcount() == 0 );
SparseMatIterator_<int> it = v.begin();
SparseMatIterator_<int> it_end = v.end();
for( k = 0; it != it_end; ++it, ++k )
;
CV_Assert( k == 0 );
int sum0 = 0, sum = 0;
for( j = 0; j < nz; j++ )
{
int val = rng.uniform(1, 100);
for( k = 0; k < dims; k++ )
idx[k] = rng.uniform(0, sizes[k]);
if( dims == 1 )
{
CV_Assert( v.ref(idx[0]) == v(idx[0]) );
}
else if( dims == 2 )
{
CV_Assert( v.ref(idx[0], idx[1]) == v(idx[0], idx[1]) );
}
else if( dims == 3 )
{
CV_Assert( v.ref(idx[0], idx[1], idx[2]) == v(idx[0], idx[1], idx[2]) );
}
CV_Assert( v.ref(idx) == v(idx) );
v.ref(idx) += val;
if( v(idx) == val )
nz0++;
sum0 += val;
}
CV_Assert( (int)v.nzcount() == nz0 );
it = v.begin();
it_end = v.end();
for( k = 0; it != it_end; ++it, ++k )
sum += *it;
CV_Assert( k == nz0 && sum == sum0 );
v.clear();
CV_Assert( (int)v.nzcount() == 0 );
it = v.begin();
it_end = v.end();
for( k = 0; it != it_end; ++it, ++k )
;
CV_Assert( k == 0 );
}
}
catch(...)
{
ts->set_failed_test_info(cvtest::TS::FAIL_MISMATCH);
}
}
};
TEST(Core_SparseMat, iterations) { CV_SparseMatTest test; test.safe_run(); }
TEST(MatTestRoi, adjustRoiOverflow)
{
Mat m(15, 10, CV_32S);
Mat roi(m, cv::Range(2, 10), cv::Range(3,6));
int rowsInROI = roi.rows;
roi.adjustROI(1, 0, 0, 0);
ASSERT_EQ(roi.rows, rowsInROI + 1);
roi.adjustROI(-m.rows, -m.rows, 0, 0);
ASSERT_EQ(roi.rows, m.rows);
}
TEST(MatTestRoi, adjustRoiUndefinedBehavior)
{
Mat m(6, 6, CV_8U);
Mat roi(m, cv::Range(2, 4), cv::Range(2, 4));
// This could trigger a (negative int)*size_t when updating data,
// which is undefined behavior.
roi.adjustROI(2, 2, 2, 2);
EXPECT_EQ(m.data, roi.data);
}
CV_ENUM(SortRowCol, SORT_EVERY_COLUMN, SORT_EVERY_ROW)
CV_ENUM(SortOrder, SORT_ASCENDING, SORT_DESCENDING)
PARAM_TEST_CASE(sortIdx, MatDepth, SortRowCol, SortOrder, Size, bool)
{
int type;
Size size;
int flags;
bool use_roi;
Mat src, src_roi;
Mat dst, dst_roi;
virtual void SetUp()
{
int depth = GET_PARAM(0);
int rowFlags = GET_PARAM(1);
int orderFlags = GET_PARAM(2);
size = GET_PARAM(3);
use_roi = GET_PARAM(4);
type = CV_MAKE_TYPE(depth, 1);
flags = rowFlags | orderFlags;
}
void generateTestData()
{
Border srcBorder = randomBorder(0, use_roi ? MAX_VALUE : 0);
randomSubMat(src, src_roi, size, srcBorder, type, -100, 100);
Border dstBorder = randomBorder(0, use_roi ? MAX_VALUE : 0);
randomSubMat(dst, dst_roi, size, dstBorder, CV_32S, 5, 16);
}
template<typename T>
void check_(const cv::Mat& values_, const cv::Mat_<int>& idx_)
{
cv::Mat_<T>& values = (cv::Mat_<T>&)values_;
cv::Mat_<int>& idx = (cv::Mat_<int>&)idx_;
size_t N = values.total();
std::vector<bool> processed(N, false);
int prevIdx = idx(0);
T prevValue = values(prevIdx);
processed[prevIdx] = true;
for (size_t i = 1; i < N; i++)
{
int nextIdx = idx((int)i);
T value = values(nextIdx);
ASSERT_EQ(false, processed[nextIdx]) << "Indexes must be unique. i=" << i << " idx=" << nextIdx << std::endl << idx;
processed[nextIdx] = true;
if ((flags & SORT_DESCENDING) == SORT_DESCENDING)
ASSERT_GE(prevValue, value) << "i=" << i << " prevIdx=" << prevIdx << " idx=" << nextIdx;
else
ASSERT_LE(prevValue, value) << "i=" << i << " prevIdx=" << prevIdx << " idx=" << nextIdx;
prevValue = value;
prevIdx = nextIdx;
}
}
void validate()
{
ASSERT_EQ(CV_32SC1, dst_roi.type());
ASSERT_EQ(size, dst_roi.size());
bool isColumn = (flags & SORT_EVERY_COLUMN) == SORT_EVERY_COLUMN;
size_t N = isColumn ? src_roi.cols : src_roi.rows;
Mat values_row((int)N, 1, type), idx_row((int)N, 1, CV_32S);
for (size_t i = 0; i < N; i++)
{
SCOPED_TRACE(cv::format("row/col=%d", (int)i));
if (isColumn)
{
src_roi.col((int)i).copyTo(values_row);
dst_roi.col((int)i).copyTo(idx_row);
}
else
{
src_roi.row((int)i).copyTo(values_row);
dst_roi.row((int)i).copyTo(idx_row);
}
switch(type)
{
case CV_8U: check_<uchar>(values_row, idx_row); break;
case CV_8S: check_<char>(values_row, idx_row); break;
case CV_16S: check_<short>(values_row, idx_row); break;
case CV_32S: check_<int>(values_row, idx_row); break;
case CV_32F: check_<float>(values_row, idx_row); break;
case CV_64F: check_<double>(values_row, idx_row); break;
default: ASSERT_FALSE(true) << "Unsupported type: " << type;
}
}
}
};
TEST_P(sortIdx, simple)
{
for (int j = 0; j < 5; j++)
{
generateTestData();
cv::sortIdx(src_roi, dst_roi, flags);
validate();
}
}
INSTANTIATE_TEST_CASE_P(Core, sortIdx, Combine(
Values(CV_8U, CV_8S, CV_16S, CV_32S, CV_32F, CV_64F), // depth
Values(SORT_EVERY_COLUMN, SORT_EVERY_ROW),
Values(SORT_ASCENDING, SORT_DESCENDING),
Values(Size(3, 3), Size(16, 8)),
::testing::Bool()
));
TEST(Core_sortIdx, regression_8941)
{
cv::Mat src = (cv::Mat_<int>(3, 3) <<
1, 2, 3,
0, 9, 5,
8, 1, 6
);
cv::Mat expected = (cv::Mat_<int>(3, 1) <<
1,
0,
2
);
cv::Mat result;
cv::sortIdx(src.col(0), result, cv::SORT_EVERY_COLUMN | cv::SORT_ASCENDING);
#if 0
std::cout << src.col(0) << std::endl;
std::cout << result << std::endl;
#endif
ASSERT_EQ(expected.size(), result.size());
EXPECT_EQ(0, cvtest::norm(expected, result, NORM_INF)) <<
"result=" << std::endl << result << std::endl <<
"expected=" << std::endl << expected;
}
TEST(Core_Mat, augmentation_operations_9688)
{
{
Mat x(1, 1, CV_64FC1, 1.0f);
Mat p(1, 4, CV_64FC1, 5.0f);
EXPECT_ANY_THROW(
x += p;
) << x;
}
{
Mat x(1, 1, CV_64FC1, 1.0f);
Mat p(1, 4, CV_64FC1, 5.0f);
EXPECT_ANY_THROW(
x -= p;
) << x;
}
}
//These tests guard regressions against running MatExpr
//operations on empty operands and giving bogus
//results.
TEST(Core_MatExpr, empty_check_15760)
{
EXPECT_THROW(Mat c = min(Mat(), Mat()), cv::Exception);
EXPECT_THROW(Mat c = abs(Mat()), cv::Exception);
EXPECT_THROW(Mat c = min(Mat(), Mat()), cv::Exception);
EXPECT_THROW(Mat c = Mat() | Mat(), cv::Exception);
EXPECT_THROW(Mat c = Mat() + Mat(), cv::Exception);
EXPECT_THROW(Mat c = Mat().t(), cv::Exception);
EXPECT_THROW(Mat c = Mat().cross(Mat()), cv::Exception);
}
// https://github.com/opencv/opencv/issues/23577
// A scalar passed to Mat::mul() binds to _InputArray(const double&), i.e. to a temporary
// double on the caller's stack. The returned MatExpr used to keep a Mat header pointing at
// that stack slot after it died. The helpers are called through volatile function pointers
// so they cannot be inlined, which makes the stale-stack read deterministic.
MatExpr makeScalarMulExpr(const Mat& m, double scale)
{
return m.mul(scale);
}
void overwriteStackFrame()
{
volatile double buf[256];
for (int i = 0; i < 256; i++)
buf[i] = -1.0;
(void)buf;
}
TEST(Core_MatExpr, mul_scalar_use_after_scope_23577)
{
MatExpr (*volatile makeExprFn)(const Mat&, double) = makeScalarMulExpr;
void (*volatile overwriteFn)() = overwriteStackFrame;
Mat m(2, 3, CV_32FC1, Scalar::all(3.0f));
MatExpr e = makeExprFn(m, 7.0);
overwriteFn();
Mat res = e;
EXPECT_EQ(0, cvtest::norm(res, Mat(2, 3, CV_32FC1, Scalar::all(21.0f)), NORM_INF));
}
// Disabled with the new broadcasting element-wise engine: a 4x1 CV_64F *Mat* is no longer treated as a
// Scalar (only true scalars - numbers / cv::Scalar / Vec / Matx, which arrive via _InputArray::MATX -
// are scalars; real Mats ride broadcasting). Here b broadcasts against a(1x1) -> 4x1, not 1x1. A
// follow-up OpenCV issue tracks this intended behavior change.
TEST(Core_Arithm, DISABLED_scalar_handling_19599) // https://github.com/opencv/opencv/issues/19599 (OpenCV 4.x+ only)
{
Mat a(1, 1, CV_32F, Scalar::all(1));
Mat b(4, 1, CV_64F, Scalar::all(1)); // MatExpr may convert Scalar to Mat
Mat c;
EXPECT_NO_THROW(cv::multiply(a, b, c));
EXPECT_EQ(1, c.cols);
EXPECT_EQ(1, c.rows);
}
// https://github.com/opencv/opencv/issues/24163
typedef tuple<perf::MatDepth,int,int,int> Arith_Regression24163Param;
typedef testing::TestWithParam<Arith_Regression24163Param> Core_Arith_Regression24163;
TEST_P(Core_Arith_Regression24163, test_for_ties_to_even)
{
const int matDepth = get<0>(GetParam());
const int matHeight= get<1>(GetParam());
const int matWidth = 3; // Fixed
const int alpha = get<2>(GetParam());
const int beta = get<3>(GetParam());
// If alpha and/or beta are negative, and matDepth is unsigned, test is passed.
if( ( (alpha < 0) || (beta < 0) )
&&
( (matDepth != CV_8S) && (matDepth != CV_16S) && (matDepth != CV_32S) ) )
{
throw SkipTestException( cv::format("Test is skipped(matDepth is not signed, alpha = %d, beta = %d)", alpha, beta) );
}
const int matType = CV_MAKE_TYPE(matDepth, 1);
const Size matSize(matWidth, matHeight);
const Mat src1(matSize, matType, Scalar(alpha,alpha,alpha,alpha));
const Mat src2(matSize, matType, Scalar(beta, beta, beta, beta));
const Mat result = ( src1 + src2 ) / 2;
const int rounding = fegetround();
fesetround(FE_TONEAREST);
const int mean = (int)lrint( static_cast<double>(alpha + beta) / 2.0 );
fesetround(rounding);
const Mat expected(matSize, matType, Scalar::all(mean));
// Compare result and extected.
ASSERT_EQ(expected.size(), result.size());
EXPECT_EQ(0, cvtest::norm(expected, result, NORM_INF)) <<
"result=" << std::endl << result << std::endl <<
"expected=" << std::endl << expected;
}
INSTANTIATE_TEST_CASE_P(/* */, Core_Arith_Regression24163,
testing::Combine(
testing::Values(perf::MatDepth(CV_8U), CV_8S, CV_16U, CV_16S, CV_32S), // MatType
testing::Values( 3, 4, 5, 6), // MatHeight
testing::Values(-2,-1, 0, 1, 2), // src1
testing::Values( -1, 0, 1 ) // src2
)
);
}} // namespace