Commit Graph

193 Commits

Author SHA1 Message Date
Shiven Solanki
76bae0c542 core: support CV_16F and CV_16BF in finiteMask (#30620)
* core: support CV_16F and CV_16BF in finiteMask

finiteMask asserted CV_32F or CV_64F input, so 16-bit float arrays,
which can hold NaN and infinity too, could not be checked.

Add finiteMask16_, which marks a pixel as finite if no channel has an
all-ones exponent (0x7c00 for CV_16F, 0x7f80 for CV_16BF), for 1 to 4
channels. getFiniteMaskFunc now takes the depth. The OpenCL kernel only
handles float and double, so other depths fall back to the CPU path.

* core: use SIMD and typed templates in 16-bit finiteMask

Use hfloat and bfloat as the template parameter of finiteMask16_ instead
of the raw exponent masks, and add a universal-intrinsics path for 1 to
4 channels.

Add Core_FiniteMask_bits, which checks exact bit patterns at the edges
of the exponent: largest finite, subnormal, signalling, quiet and
negative NaN, and both infinities.

* core: use the scalar loop for 1-channel 16-bit finiteMask

With 1 channel, the compiler vectorizes the scalar loop, and it runs
faster than the explicit SIMD path. Use the SIMD path only for 2 to 4
channels.
2026-11-13 15:36:54 +05:30
Abhishek Gola
370175b3bd Merge pull request #30624 from sshivensolanki/core-lut-test-bool
core: remove CV_Bool conversion from LUT tests
2026-11-10 16:23:21 +05:30
Shiven Solanki
f5f76c0786 core: fix cv_absdiff overflow for int64 in norm of CV_64S
Fixes #30731
2026-11-10 00:32:38 +08:00
Shiven Solanki
566df44633 core: support fp8 depths in cv::sum and cv::mean (#30670)
* core: support fp8 depths in cv::sum

cv::sum and cv::trace threw for CV_8F_E4M3FN and CV_8F_E4M3FNUZ. Add
sum8f and sum8fnuz to the function table, and collect their float totals
in blocks like CV_16F and CV_16BF.

* core: test cv::sum on fp8 past the block size

Add a (1 << 15) + 1 element case to Core_Sum_FP8, so the float total is
moved to the double result and reset between blocks.

* core: support fp8 depths in cv::mean

cv::mean uses the same adding functions as cv::sum, so adding fp8 to that table made it accept these depths. Its blockSum check still left them out, so the float totals were written straight into the double result and the mean came back wrong. Use the block path for CV_8F_E4M3FN and CV_8F_E4M3FNUZ, as cv::sum does, and check cv::mean in Core_Sum_FP8.

* core: test cv::mean with a mask on fp8

* core: split Core_Sum_FP8 into sum, mean and mean_mask tests

Move the array setup into a fixture, and make the length a test parameter, so each case runs on its own.
2026-11-09 09:41:13 +05:30
Shiven Solanki
bb8cbcdb0b Merge pull request #30715 from sshivensolanki:core-carttopolar-inplace-5x
core: fix in-place cartToPolar when only the magnitude overwrites an input (5.x) - #30715

5.x port of #30646, as requested in its review. Fixes #30645 on 5.x.

### Problem

`cv::cartToPolar` gives wrong results on `CV_32F` when only the magnitude output is the same `Mat` as `x` or `y`. The SIMD tail handling repeats the last full block, and `cartToPolar32f_` only skipped that for in-place calls when the angle was aliased.

### Fix

Same as #30646: added `mag == X || mag == Y` to the check, so these calls handle the leftover elements with the scalar code.

### Tests

Same `Core_CartToPolar_inplace_mag.accuracy` test as #30646 (`CV_32F`, lengths 1 to 39, magnitude overwriting `x`, then `y`). On Apple M1 Pro it fails without the fix on 5.x and passes with it. The full `opencv_test_core` passes.

### Pull Request Readiness Checklist

See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
      Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake
2026-11-08 11:47:11 +03:00
Vincent Rabaud
e40204af2b Have EwMul::scl match the SIMD implementation in vecBinaryKernel (#30643)
* match SIMD and scalar scale association in EwMul

Restore `EwMul::scl` from `(a * b) * s` to `(a * s) * b` so the scalar
path matches SIMD `vec(preproc(a, s), b)` and avoids premature `float`
overflow on `a * b`.

Canonicalize single-sided `src1` broadcasts (`s1x == 0` or `s1y == 0`)
onto `src0` for `EwMul` in `vecBinaryKernel` and `scalarBinaryKernel`,
preserving loop-hoisted `b * s` in SIMD while matching the `(b * s) * a`
grouping in the scalar tails.

* Add more tests
2026-11-04 12:52:29 +05:30
Abhishek Gola
739c1e60fd Merge pull request #30611 from sshivensolanki/fix-bitwise-not-bool
core: make bitwise_not a logical NOT for CV_Bool
2026-11-02 14:48:40 +05:30
Shiven Solanki
482f8f784b core: remove CV_Bool conversion from LUT tests
The Core_LUT tests converted CV_Bool results to CV_8U before comparing
them, because cv::norm did not support CV_Bool at the time. cv::norm
handles CV_Bool now, so remove the conversion and its TODO.
2026-11-02 13:09:19 +08:00
Shiven Solanki
45080272b8 core: support CV_16F and CV_16BF in patchNaNs
patchNaNs asserted CV_32F or CV_64F input, so 16-bit float arrays,
which can hold NaN too, could not be patched.

Add patchNaNs_16, the same bit test as the 32-bit kernel on 16-bit
words, with the infinity pattern of each format (0x7c00 for CV_16F,
0x7f80 for CV_16BF). getPatchNanFunc now takes the depth. The OpenCL
kernel only handles float and double, so other depths fall back to
the CPU path.
2026-11-01 04:47:29 +08:00
Shiven Solanki
806a40d66e core: treat any non-zero CV_Bool as true in bitwise_not, skip OpenCL
- The CV_Bool NOT kernel now computes x == 0 instead of x ^ 1, so a
  non-0/1 byte (still true, as in convertTo) becomes 0 instead of 254.
  The cvtest::logicOp reference does the same.
- bitwise_not no longer tries OpenCL for CV_Bool. It already ended up
  on the CPU kernel, but only because memopTypeToStr() asserts on
  CV_Bool and CV_OCL_RUN catches the exception.
- Core_Bitwise.not_bool also checks a UMat input and 255 bytes in both
  the SIMD loop and the scalar tail.
2026-10-31 22:22:25 +08:00
Shiven Solanki
693cc84722 core: make bitwise_not a logical NOT for CV_Bool
The NOT kernel was picked by element size only, so CV_Bool ran the
same ~x kernel as CV_8U and turned 0/1 into 255/254. Both are non-zero,
so every element of ~mask counted as true. Pass the depth to
getNotFunc and use x ^ 1 for CV_Bool. Fix the same ~x in the
cvtest::logicOp reference, which made Core_Not expect 254.

Add a Core_Bitwise regression test.
2026-10-31 18:09:59 +08:00
Abhishek Gola
8ce9c2c1be Merge pull request #30579 from sshivensolanki/fix-norm-fp8
core: support fp8 depths in cv::norm
2026-10-31 12:58:21 +05:30
Abhishek Gola
576defd806 Merge pull request #30466 from tushar152006/fix-convert-fp-to-64int-range
core: fix convertTo() losing values above int32 when converting from FP to 64-bit int
2026-10-30 14:12:03 +05:30
Shiven Solanki
d107ce0e5c core: compare fp8 norm test with EXPECT_DOUBLE_EQ
With IPP, cv::norm of the CV_32F reference computes NORM_L2SQR as the square of NORM_L2, which can be off by 1 ulp (66.5625 vs 66.56250000000001).
2026-10-30 16:02:39 +08:00
Abhishek Gola
5fc1aaf807 Merge pull request #30537 from sshivensolanki/fix-reduce-arg-new-depths
core: support CV_Bool and fp8 depths in reduceArgMax and reduceArgMin
2026-10-29 18:03:13 +05:30
Shiven Solanki
c415e4fcef Merge pull request #30526 from sshivensolanki:fix-minmax-fp8
core: support fp8 depths in minMaxLoc and minMaxIdx - #30526

Fixes #30525

### Problem

`minMaxIdxTab` (`modules/core/src/minmax.simd.hpp`) has no entries for `CV_8F_E4M3FN` and `CV_8F_E4M3FNUZ`, so `cv::minMaxLoc` and `cv::minMaxIdx` fail with `func != 0` for fp8 input.

### Fix

- `modules/core/include/opencv2/core/private.hpp`: new `CV_TOGGLE_FP8(x)`, the 8-bit version of `CV_TOGGLE_FLT`: it flips the 7 magnitude bits of negative values, so sign-magnitude fp8 bytes compare in the same order as `int8`.
- `modules/core/src/minmax.simd.hpp`: new `minMaxIdx8f`, used for both fp8 depths. It toggles the input in blocks of 1024 bytes and runs the vectorized `minMaxIdx8s` kernel on them.
- `modules/core/src/minmax.dispatch.cpp`: the fp8 result is toggled back and decoded with `fp8_t::decodeLUT()` / `fp8a_t::decodeLUT()`.
- `modules/core/include/opencv2/core.hpp`: removed the outdated `@note` saying that `CV_16F`/`CV_16BF`/`CV_Bool`/`CV_64U`/`CV_64S`/`CV_32U` are not supported for `minMaxLoc` / `minMaxIdx`.

On 1920x1080 input (single thread, Apple M1 Pro), `minMaxLoc` takes 0.14 ms for both fp8 depths (0.11 ms for `CV_8U`), compared with 2.8 ms for the first version of this PR, which converted every element to `float`. NaN values are not handled specially: like any other byte, they are ordered by their toggled bit pattern.

### Tests

`MinMaxSupportedMatDepth` and `MinMaxAccuracyNewTypes` (`accuracy` and `accuracy_with_mask`) now also run on both fp8 depths, including each format's largest value (448 / 240) and masked-out outliers. The 8 new cases fail on current 5.x (`func != 0`) and pass with this patch. I also compared the results with a float reference on 1600 random fp8 inputs of different sizes, with and without a mask: values and locations match.

All `*MinMax*` / `*minMax*` tests in `opencv_test_core` pass locally on Apple M1 Pro (3113 tests), with OpenCL enabled and with `OPENCV_OPENCL_DEVICE=disabled`. The full `opencv_test_core` passes, except 7 tests that need `opencv_extra` test data, which I didn't have locally (FileStorage base64 and globbing).

### Pull Request Readiness Checklist

See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
      Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake
2026-10-29 08:35:30 +03:00
Shiven Solanki
684f8c445e core: support fp8 depths in cv::norm
getNormFunc and getNormDiffFunc had no entries for CV_8F_E4M3FN and
CV_8F_E4M3FNUZ, so cv::norm failed with "func != 0". Add the fp8 kernels
with float accumulators and the same block accumulation as CV_16F and
CV_16BF. Add cv_absdiff overloads for fp8_t and fp8a_t that return
float, so the difference of two fp8 values is not rounded back to fp8.

Add a Core_Norm_FP8 test.
2026-10-29 12:20:06 +08:00
Shiven Solanki
18520b5674 core: compare toggled fp8 bytes in reduceArgMax and reduceArgMin
Address review: instead of decoding each fp8 value to float, compare
the bytes as int8 after CV_TOGGLE_FP8, which keeps the order of the
sign-magnitude values. reduceMinMaxImpl runs on a one-byte ToggledFp8
type, so no temporary copy is needed.

Add -1 to the ReduceArgNewTypes values, so the test fails if the fp8
bytes are compared without toggling.
2026-10-29 11:09:32 +08:00
Shiven Solanki
67c2e2c3ff core: support CV_Bool and fp8 depths in reduceArgMax and reduceArgMin
depthDispatch had no case for CV_Bool, CV_8F_E4M3FN and CV_8F_E4M3FNUZ,
so reduceArgMax / reduceArgMin failed with "Unsupported matrix type".
Dispatch them to bool, fp8_t and fp8a_t; the fp8 types compare through
their float conversion.

Add a ReduceArgNewTypes test, since ElemWiseTest does not generate these
depths.
2026-10-27 02:16:24 +08:00
Shiven Solanki
fca52f6284 core: support fp8 lookup tables in LUT
getLUTFunc had no case for CV_8F_E4M3FN and CV_8F_E4M3FNUZ tables, so
cv::LUT failed with "An unexpected type combination was specified". LUT
only copies table entries, so use the same 1-byte copy as CV_Bool for
both 8-bit and 16-bit indices.

Add both fp8 depths to the LUTAccuracyNewDstTypes test.
2026-10-27 01:06:00 +08:00
Tushar Burla
e1d90775be core: fix convertTo() losing values above int32 when converting from FP to 64-bit int
In modules/core/src/convert.hpp, v_store_as() for 64-bit integer destinations (int64_t and uint64_t) from v_float32 rounded into a 32-bit integer (v_int32) before widening, causing values outside the 32-bit signed range (e.g. >= 2^31 in CV_16BF / CV_16F) to saturate to INT32_MIN/INT32_MAX on the SIMD path.

Use buffer-based saturate_cast<int64_t> / saturate_cast<uint64_t> to preserve the full 64-bit destination range, matching the existing precedent for v_store_pair_as(v_float64) and v_store_pair_as(unsigned, v_float32).

Add Core_ConvertTo64Int regression tests across vector and scalar lengths.

Resolves #29996.
2026-10-23 23:18:58 +05:30
Alexander Smorkalov
e552fd3c2d Updated test data for division to satisfy armv7a. 2026-10-22 17:20:33 +03:00
Abhishek Gola
781f49134b Merge pull request #30430 from sshivensolanki/opt-findnonzero-simd
core: SIMD fast path for findNonZero on 8-bit inputs
2026-10-22 14:30:34 +05:30
Shiven Solanki
4943b4d65a core: simplify findNonZero accuracy test 2026-10-21 16:36:42 +08:00
Shiven Solanki
155f4e18fd core: SIMD fast path for findNonZero on 8-bit inputs 2026-10-21 15:22:28 +08:00
pranayr710
afa5b1b5f3 core: saturate cv::absdiff on CV_64S instead of letting it return a negative
getAbsdiffFunc_() documents that a signed depth has two outputs: R == T, the saturating |a-b| kept
in the signed range, which is the depth cv::absdiff returns; and R == the unsigned type of the same
width. CV_8S, CV_16S and CV_32S each have both. CV_64S only had the unsigned one, so the signed
form fell through to a path that wraps:

    absdiff(INT64_MIN, 0)         -> -9223372036854775808
    absdiff(INT64_MIN, INT64_MAX) -> -1

at every length, scalar included, in a CV_64S destination. The narrower depths all saturate at
their maximum: absdiff(INT_MIN, INT_MAX) on CV_32S is INT_MAX.

The missing row now uses EwAbsdiffS, whose scalar step gains a 64-bit overload. The generic one
widens into the work type, which the narrower depths have (short, int, int64_t) and 64-bit does not,
and |INT64_MIN - b| does not fit in int64_t anyway. The difference is therefore taken in uint64,
which is exact for every pair, and clamped to INT64_MAX. The narrower depths reach that overload
only through their int64 work type, where |a - b| is at most 2^32 and the clamp is a no-op.

Core_AbsdiffSigned checks both properties - never negative, and saturating at the depth's maximum -
across CV_8S, CV_16S, CV_32S and CV_64S.
2026-10-21 09:49:45 +03:00
Abhishek Gola
56d8dcb149 Merge pull request #30206 from pranayr710/fix/convert-64u-signed
core: stop convertTo() treating CV_64U as signed
2026-10-20 09:39:40 +05:30
Alexander Smorkalov
22d61d85da Merge pull request #30341 from sshivensolanki:fix-findnonzero-fp8
core: fix findNonZero for fp8 depths
2026-10-19 09:09:46 +03:00
pranayr710
32b8669583 core: stop convertTo() treating CV_64U as signed
CV_64U is the only unsigned depth whose range does not fit in the signed type of the same width, so
reading its bit pattern as signed goes unnoticed until the top bit is set. Three places did.

1. CV_64U -> CV_64S dispatched to cvt64s, a raw byte copy, so nothing saturated: 2^63 became
   INT64_MIN and UINT64_MAX became -1, at every length. CV_32U -> CV_32S saturates, so this is now
   a saturating conversion like the rest.

2. vx_load_pair_as(const uint64_t*, v_float64&, v_float64&) and
   vx_load_as(const uint64_t*, v_float32&) both converted with v_cvt_f64(), which takes signed
   lanes, so CV_64U to CV_64F, CV_32F, CV_16F and CV_16BF returned negative values above INT64_MAX.
   Vector body only, so the same value was right at length 1 and wrong at length 16.

The unsigned conversion splits into two halves below 2^32: each converts exactly, scaling the high
half by 2^32 is exact, and the single add is the only rounding, so the result matches (double)x.
Converting the bit pattern as signed and adding 2^64 back would round twice - for 2^63 + 1025 that
gives 2^63 where (double)x is 2^63 + 2048.

Core_ConvertFrom64U covers the integer and floating-point destinations, with 2^63 + 1025 among the
values since it is the case that distinguishes one rounding from two.
2026-10-17 00:30:36 +05:30
Shiven Solanki
b1a94cda72 core: fix findNonZero for fp8 depths 2026-10-17 00:08:23 +08:00
Shiven Solanki
f365611686 core: report the unsupported type in cv::sum error message 2026-10-16 15:21:15 +08:00
pranayr710
ec1ee5a5fb Merge pull request #30199 from pranayr710:fix/convert-32u-signed-and-precision
core: fix convertTo() from CV_32U returning negative values for CV_16BF and losing precision for CV_64F - #30199

Fixes #30198.

Two entries in the `32u` block of `convert.simd.hpp` pick the wrong type. Both make `convertTo()` from `CV_32U` return something an unsigned source cannot produce, and both are one-line changes.

### 1. `CV_32U -> CV_16BF` declared its source as `int`

```cpp
DEF_CVT_FUNC(32u16bf, cvt1_, int, bfloat, v_float32)
```

Every other entry in the block says `unsigned`, including the neighbouring `CV_32U -> CV_16F`, which is correct. So everything above `INT_MAX` was read as negative - `UINT_MAX` converted to `-1`, `3000000000` to `-1291845600`.

This one is wrong at **every length, scalar path included**, because the type is wrong at the declaration rather than in the vector code.

### 2. `CV_32U -> CV_64F` widened through `float`

```cpp
DEF_CVT_FUNC(32u64f, cvt_, unsigned, double, v_float32)
```

`float` has a 24-bit mantissa and cannot hold a `uint32`, so values above 2^24 were rounded on the way to a destination that represents all of them exactly: `16777217` came back as `16777216`, `UINT_MAX` as `4294967296`. Only the vector body was affected, so the same value was correct at length 8 and wrong at length 16.

`CV_32U` was the only integer depth converting to `CV_64F` through `float` - `8U`, `8S`, `16U`, `16S` and `32S` go via `v_int32`, `64U` and `64S` via `v_float64`. It now uses the exact 64-bit path like the rest.

### One thing that needed care

`vx_load_pair_as(const unsigned*, v_float64&, v_float64&)` backed that exact path with a scalar spill through a buffer, so simply switching to it would have traded precision for speed - which is not a trade worth offering. It now widens to 64 bits and uses the existing signed conversion, exact because every `uint32` is a non-negative `int64`, and stays vectorized:

```cpp
v_uint64 lo, hi;
v_expand(vx_load(ptr), lo, hi);
a = v_cvt_f64(v_reinterpret_as_s64(lo));
b = v_cvt_f64(v_reinterpret_as_s64(hi));
```

No new HAL primitive is needed - `v_cvt_f64(v_int64)` exists on every backend.

### How these were found

A length-independence sweep over the element-wise operations: 2688 combinations of depth, boundary value and length, checking that an element's result never depends on how many elements sit beside it.

Worth recording that the sweep's first output was misleading. It reported `add`, `absdiff` and `multiply` on `CV_32U` as broken, because it compared results via `convertTo(CV_64F)` - which is defect 2. Reading the raw `uint32` lanes instead showed all three are exact, and that the readback was the bug. I would have filed three imaginary bugs by trusting the first run.

### Testing

`Core_ConvertFrom32U` asserts that no conversion from `CV_32U` is ever negative, and that `CV_64F` - the only destination here that can represent every `uint32` - is exact. Lengths straddle the vector width so the body, the tail and the two together are covered.

Checked it fails without the patch rather than assuming: **36 of its 224 cases fail** on current 5.x with only the test applied.

With the patch: 228/228 on `*ConvertTo*` and `*ConvertFrom32U*` at both the default dispatch and `OPENCV_CPU_DISABLE=AVX2,AVX,FP16`. Full `opencv_test_core` 17185 passed, with only the 7 filestorage/globbing failures this machine always has.

### Note on overlap

#30178 also touches `convert.hpp` and `test_arithm.cpp`, but in the other direction (16-bit float sources into wide integer destinations) and in different regions of both files, so there is no functional overlap - only a possible textual conflict in the test file, which I am happy to rebase around.

### Pull Request Readiness Checklist

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
- [x] The feature is well documented and sample code can be built with the project CMake
2026-10-15 12:38:17 +03:00
Abhishek Gola
3f426d1f1b Merge pull request #30207 from abhishek-gola:core-drop-nd-suffix
drop ND prefix from the functions - #30207

Merge pull request #30207 from abhishek-gola:core-drop-nd-suffix

### Pull Request Readiness Checklist

See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
      Patch to opencv_extra has the same branch name.
- [x] The feature is well documented and sample code can be built with the project CMake
2026-10-14 11:26:22 +03:00
Vincent Rabaud
57c4544b70 use float32 intermediate instead of float16 for CV_8U and CV_8S
On ARM with CV_SIMD_16F, getMulFunc_, getDivFunc_, and getAddWeightedFunc_
used float16 for 8-bit integer SIMD kernels, leading to precision loss
and overflow (> 65504). Switch to float32 to match x86 and ensure precision.
2026-10-13 11:35:33 +02:00
Alexander Smorkalov
a232314184 Merge pull request #30185 from asmorkalov:as/arithmetics_fix
Fix Scalars and small matrix broadcasting logic. - #30185

Replaces https://github.com/opencv/opencv/pull/30166

**non-continuous** array of the same shape and type (e.g. a column `P.col(0)` of a 4xN matrix of homogeneous 3D
points) silently treats the continuous operand as a `cv::Scalar` and broadcasts its first element:

`cc` continuous 4x1 `CV_64FC1`, `P.col(0)` same shape but non-continuous
cc = [10, 20, 30, 40] — a continuous 4x1 CV_64FC1.
It comes from P, a 4x10 CV_64F matrix filled with `P.at<double>(i,j) = 10*(i+1) + j:`
```
P = [ 10 11 12 ... 19
      20 21 22 ... 29
      30 31 32 ... 39
      40 41 42 ... 49 ]
```

### Same-shape pair

| op | src1 | src2 | Expected | 4.x (4.6) | 5.x HEAD | 5.x + PR 30185 |
|---|---|---|---|---|---|---|
| `subtract` | `cc` | `P.col(0)` | `0 0 0 0` | `0 0 0 0` | **`0 -10 -20 -30`** | `0 0 0 0` |
| `subtract` | `P.col(0)` | `cc` | `0 0 0 0` | `0 0 0 0` | **`0 10 20 30`** | `0 0 0 0` |
| `add` | `cc` | `P.col(0)` | `20 40 60 80` | `20 40 60 80` | **`20 30 40 50`** | `20 40 60 80` |
| `multiply` | `cc` | `P.col(0)` | `100 400 900 1600` | `100 400 900 1600` | **`100 200 300 400`** | `100 400 900 1600` |
| `divide` | `cc` | `P.col(0)` | `1 1 1 1` | `1 1 1 1` | **`1 0.5 0.33333 0.25`** | `1 1 1 1` |
| `absdiff` | `cc` | `P.col(0)` | `0 0 0 0` | `0 0 0 0` | **`0 10 20 30`** | `0 0 0 0` |
| `min` | `cc` | `P.col(0)` | `10 20 30 40` | `10 20 30 40` | **`10 10 10 10`** | `10 20 30 40` |
| `max` | `cc` | `P.col(0)` | `10 20 30 40` | `10 20 30 40` | `10 20 30 40` | `10 20 30 40` |
| `compare EQ` | `cc` | `P.col(0)` | `255 255 255 255` | `255 255 255 255` | **`255 0 0 0`** | `255 255 255 255` |
| `addWeighted` | `cc` | `P.col(0)` | `0 0 0 0` | `0 0 0 0` | **`THROW`** | `0 0 0 0` |
| `bitwise_xor` | `cc` | `P.col(0)` | `0 0 0 0` | `0 0 0 0` | **`0 2.2e-308 3.6e-308 7.1e-307`** | `0 0 0 0` |
| `subtract` +mask | `cc` | `P.col(0)` | `0 0 0 0` | `0 0 0 0` | **`0 -10 -20 -30`** | `0 0 0 0` |
| `operator-` | `cc` | `P.col(0)` | `0 0 0 0` | `0 0 0 0` | **`0 -10 -20 -30`** | `0 0 0 0` |

### Genuine `Scalar` partner

| op | src1 | src2 | Expected | 4.x (4.6) | 5.x HEAD | 5.x + PR 30185 |
|---|---|---|---|---|---|---|
| `subtract` | `cc` | `Scalar(5)` | `5 15 25 35` | `5 15 25 35` | **`5 20 30 40`** | `5 15 25 35` |
| `subtract` | `Scalar(5)` | `cc` | `-5 -15 -25 -35` | `-5 -15 -25 -35` | **`-5 -20 -30 -40`** | `-5 -15 -25 -35` |
| `subtract` | `cc` | `Scalar(5,6,7,8)` | `5 15 25 35` | `5 15 25 35` | **`5 14 23 32`** | `5 15 25 35` |
| `subtract` | `cc` | `Vec4d(5,6,7,8)` | `5 15 25 35` | `5 15 25 35` | **`5 14 23 32`** | `5 15 25 35` |
| `add` | `cc` | `Scalar(5)` | `15 25 35 45` | `15 25 35 45` | **`15 20 30 40`** | `15 25 35 45` |
| `multiply` | `cc` | `Scalar(2)` | `20 40 60 80` | `20 40 60 80` | **`20 0 0 0`** | `20 40 60 80` |
| `divide` | `cc` | `Scalar(2)` | `5 10 15 20` | `5 10 15 20` | **`5 inf inf inf`** | `5 10 15 20` |
| `max` | `cc` | `Scalar(25)` | `25 25 30 40` | `25 25 30 40` | **`25 20 30 40`** | `25 25 30 40` |
| `compare GT` | `cc` | `Scalar(25)` | `0 0 255 255` | `0 0 255 255` | **`0 255 255 255`** | `0 0 255 255` |
| `operator-` | `cc` | `Scalar(5)` | `5 15 25 35` | `5 15 25 35` | **`5 20 30 40`** | `5 15 25 35` |
| `subtract` | `cc` | `Scalar::all(5)` | `5 15 25 35` | `5 15 25 35` | `5 15 25 35` | `5 15 25 35` |
| `subtract` | `cc` | `Vec<double,1>(5)` | `5 15 25 35` | `5 15 25 35` | `5 15 25 35` | `5 15 25 35` |
| `subtract` | `UMat cc` | `Scalar(5)` | `5 15 25 35` | `5 15 25 35` | `5 15 25 35` | `5 15 25 35` |

### Pull Request Readiness Checklist

See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [ ] The PR is proposed to the proper branch
- [ ] There is a reference to the original bug report and related work
- [ ] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
      Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake
2026-10-12 13:38:25 +03:00
Abhishek Gola
0054f3aa7e Merge pull request #30159 from pranayr710/fix/norm-l1-32s
core: fix cv::norm(CV_32S, NORM_L1) returning negative at INT_MIN and losing precision above 2^24
2026-10-12 13:27:56 +05:30
Vincent Rabaud
282e14732f allow empty array with scalar operand in arithm_op
Previously, arithm_op returned an empty output when one operand was an
empty Mat and the other was a Scalar.
The new element-wise engine asserted `src1.empty() == src2.empty()` before
checking `isScalarArg`, causing calls such as `cv::max(empty_mat, 1.0, dst)`
or `cv::add(empty_mat, Scalar(1), dst)` to fail with an assertion error.
2026-10-11 22:13:22 +02:00
pranayr710
03160275da core: report out-of-range cases as skipped, and test cv_abs() directly
- The CV_32S instantiation covers values outside the int32 range, which only apply to CV_64S.
  Those now throw SkipTestException so they are reported as skipped rather than silently passing.

- Core_CvAbs checks cv_abs() at the lowest value of each signed type, where the magnitude is not
  representable in that type. The norm test only reaches cv_abs() indirectly, so a direct one makes
  the contract explicit and fails for an obvious reason if it regresses.
2026-10-10 19:55:25 +05:30
pranayr710
70dc2027b9 core: address review - fix cv_abs(int64) too, and tighten the test
- cv_abs(int64) had the same std::abs UB at INT64_MIN that cv_abs(int) had, so
  cv::norm(CV_64S, NORM_L1) still returned a negative value - at every length, masked and unmasked.
  Verified that before changing it. Same fix: negate in the unsigned type.

- Core_NormL1_32S becomes Core_NormL1_Signed and covers CV_64S alongside CV_32S, so both signed
  integer depths are held to the same rule.

- EXPECT_DOUBLE_EQ -> EXPECT_EQ, since the test does claim exact equality: every value used is
  below 2^53 in magnitude and so is its total.

- Shortened the comments in the test and in norm.simd.hpp to describe what the code must do rather
  than retell the defects.
2026-10-10 19:55:25 +05:30
pranayr710
3a0c43a19d core: fix cv::norm(CV_32S, NORM_L1) returning negative and losing precision
Two independent defects, both visible from the same observation: an L1 norm is a sum of
magnitudes, so it can never be negative and can never depend on how many elements sit beside a
given one. cv::norm() on CV_32S broke both rules.

1. Negative result at INT_MIN. cv_abs(int) is (unsigned)std::abs(x), and std::abs(INT_MIN) is
   undefined - its result is not representable in int. In optimized builds the contribution came
   out negative, so

       cv::norm(Mat(1, 1, CV_32S, Scalar(INT_MIN)), NORM_L1)  ==  -2147483648

   With a mask this is wrong at every length, since the masked path is scalar throughout.
   Fixed at the source by negating in unsigned, where INT_MIN's magnitude is an ordinary value.
   Behaviour is unchanged for every other input, and the UB is gone for all other callers too.

2. Precision loss above 2^24 in the vector body. NormL1_SIMD<int, double> widened int32 to float
   before accumulating into double, and float cannot represent every int32, so values above 2^24
   were rounded first:

       127 elements of INT_MAX  ->  272730423281, exact answer 272730423169

   Only the vector body was affected, so the error appeared once the array was long enough to
   enter it - the same answer was correct at length 8 and wrong at length 16. Widen straight to
   double instead and take the magnitude there; this is exact over the whole int32 range,
   INT_MIN included, and is the same conversion the NEON backend already documents as the
   correct replacement for an f32 round-trip.

NORM_INF and NORM_L2 on CV_32S were already correct and are untouched: NORM_INF accumulates in
unsigned, and NORM_L2 uses v_dotprod_expand_fast, which stays in integers.

Core_NormL1_32S covers both defects over masked and unmasked input, asserting non-negativity as
well as the exact value, at lengths straddling the vector width.
2026-10-10 19:55:25 +05:30
Abhishek Gola
0f0b88d926 Merge pull request #29965 from pranayr710/fix/convert-64bit-saturation
core: saturate when narrowing 64-bit and 32U sources in convertTo
2026-10-09 14:36:04 +05:30
Lazizbek Ergashev
c0baf47b20 Merge pull request #30154 from lazerg:fix/issue-30153-inrange-bool
core: reject CV_Bool input in inRange instead of crashing - #30154

Fixes #30153.

`cv::inRange` has no kernel for `CV_Bool` (or the two `CV_8F` depths), so `getInRangeFunc()` returns a null pointer and the call segfaults. Like `addWeighted` in #29883, it now throws `StsNotImplemented` for these depths, and the caller has to convert the input first.

### Pull Request Readiness Checklist

See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch (`5.x`, `CV_Bool` and `CV_8F` don't exist on `4.x`)
- [x] There is a reference to the original bug report and related work (#30153, #29883)
- [x] There is an accuracy test (`Core_Arithm.inRange_unsupported_depth_30153`, which segfaults without the fix); not applicable: performance test and opencv_extra test data
- [x] N/A: this is a bug fix, no new public API or documentation needed
2026-10-06 09:15:49 +03:00
pranayr710
a4ef0452f1 core: use the 64-bit v_select() instead of the local blend helpers
The 64-bit lane forms of v_select() landed with #30071, so the two
hand-written v_blend_s64 / v_blend_u64 helpers this patch carried are no
longer needed. Drop them and call v_select() directly; the argument order
and the all-ones / all-zeros mask convention are identical, so the
generated code is the same where a backend already had a native blend and
better where it now has one.

The shift-and-equality trick stays: the 64-bit ORDERING compares are still
unusable here, since v_gt on v_int64x2 is the sign of (b - a) at the SSE
and NEON baselines.
2026-10-01 20:30:42 +05:30
pranayr710
5493fe0758 core: scope the saturation test's 64-bit values to the 64-bit sources
The values at the ends of the 64-bit range were crossed with the CV_32U
source as well, where they never reach the narrowing this patch changes -
they only exercise the double -> CV_32U conversion that produces the
source array. That conversion is not length-independent on macOS/ARM64,
so those cases failed there for a reason unrelated to this change.

Split the instantiation in two: CV_32U keeps the values that fit its own
range, and the 64-bit sources keep the 64-bit extremes, which is where
they test the clamp. Reverting the clamp still fails the From64 cases at
INT64_MIN and INT64_MAX, so the coverage this adds is unchanged.
2026-10-01 20:29:46 +05:30
pranayr710
4f942c6a3c core: make the 64-bit clamp correct at every dispatch level
The clamp used the 64-bit ordering compares, which was raised in review as
unsafe. It is: at the SSE and NEON baselines v_gt on v_int64x2 is the sign
of (b - a) (intrin_sse.hpp, intrin_neon.hpp), so it overflows - and answers
the wrong way - exactly when the operands sit at opposite ends of the
64-bit range, which is the case a saturating conversion has to get right.
v_gt(INT64_MIN, INT32_MAX) reports true. Only the 256-bit AVX2 path lowers
to a native compare, so the conversion was right when a build dispatched to
AVX2 and wrong at its own baseline:

  Mat src(1, 64, CV_64S, Scalar(INT64_MIN));
  src.convertTo(dst, CV_8U);     // AVX2: 0    SSE/NEON baseline: 255

Use an arithmetic shift and an equality instead. v_eq on 64-bit lanes is
built from 32-bit compares and is exact, and the shift cannot overflow, so
the result no longer varies with the dispatch level. The unsigned-source
helpers already worked this way and are unchanged.

The parameterised test now covers INT64_MIN, INT64_MAX, INT32_MIN and
INT32_MIN-1 as well, so the boundary cases are exercised; NEON has the same
subtraction-based compare, so the ARM CI jobs guard this directly.
2026-10-01 20:29:46 +05:30
pranayr710
93c47b1e24 core: address review on the convertTo saturation fix
Turn the saturation test into a TEST_P over source depth, destination
depth and value, and drop the length sweep in favour of a single 127
element row, which covers both the vector body and an odd tail. Remove a
stray blank line that was not part of the change.

Document why the 64-bit blend is written out by hand: v_select() has no
64-bit integer form on any backend - intrin_sse.hpp carries those two
entries commented out as TBD and the NEON list stops at v_float64x2 - so
the mask is applied with the same v_and/v_gt shape the file already uses.
2026-10-01 20:29:27 +05:30
pranayr710
34b8868876 core: saturate when narrowing 64-bit and 32U sources in convertTo
v_pack() narrows 64-bit lanes by truncation: at the 8/16/32-bit widths
v_pack saturates, but the 64->32 forms are defined with static_cast (see
OPENCV_HAL_IMPL_C_PACK in intrin_cpp.hpp) because no backend offers a
saturating 64->32 pack. The vectorized conversion helpers packed straight
from a 64-bit source, so a value outside the 32-bit range wrapped, and the
saturating narrow that followed then clamped the WRAPPED value - landing at
the wrong end of the destination's range. The same happened one width down,
where a CV_32U source was reinterpreted as signed without clamping.

Only the vector loop was affected, so the answer depended on how long the
array was: below the vector width the scalar path saturated correctly.

  Mat src(1, n, CV_64U, Scalar(4294967295));
  src.convertTo(dst, CV_8U);       // n < 16: 255      n >= 16: 0
  src.convertTo(dst, CV_16U);      // n < 16: 65535    n >= 16: 0

Clamp into the destination's range before packing. The unsigned-source
helpers test the high bits with a shift instead of an ordering compare,
since unsigned 64-bit comparison is not uniformly available across the SIMD
backends, and v_select() has no 64-bit form so the blend goes through the
comparison mask by hand.

Affects CV_64U/CV_64S -> CV_8U/CV_8S/CV_16U/CV_16S/CV_32S and
CV_32U -> CV_8S/CV_16S.
2026-10-01 20:29:06 +05:30
Vadim Pisarevsky
b5c73e9fcf Merge pull request #30007 from vpisarev:fix_flt2int
core: saturating float/double->intXY conversions in cvRound/cvFloor/cvCeil and the corresponding univ. intrinsics. - #30007

Merge pull request #30007 from vpisarev:fix_flt2int

Fixes #28557 (supersedes the tail-only fix from #29895).

### The problem

On x86 `cvtss2si`/`cvtsd2si`/`cvtps2dq` return the "integer indefinite" value `0x80000000` (`INT_MIN`) for any out-of-range input, so

```cpp
cvRound(3e9);                          // INT_MIN
saturate_cast<ushort>(60000.f*60000.f); // 0 instead of 65535  (#28557: the scalar tail of cv::multiply)
v_round(v_float32(1e10f));             // INT_MIN lanes
```

The problem is not x86-only. `cvRound()` on aarch64, riscv64 and loongarch64 went through `(int)lrint()`, which the compilers implement as a 64-bit conversion followed by truncation to 32 bits, i.e. large values *wrap* instead of saturating (`fcvtzs x0` + `mov w0`, `fcvt.l.d` + `sext.w`). NEON `v_round/v_floor/v_ceil/v_trunc(v_float64x2)` narrowed with a wrapping `vmovn`, and `saturate_cast<unsigned/int64/uint64>(float/double)` were plain UB above the target range.

### The fix

**`fast_math.hpp`**
- `cvRound()`, `cvFloor()`, `cvCeil()` saturate on every platform. New `cvTrunc()` (round towards zero, saturating; the scalar counterpart of `v_trunc`) and `cvRound64()` (round-half-to-even to `int64`, saturating).
- x86 (SSE2): the input is clamped from above (`min`) before `cvt*`; the "indefinite" value is already the correct result below `INT_MIN`. `cvFloor` also clamps from below because of the "-1" correction.
- aarch64 (`__GNUC__`/clang): one-instruction inline asm `fcvtns/fcvtms/fcvtps/fcvtzs` (GCC's `arm_neon.h` has no scalar f64→s32 ACLE functions, and inline asm needs no header).
- riscv64: `fcvt.w.{s,d}` / `fcvt.l.{s,d}` with an explicit rounding mode (`rne`, `rdn`, `rup`, `rtz`).
- loongarch64: `ftint*.w.{s,d}` + `movfr2gr.s` (the old `.l.d` + `movfr2gr.d` wrapped); `cvRound` got a branch too.
- MSVC ARM64: the 64-bit results are clamped before narrowing.
- Portable `#else` branch: hand-written clamp before the conversion, no new headers.
- Exact semantics: `double` saturates to `INT_MIN`/`INT_MAX` exactly. `INT_MAX` is not representable as `float`, so `float` inputs `>= 2^31` give **2147483520** (the largest float below 2^31, the clamp value) where the instruction does not saturate by itself (x86, portable) and `INT_MAX` where it does (ARM, RISC-V, LoongArch). Both are accepted by the tests and documented.
- **NaN handling is out of scope in this PR**.

**`saturate.hpp`**
- `float/double → unsigned/int64/uint64` now saturate and use round-half-to-even via `cvRound64()` (no libm `round()` call; OpenCV builds without `-ffast-math`, where `rint()`/`round()` are real calls).
- `int/int64 → schar/short/int` range checks are done in unsigned arithmetic. The old `(unsigned)(v - SHRT_MIN)` overflowed (UB) for `v > INT_MAX - 32768`; such values were unreachable before but are returned by the saturating `cvRound()` now, and GCC 15 actually exploits the UB (derives `v <= INT_MAX-32768` and folds neighbouring comparisons).

**Universal intrinsics**
- SSE, AVX2, AVX-512: clamp before `cvt` in `v_round/v_floor/v_ceil/v_trunc` (f32 and f64, `v_round(a, b)` included). AVX2 keeps `_mm256_floor_ps/_ceil_ps`.
- NEON f64: saturating narrow (`vqmovn_s64`); `v_floor/v_ceil` use `fcvtms/fcvtps` directly; `v_trunc` used `vcvtaq` (round-to-nearest-away) instead of truncation.
- WASM f32: clamp before the `-1/+1` corrections (they wrapped `INT_MIN`); `v_round` was `trunc_sat(a + 0.5)` (wrong for negatives and ties), now `f32x4.nearest`; f64 `v_trunc` via `cvTrunc`.
- MSA f64: clamp before `pckev.w`, which takes the low 32 bits of the saturated int64.
- RVV f16 `v_floor`: rounding mode `2` (RDN) instead of `1` (RTZ).
- VSX, LSX/LASX, RVV f32/f64, RVV 0.7.1: untouched, the conversion instructions saturate by ISA definition.
- `intrin_cpp.hpp`: `v_trunc` via `cvTrunc`; docs mention the saturation.

`arithm.simd.hpp` is not modified: `Core_Arithm.mul_overflow_28557` passes because the scalar tail's `saturate_cast<ushort>(float)` saturates now.

### Tests

- `Core_Arithm.mul_overflow_28557` re-enabled.
- `Core_Arithm.mul_overflow_tail_and_inplace`: 8U/8S/16U/16S, row lengths 1..70 (vector body + scalar tail), out-of-place and in-place `multiply`, `mul`, `pow(x, 2)`.
- `Core_ConvertTo.float_overflow_saturation`: 32F/64F → 8U/8S/16U/16S/32S/32U/64S/64U with `±1e10`, `±1e30`, `±inf`, `2147483647.5`, `x.5` etc.; vector body vs. scalar reference, extreme inputs must hit the type limits.
- `Core_FastMath.SaturatingRoundingOps`: boundary table (`2147483647.5`, `-2147483648.5`, `2147483520f`, `-2147483904f`, `±DBL_MAX`, `±inf`, ...) plus a 200k-value log-uniform random sweep against `nearbyint/floor/ceil/trunc` clamped to `int`.
- `Core_FastMath.Round64`: boundaries around `±2^63`, `.5` cases, random sweep.
- `Core_SaturateCast.FloatToIntSaturation`, `RoundHalfToEven`, `IntToNarrowerIntBoundaries` (regression for the signed-overflow UB).
- `test_intrin_utils.hpp` (`test_float_math`, `test_round_pair_f64`): overflow/boundary lanes for f32, f64 and f16, compared against the scalar functions and checked against explicit `INT_MIN` / `[2147483520, INT_MAX]` / `INT_MAX` limits. Runs on every backend and dispatch level.

### Verification

- x86-64, GCC 15.2, `CPU_BASELINE=SSE4_2 CPU_DISPATCH=AVX2,AVX512_SKX`: full `opencv_test_core` passes (16864 tests), i.e. SSE4.2 baseline, AVX2 dispatch and the CPP emulator paths. AVX-512 is compile-checked only (no AVX-512 hardware here).
- The standalone scalar checks also pass with the portable `#else` branch forced (`-U__SSE2__`) and under `-fsanitize=undefined`.
- aarch64 (`aarch64-linux-gnu-gcc-14`) and riscv64 (`riscv64-linux-gnu-gcc-14 -march=rv64gcv_zvfh`): compile-checked, generated code inspected (`fcvtns w0, d0`, `fcvt.w.d a0, fa0, rne`, `sqxtn`, `vfcvt.x.f.v`, ...). Not run (no hardware/qemu).
- **Not verified at all** (please watch CI): LoongArch (`ftint*.w.d`/`ftintrne.*` asm), WASM (`wasm_f32x4_nearest`), MSA, MSVC ARM64 (`vcvtd_s64_f64`, `vcvts_s32_f32`, `vcvtnd_s64_f64`).

### Behaviour changes worth noting

- `saturate_cast<unsigned/int64/uint64>(x.5)` now rounds half to even (was half away from zero), consistent with all the other integer targets.
- `cvRound(float)` for inputs `>= 2^31` returns **2147483520** on x86 (was `INT_MIN`); `INT_MAX` on ARM/RISC-V. It would be noticeably slower to implement true saturation to `INT_MAX`. Note that around `INT_MAX` float's cannot represent the integer's exactly anyway.
- `saturate_cast<int>(1e10)` is `INT_MAX` (documentation used to say "no clipping is done for 32-bit integers").

### Pull Request Readiness Checklist

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on code under GPL or another license incompatible with OpenCV.
- [x] The PR is proposed to the proper branch (`5.x`).
- [x] There is a reference to the original bug report and related work: #28557, #29895.
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable: accuracy tests added, no test data needed.
- [x] The feature is well documented and sample code can be built with the project CMake: doxygen comments of `cvRound`/`cvFloor`/`cvCeil`/`cvTrunc`/`cvRound64`, `saturate_cast` and the intrinsics conversion group updated.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01KVnDjvrFtxcyw7RFzSPews
2026-09-30 09:02:12 +03:00
pranayr710
2aaffd248d Merge pull request #30003 from pranayr710:fix/sum-32bit-accumulator
core: stop cv::sum() wrapping at 32 bits for CV_32U and CV_32S - #30003

Fixes #30002

### Problem

`cv::sum()` returns doubles, but for single-channel `CV_32S` and `CV_32U` it accumulates part of
the total in 32 bits, so a sum beyond the 32-bit range wraps. For `CV_32S` that is signed integer
overflow.

```
Mat m(1, 8, CV_32S, Scalar(INT_MAX));
cv::sum(m)[0];        // -8            expected 17179869176

Mat u(1, 8, CV_32U, Scalar(UINT_MAX));
cv::sum(u)[0];        // 8589934584    expected 34359738360
```

`sum_()`'s unrolled single-channel step adds four elements **to each other** in `WT` before the
result reaches the `ST` accumulator, and `WT` defaults to the source type:

```cpp
s0 += (WT)src[0] + (WT)src[cn] + (WT)src[cn*2] + (WT)src[cn*3];
```

For `CV_8U`/`CV_16U`/`CV_16S` that is harmless — integer promotion widens the operands to `int`
first. For the 32-bit depths the additions happen in 32 bits.

The vectorized specialization only runs from `len >= 6 * vector_width`, so shorter arrays take the
scalar route entirely and longer ones still leave a wrapping tail; and `DEFINE_SUM_SIMD_32` is
instantiated only for `int` and `float`, so `CV_32U` has no vectorized path at all. Multi-channel
inputs are unaffected: those branches add each element straight into its own `double` accumulator.

### Fix

Pass an explicit 64-bit integer `WT` for the two entry points. Widening to 64-bit integers rather
than to `double` keeps the step in integer arithmetic, and four 32-bit values cannot come near the
64-bit range. The 16-bit float entry points already pass an explicit `WT` for the same reason.

### Performance

1920x1080, best of 5 runs of 50 iterations:

| depth | before (wrong) | this patch (int64 WT) | double WT, for comparison |
| --- | --- | --- | --- |
| `CV_32U` | 0.430 ms | 0.407 ms | 0.729 ms |
| `CV_32S` | 0.235 ms | 0.258 ms | 0.268 ms |
| `CV_16U` (not touched) | 0.111 ms | 0.095 ms | |
| `CV_32F` (not touched) | 0.244 ms | 0.254 ms | |

Accumulating in `double` would also fix the wrap but costs about 70% on `CV_32U`, which has no
vectorized path and therefore runs this step for every element. The integer widening has no
measurable cost; run-to-run noise on this machine is around 10%.

### Tests

`Core_SumWide.no_32bit_wraparound` is a `TEST_P` over depth, channel count and length (4, 8, 23,
24, 64, 127 — around the vectorized path's 6-vector-width threshold), asserting the exact total.
It fails on unpatched 5.x:

```text
[  FAILED  ] Core_SumWide.no_32bit_wraparound/0, where GetParam() = (12, 1, 4)
    Which is: 17179869180
    Which is: 4294967292
```

and passes with the patch. Full `opencv_test_core`: 16897 of 16904. The 7 failures
(`Core_InputOutput.filestorage_base64_*`, `Core_globbing.accuracy`) reproduce identically on
unmodified 5.x in this environment and are unrelated.

### Pull Request Readiness Checklist

See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
      Patch to opencv_extra has the same branch name.
- [x] The feature is well documented and sample code can be built with the project CMake
2026-09-29 12:07:34 +03:00
Vincent Rabaud
551dbcac54 Merge pull request #29948 from vrabaud:comma_initializer
Remove deprecated CommaInitializer API - #29948

This goes hand in hand with https://github.com/opencv/opencv_contrib/pull/4217

### Pull Request Readiness Checklist

See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [ ] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
      Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake
2026-09-16 13:59:50 +03:00