Commit Graph

6137 Commits

Author SHA1 Message Date
Shiven Solanki
19fc7d3052 core: support fp8 depths in split, merge and mixChannels 2026-10-14 21:20:21 +08:00
Vincent Rabaud
670368ab56 Add missing ReduceParams wasm bindings 2026-10-14 13:55:26 +02: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
d654f97d8e Merge pull request #30222 from vrabaud:autobuffer
reduce TExpr::exec stack buffer size from 16 KB to 4 KB
2026-10-13 08:48:34 +03:00
Savya Sanchi Sharma
303f83ef92 Merge pull request #29729 from SavyaSanchi-Sharma:vizsplat
Added Gaussian Splat Renderer Support - #29729

Adds 3D Gaussian Splatting support to `ptcloud`: a loader for trained scenes and a `viz3d` renderer that draws them alpha-blended and depth-sorted alongside existing opaque geometry.

### Result

<img width="1842" height="811" alt="splat" src="https://github.com/user-attachments/assets/abfa5c01-6dbb-4367-b426-a618e3748649" />

[.splat source](https://huggingface.co/cakewalk/splat-data/resolve/main/train.splat)

### 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
- [ ] 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-12 16:33:54 +03: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
25beda402a Merge pull request #30157 from abhishek-gola:core-reduce-nd
core: reduceND, used by the DNN Reduce2 layer - #30157

Split out of #30082, which now carries only the resize half.

Adds `cv::reduceND`, which reduces an n-dimensional array over a set of axes with any of the `ReduceTypes`, extended with `REDUCE_PROD`, `REDUCE_L1`, `REDUCE_L2`, `REDUCE_LOG_SUM` and `REDUCE_LOG_SUM_EXP`. `cv::reduce` accepts n-dimensional input through it.

`sum`, `mean` and `minMaxIdx` now share one parallel driver (`stat_parallel.hpp`), so they parallelize over large arrays the same way `reduceND` does.

The new graph engine's `Reduce2` layer calls `cv::reduceND` instead of its own kernels, so `reduce2_kernels.simd.hpp` and the hand-written reduction loops in `reduce2_layer.cpp` go away.

### 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-12 12:08:20 +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
Alexander Smorkalov
31d0b67649 Merge pull request #30232 from vrabaud:pop_back
core: decrement size directly in AutoBuffer::pop_back()
2026-10-12 09:27:13 +03:00
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
Vincent Rabaud
30a7014ecc core: decrement size directly in AutoBuffer::pop_back()
Calling resize(size() - 1) in pop_back() pulls in the buffer growth path
for the unreachable sz == 0 case in release builds (where size() - 1
underflows to SIZE_MAX), which both bloats codegen and triggers an LLVM
ScalarEvolution assertion on 32-bit Hexagon Clang. Guard and decrement
sz directly instead.
2026-10-11 10:36:48 +02:00
pranayr710
7843afa92e core: fix the masked CV_32S L1 norm for INT_MIN
Rebasing onto 5.x picked up facc3fdc7d, which vectorized the masked norm for the remaining depths,
and Core_NormL1_Signed then failed on CI for masked CV_32S at INT_MIN - 13 jobs, every platform.

The new kernel takes the magnitude before widening:

    v_int32 s = v_reinterpret_as_s32(v_and(v_abs(vx_load(src + i)), v_normmask_u32(mask + i)));
    acc0 = v_add(acc0, v_cvt_f64(s));

v_abs() does give |INT_MIN| correctly, as an unsigned 2147483648, but reinterpreting that back as
int32 turns it negative again and the widening carries the sign into the accumulator, so the norm
came out as -16 * 2^31 for 16 elements. Mask the value instead, widen to double - exact for every
int32 - and take the magnitude there, which is what the unmasked path already does.

The 8- and 16-bit masked kernels are not affected: v_abs() returns the unsigned type there too, and
they accumulate in unsigned without reinterpreting back to signed.
2026-10-10 23:40:36 +05:30
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
Vincent Rabaud
0e20693a8d reduce stack buffer size in MatExprInvoker from 128 KB to 32 KB
MatExprInvoker::operator() previously allocated two cv::AutoBuffer<uchar,
16 * 1024 + 64> instances (scratchBuf and tstoreBuf) simultaneously on
the stack, consuming over 32 KB per buffer and pushing the stack frame
over 36 KB. Furthermore, capElems = 16 * 1024 could allocate up to 128 KB
(16K * 8 bytes for CV_64F) before even accounting for multiple scratch
slots, exceeding a typical 32 KB L1 data cache.
2026-10-10 13:54:34 +02:00
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
Abhishek Gola
19041e56a5 Merge pull request #30147 from Teddy-Yangjiale/rvv-hal-interleave
core: use RVV segmented loads/stores for v_load_deinterleave/v_store_interleave
2026-10-09 13:55:33 +05:30
Alexander Smorkalov
4b89eb0ce2 Merge pull request #29989 from vrabaud:variant
Add compile-time fast paths for _InputArray/_OutputArray
2026-10-09 09:01:51 +03:00
Prasadayus
facc3fdc7d core: vectorize masked norm for remaining depths 2026-10-08 18:13:33 +05:30
Alexander Smorkalov
74b4f07668 Merge pull request #30162 from officialarghya29:fix/rect-unsigned-intersection-5x
core: fix Rect_<unsigned> intersection for disjoint rectangles
2026-10-07 10:00:26 +03:00
Abhishek Gola
65766b988a Merge pull request #30083 from abhishek-gola:dnn-eltwise-core-engine
Unify element-wise ops with the core engine - #30083

### 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-07 08:35:31 +03:00
Arghya Bose
0b9c7df2dd core: fix Rect_<unsigned> intersection for disjoint rectangles
Rect_::operator&= computed width - (Rx_max.x - Rx_min.x) before knowing whether
the rectangles actually overlap. For unsigned _Tp the subtraction wraps when the
rectangles are disjoint, so the result was a bogus non-empty rectangle instead of
an empty one:

    Rect_<unsigned>(0, 0, 1, 1) & Rect_<unsigned>(2, 2, 1, 1)  // was [1 x 1 from (2, 2)]

Return an empty rectangle once the coordinate gap exceeds the corresponding
width/height, before the subtraction can underflow.
2026-10-06 21:43:57 +05:30
pranayr710
35d007f30e core: narrow uint64 -> int32 with v_pack + v_min instead of a local clamp
Review follow-up. v_pack() already clamps anything above UINT32_MAX to UINT32_MAX, so narrowing as
unsigned first and bringing the result down to INT32_MAX with the same 32-bit v_min() the
uint32 -> int32 direction already uses gives the right answer for the whole uint64 range, and the
last local clamp helper in this file goes away.

convert.hpp now has no hand-written 64-bit clamping left at all.
2026-10-06 21:17:53 +05:30
pranayr710
4ff82a22c6 core: make v_pack/v_pack_u saturate when narrowing 64 to 32 bits
Review request: fix the narrow globally rather than clamping at one call site.

v_pack() saturated at 8, 16 and 32 bits but truncated at 64->32, and v_pack_u() had no 64-bit form
at all. That is why convertTo() had to clamp by hand before packing: an out-of-range value wrapped
first, and the later saturating narrow to 8 or 16 bits then saturated the WRAPPED value, which is
not merely imprecise but the wrong end of the range (4294967295 -> -1 -> 0 for uchar, not 255).

The backends did not even agree with each other: RVV narrowed with vnclip/vnclipu for 8, 16 and 32
bits but with the truncating vnsra/vnsrl at 64, and NEON used vqmovn for the narrow widths and the
plain vmovn at 64.

All of them now saturate, and all of them gain v_pack_u() for int64 -> uint32:

  - NEON, MSA, RVV, RVV071: the saturating primitive already existed next to the one in use
    (vqmovn/vqmovun, msa_qpack*, vnclip/vnclipu), so these are one-word changes.
  - VSX: vec_packs/vec_packsu instead of vec_pack. The 64-bit v_pack_u was already written here and
    commented out with "not implemented on other platforms", so it is simply enabled.
  - AVX-512: vpmovsqd / vpmovusqd narrow with saturation natively.
  - SSE and AVX2: decided on the two 32-bit halves, so no 64-bit compare is needed - a value fits
    exactly when the high half equals sext(low), and cmpgt on the high half yields 0 / all-ones,
    which doubles as the saturated value for pack_u.
  - WASM, LSX, LASX: no saturating narrow, so OPENCV_HAL_IMPL_SATURATING_PACK_64 in
    intrin_forward.hpp builds it from the backend's truncating narrow, again from the 32-bit halves.
  - intrin_cpp.hpp: saturate_cast instead of static_cast, matching every other width.

A 64-bit ordering compare would have been the obvious way to decide saturation and is the one thing
to avoid here: at the SSE and NEON baselines v_gt on 64-bit lanes is the sign of (b - a), 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 narrow has to get right.

convertTo() now calls v_pack()/v_pack_u() directly and keeps one local helper, for uint64 -> int32:
no width has a v_pack_s, so that direction has no HAL counterpart to use. Its int64 -> uint64 path
also stops using v_gt(x, 0) to clamp negatives, for the reason above, and tests the sign bit instead.

Tests: test_pack64_saturation and test_pack64_u_saturation check the three narrows either side of
the destination range, wired into the uint32 and int32 suites. The pack_saturate_cast carve-out in
test_intrin_utils.hpp that documented 64-bit as non-saturating is removed, so the existing
test_pack<> now holds every width to the same rule.

v_rshr_pack_u is left without a 64-bit form: it has no callers and the rounding step would need its
own decision about where the rounding happens relative to the clamp.
2026-10-06 19:36:37 +05:30
Teddy-Yangjiale
b6d7f86af4 core: use RVV segmented loads/stores for v_load_deinterleave/v_store_interleave 2026-10-06 18:33:57 +08:00
Abhishek Gola
33d76d5ade Merge pull request #30091 from abhishek-gola:core-shape-einsum
Add squeeze/unsqueeze/flatten/reshape for N-D arrays - #30091

### 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-06 12:44:51 +03:00
Alexander Smorkalov
b202aba69c Merge pull request #30133 from uwezkhan:sparse-index-bound
core: bound the sparse matrix element index in FileStorage read 🤖🤖🤖
2026-10-06 11:45:11 +03:00
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
Uwez Khan
8fd8b0c945 use theRNG() in the sparse matrix round-trip test 2026-10-05 13:53:58 +05:30
NIKHIL
6dfd7395d0 core(persistence): emit valid JSON string escapes 2026-10-04 03:38:30 +05:30
Uwez Khan
4dcc0481f6 bound the sparse matrix element index in FileStorage read 2026-10-02 18:55:19 +05:30
Abhishek Gola
20e367198c Merge pull request #30081 from abhishek-gola:core-nd-data-movement
core: unified N-D data-movement engine - #30081

closes: https://github.com/opencv/opencv/issues/29315 

### 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-02 16:20:57 +03:00
Vincent Rabaud
bd4c7bdcf8 Merge pull request #30117 from vrabaud:kmeans
kmeans: handle NaN and huge input values without crashing/OOB - #30117

kmeans: handle NaN and huge input values without crashing/OOB

When input data contains NaN or values large enough for squared L2 distances to overflow float (Inf), distance comparisons fail and can leave bestCenter or farthest_i as -1 (causing out-of-bounds memory access) or leave clusters empty (triggering CV_Assert(counters[k] != 0)).

Bail out early on the first iteration when non-finite distances are detected in generateCentersPP or KMeansDistanceComputer, zero-initialize the output labels and centers, and return -1.0 for compactness.

### 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-02 13:18:18 +03:00
Jaivardhan Bhola
193f8c4c5d Merge pull request #29618 from jaivardhan-bhola:vlm-ocr-support-engine-new
Added support for Granite Docling 258M and PaddleOCR-VL - #29618

Adds `com.microsoft::GroupQueryAttention` to the engine-new ONNX importer, required by GraniteDocling-258M's ,end-to-end samples for GraniteDocling-258M and PaddleOCR-VL-1.5. Verified on Linux x86_64 / GCC / CPU

**companion opencv_extra PR** [Vlm ocr support engine new opencv/opencv_extra#1412](https://github.com/opencv/opencv_extra/pull/1412) for test data


upstream/5.x already lowers `GroupQueryAttention` to `AttentionOnnxAi`, but that path rejects `do_rotary=1`:

```cpp
CV_CheckEQ(params.get<int>("do_rotary", 0), 0, "GroupQueryAttention: do_rotary=1 is not supported");
```

GraniteDocling-258M's export sets it. Confirmed two ways: building a Llama checkpoint from its published `text_config` (9 heads / 3 KV heads, `rope_theta=100000`) and running onnxruntime-genai's `model_builder`; and reading the community export at `onnx-community/granite-docling-258M-ONNX`, which carries 30 `GroupQueryAttention` nodes with `do_rotary=1`, `num_heads=9`, `kv_num_heads=3`, `head_dim=64`.


## Changes

**Importer** (`onnx_importer2.cpp`, +49)

Routing as above, plus the input validation the op needs: packed QKV rejected, past_key / past_value required as a pair, `do_rotary=1` requires cos/sin, unsupported trailing inputs rejected, and `seqlens_k` shorter than the buffer recognised as a shared-buffer export rather than silently mis-attended.

**Layer** (`group_query_attention_layer.cpp`, +380)

Attention is built on `fastGemmBatch` and `fused_softmax_softcap_mask`, the same kernels `attention_onnxai_layer.cpp` uses. Grouping falls out of the batched-GEMM offset table (query head → `h / groupSize`), so no broadcast copy is needed, and the second GEMM writes straight into the `[B, S, num_heads*D]` output. Supports rotary (full and partial), sliding window, softcap, growing and preallocated caches, and optional `present_*` outputs.

**Core** (`persistence_json.cpp`, +92)

`\uXXXX` escapes are UTF-16 code units, so anything above the BMP arrives as a surrogate pair. These were encoded as two separate 3-byte sequences CESU-8, which is not valid UTF-8 - for keys and values alike. Now recombined into one 4-byte sequence, with unpaired surrogates rejected.


**Tests / perf / samples**

`test_layer_group_query_attention.cpp` (+93), `test_tokenizer.cpp` (+28), `test_tokenizer.py` (+42), `perf_layer.cpp` (+125: `Layer_GroupQueryAttention` MHA_ShortCache and Grouped_WithCache, plus `Layer_Sign`), and two samples (`granite_docling_inference.py`, `paddleocr_vl_inference.py`).


### 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-01 18:03:55 +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
pbkx
1bb302e477 fix OutputArray release for std::array<Mat> 2026-09-30 09:55:04 -07:00
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
omrope79
f01a66d18f Merge pull request #29963 from omrope79:linear-assignment
Add cv::linearAssignment() rectangular assignment solver - #29963

Adds `cv::linearAssignment()` to `modules/core`, next to `solveLP`: a Jonker-Volgenant solver that pairs the rows of a cost matrix with its columns at the lowest total cost. It pairs existing tracks with new detections in a tracking pipeline.

`costThreshold` is applied during the solve, so a pair that is too expensive is forbidden and a pair is only made when it beats the price of leaving it unmade. Implemented from Crouse 2016, cited in the doxygen. 

Accuracy and performance tests are included and need no new test data.

### 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 17:06:55 +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
Teddy-Yangjiale
95e8141250 Merge pull request #30069 from Teddy-Yangjiale:rvv-f64-arithm
core: enable CV_64F arithmetic SIMD kernels for scalable SIMD - #30069

### Summary

The CV_64F element-wise arithmetic kernels in `modules/core/src/arithm.simd.hpp` are guarded by `CV_SIMD_64F`, which is 0 on scalable-vector (RVV) builds, while the kernels themselves are already written with width-independent universal intrinsics (`v_float64`, `vx_load`, `VTraits<>::vlanes()`). On RVV every CV_64F arithmetic operation therefore falls back to the scalar kernels even though `CV_SIMD_SCALABLE_64F` is 1 and `v_float64` is fully supported.

The same file already uses the dual guard `CV_SIMD_64F || CV_SIMD_SCALABLE_64F` in four other places (see the comment at L166: "scalable (RVV) has v_float64 without CV_SIMD_64F"), so the 12 remaining single-guard sites look like an oversight. This PR widens them.

### What becomes vectorized on RVV (VLEN=256 => 4 double lanes)

- `cv::add` / `cv::subtract` (CV_64F)
- `cv::multiply` (CV_64F, plus the 32U/32S f64-work-type kernels)
- `cv::divide` (DIVW group: 32U/32S/64U/64S/64F)
- `cv::min` / `cv::max` (CV_64F)
- `cv::absdiff` (CV_64F)
- `cv::compare` (CV_64F)
- `cv::addWeighted` (AWD group: 32U/32S/64U/64S/64F)

All affected kernels are element-wise with no cross-lane reductions, so results are identical to the scalar kernels (per-element IEEE operations). The only theoretical difference is that the addWeighted vector body uses fused `v_fma` while the scalar tail does separate mul+add (at most 1 ulp); the same code already passes x86 AVX2/AVX512 CI where FMA is used as well.

On fixed-width backends (x86, AArch64, LoongArch, MIPS MSA, Power VSX) `CV_SIMD_64F` is already 1, so the guard change compiles to exactly the same code as before — no impact on other architectures. ARMv7/AArch32 and WASM SIMD128 have no f64 vector type at all (`CV_SIMD128_64F=0` by design) and keep the scalar path unchanged.

### Scope

Generic `rv64gc + CPU_DISPATCH=RVV` builds do not benefit yet (`arithm` is not a dispatched file); the win applies to builds where the core library itself is compiled with RVV enabled (`CPU_BASELINE=RVV`, the common embedded configuration on SpacemiT K1/K3 boards).

### Build configuration

Cross-compiled for SpacemiT K1 (8x 1.6 GHz, RVV 1.0, VLEN=256), GCC 14.2.1, `-O3`, both sides built with identical flags:

```bash
cmake -GNinja -DCMAKE_TOOLCHAIN_FILE=riscv64-spacemit-k1.toolchain.cmake \
      -DCMAKE_BUILD_TYPE=Release -DCPU_BASELINE=RVV -DCPU_DISPATCH= \
      -DBUILD_LIST=core,ts,calib,geometry -DBUILD_TESTS=ON -DBUILD_PERF_TESTS=ON \
      -DWITH_LAPACK=OFF -DWITH_EIGEN=OFF -DWITH_OPENCL=OFF \
      -DWITH_TIFF=OFF -DWITH_OPENJPEG=OFF -DWITH_JASPER=OFF -DWITH_OPENEXR=OFF \
      -DWITH_GDAL=OFF -DWITH_GDCM=OFF -DWITH_AVIF=OFF -DWITH_JPEGXL=OFF -DWITH_IMGCODEC_GIF=OFF ..

ninja opencv_core opencv_test_core opencv_perf_core opencv_test_calib opencv_test_geometry
```


### Correctness validation (on board)

```bash
export OPENCV_TEST_DATA_PATH=.../opencv_extra/testdata
export OPENCV_OPENCL_RUNTIME=disabled
./bin/opencv_test_core     --test_threads=4
./bin/opencv_test_calib    --test_threads=4
./bin/opencv_test_geometry --test_threads=4
```

| suite | baseline | with this PR |
|---|---|---|
| `opencv_test_core` (16757 tests) | 16756 pass, 1 fail: `Samples.findFile` (missing samples data path, environment) | **identical failure set** |
| `opencv_test_calib` (34 tests) | 34/34 pass | 34/34 pass |
| `opencv_test_geometry` (323 tests) | 323/323 pass | 323/323 pass |

Zero new failures; the arithm accuracy suites (`Core_*ElemWiseTest`, `Core_AddWeighted*`, `Core_*Mixed/ArithmMixedTest`, compare) exercise the newly vectorized kernels at all depths and pass unchanged.

### Performance (SpacemiT K1, single-threaded)

This PR adds a CV_64F perf fixture (`F64ArithmTest`: 9 ops x 4 sizes x CV_64FC1 = 36 cases) to `modules/core/perf/perf_arithm.cpp`, since the existing `BinaryOpTest` fixture does not parametrize CV_64F (and has no `compare`/`addWeighted` cases at all). Numbers below are per-case minima over 4 alternating A/B rounds x 50 samples, reported with the standard `modules/ts/misc/summary.py` (`-m min`).

With the default build flags (`-O3`, GCC 14.2.1):

```
Min (ms)

                 Name of Test                   base   cand     cand
                                                min4   min4     min4
                                                                 vs
                                                                base
                                                                min4
                                                             (x-factor)
absdiff::F64ArithmTest::(127x61, 64FC1)        0.035  0.026     1.33
absdiff::F64ArithmTest::(640x480, 64FC1)       1.580  1.644     0.96
absdiff::F64ArithmTest::(1280x720, 64FC1)      4.533  5.049     0.90
absdiff::F64ArithmTest::(1920x1080, 64FC1)     10.059 10.936    0.92
add::F64ArithmTest::(127x61, 64FC1)            0.027  0.028     0.98
add::F64ArithmTest::(640x480, 64FC1)           1.529  1.561     0.98
add::F64ArithmTest::(1280x720, 64FC1)          4.560  4.450     1.02
add::F64ArithmTest::(1920x1080, 64FC1)         9.544  9.549     1.00
addWeighted::F64ArithmTest::(127x61, 64FC1)    0.033  0.028     1.14
addWeighted::F64ArithmTest::(640x480, 64FC1)   1.582  1.581     1.00
addWeighted::F64ArithmTest::(1280x720, 64FC1)  4.579  4.797     0.95
addWeighted::F64ArithmTest::(1920x1080, 64FC1) 10.255 9.885     1.04
compare::F64ArithmTest::(127x61, 64FC1)        0.099  0.035     2.85
compare::F64ArithmTest::(640x480, 64FC1)       3.834  1.300     2.95
compare::F64ArithmTest::(1280x720, 64FC1)      11.456 3.847     2.98
compare::F64ArithmTest::(1920x1080, 64FC1)     25.670 8.738     2.94
divide::F64ArithmTest::(127x61, 64FC1)         0.064  0.065     0.98
divide::F64ArithmTest::(640x480, 64FC1)        2.493  2.352     1.06
divide::F64ArithmTest::(1280x720, 64FC1)       7.359  7.192     1.02
divide::F64ArithmTest::(1920x1080, 64FC1)      16.306 15.548    1.05
max::F64ArithmTest::(127x61, 64FC1)            0.029  0.026     1.12
max::F64ArithmTest::(640x480, 64FC1)           1.583  1.600     0.99
max::F64ArithmTest::(1280x720, 64FC1)          4.746  4.963     0.96
max::F64ArithmTest::(1920x1080, 64FC1)         9.827  10.143    0.97
min::F64ArithmTest::(127x61, 64FC1)            0.029  0.026     1.10
min::F64ArithmTest::(640x480, 64FC1)           1.625  1.630     1.00
min::F64ArithmTest::(1280x720, 64FC1)          4.821  5.000     0.96
min::F64ArithmTest::(1920x1080, 64FC1)         9.363  11.126    0.84
multiply::F64ArithmTest::(127x61, 64FC1)       0.029  0.027     1.10
multiply::F64ArithmTest::(640x480, 64FC1)      1.680  1.762     0.95
multiply::F64ArithmTest::(1280x720, 64FC1)     4.835  4.929     0.98
multiply::F64ArithmTest::(1920x1080, 64FC1)    10.427 10.564    0.99
subtract::F64ArithmTest::(127x61, 64FC1)       0.027  0.026     1.06
subtract::F64ArithmTest::(640x480, 64FC1)      1.605  1.660     0.97
subtract::F64ArithmTest::(1280x720, 64FC1)     4.758  5.016     0.95
subtract::F64ArithmTest::(1920x1080, 64FC1)    11.156 10.594    1.05
```

x-factor geomean **1.13x**. `compare` is a robust ~2.9x; most other ops land near parity because GCC already auto-vectorizes the simple scalar f64 loops at `-O3` on RVV (exactly the issue #30066 works around with `-fno-tree-vectorize`). Per-case values near parity swing with the known K1 bimodal timing behavior.

With `-fno-tree-vectorize` added to the build flags (the direction proposed in #30066 for RVV), the same A/B shows the kernel-level gains directly:

```
Min (ms)

                 Name of Test                    nt     nt       nt
                                                base   cand     cand
                                                min4   min4     min4
                                                                 vs
                                                                 nt
                                                                base
                                                                min4
                                                             (x-factor)
absdiff::F64ArithmTest::(127x61, 64FC1)        0.087  0.026     3.41
absdiff::F64ArithmTest::(640x480, 64FC1)       3.351  1.423     2.36
absdiff::F64ArithmTest::(1280x720, 64FC1)      10.189 4.595     2.22
absdiff::F64ArithmTest::(1920x1080, 64FC1)     22.476 10.094    2.23
add::F64ArithmTest::(127x61, 64FC1)            0.037  0.027     1.35
add::F64ArithmTest::(640x480, 64FC1)           1.538  1.446     1.06
add::F64ArithmTest::(1280x720, 64FC1)          4.644  4.403     1.05
add::F64ArithmTest::(1920x1080, 64FC1)         10.316 9.629     1.07
addWeighted::F64ArithmTest::(127x61, 64FC1)    0.076  0.027     2.81
addWeighted::F64ArithmTest::(640x480, 64FC1)   2.978  1.363     2.18
addWeighted::F64ArithmTest::(1280x720, 64FC1)  9.141  4.118     2.22
addWeighted::F64ArithmTest::(1920x1080, 64FC1) 19.856 9.075     2.19
compare::F64ArithmTest::(127x61, 64FC1)        0.103  0.031     3.31
compare::F64ArithmTest::(640x480, 64FC1)       3.993  1.225     3.26
compare::F64ArithmTest::(1280x720, 64FC1)      11.801 3.596     3.28
compare::F64ArithmTest::(1920x1080, 64FC1)     26.611 8.125     3.28
divide::F64ArithmTest::(127x61, 64FC1)         0.156  0.065     2.41
divide::F64ArithmTest::(640x480, 64FC1)        6.095  2.330     2.62
divide::F64ArithmTest::(1280x720, 64FC1)       18.191 6.880     2.64
divide::F64ArithmTest::(1920x1080, 64FC1)      40.743 15.331    2.66
max::F64ArithmTest::(127x61, 64FC1)            0.085  0.025     3.36
max::F64ArithmTest::(640x480, 64FC1)           3.272  1.428     2.29
max::F64ArithmTest::(1280x720, 64FC1)          10.009 4.581     2.18
max::F64ArithmTest::(1920x1080, 64FC1)         21.962 10.130    2.17
min::F64ArithmTest::(127x61, 64FC1)            0.086  0.025     3.40
min::F64ArithmTest::(640x480, 64FC1)           3.316  1.417     2.34
min::F64ArithmTest::(1280x720, 64FC1)          10.133 4.583     2.21
min::F64ArithmTest::(1920x1080, 64FC1)         22.334 10.160    2.20
multiply::F64ArithmTest::(127x61, 64FC1)       0.062  0.024     2.61
multiply::F64ArithmTest::(640x480, 64FC1)      2.430  1.362     1.78
multiply::F64ArithmTest::(1280x720, 64FC1)     7.427  4.344     1.71
multiply::F64ArithmTest::(1920x1080, 64FC1)    16.160 9.370     1.72
subtract::F64ArithmTest::(127x61, 64FC1)       0.038  0.025     1.48
subtract::F64ArithmTest::(640x480, 64FC1)      1.696  1.523     1.11
subtract::F64ArithmTest::(1280x720, 64FC1)     4.794  4.805     1.00
subtract::F64ArithmTest::(1920x1080, 64FC1)    12.058 10.820    1.11
```

x-factor geomean **2.09x** (36 cases, 1.00-3.41x): compare ~3.3x, divide ~2.6x, min/max ~2.2x, absdiff ~2.2x, addWeighted ~2.2x, multiply ~1.7-2.6x. `add`/`subtract` stay near parity in both regimes — they appear to be served by a different (already-vectorized) path before the kernel table is consulted.



### 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-09-29 08:31:04 +03:00
Ziyuan_Li
912e6863df Merge pull request #30075 from ziyuanLi-alex:rvv-transpose2d
core: RVV HAL transpose2d for 3-channel element sizes - #30075

### Summary

`cv::transpose` for 3-channel types (`8UC3`/`8SC3`, `16UC3`/`16SC3`/`16FC3`, `32SC3`/`32FC3`) falls back to the scalar core path on RISC-V. The RVV HAL `transpose2d` dispatches on *element size* and only implements `esz ∈ {1, 2, 4, 8}`. This PR adds kernels for
`esz = 3, 6, 12`, and an accuracy test that covers the new paths including non-continuous ROI.

### Root cause

- `hal/riscv-rvv/src/core/transpose.cpp`: the `Transpose2dFunc tab[]` table has entries only at indices 1/2/4/8, so `cv_hal_transpose2d` returns `CV_HAL_ERROR_NOT_IMPLEMENTED` for every 3-channel type and the caller runs the generic path.
- On the scalable RVV backend (`intrin_rvv_scalable.hpp`) `CV_SIMD128` is never defined, so the existing `transpose_8/16/32/48bit_simd` fast paths `modules/core/src/matrix_transform.cpp` are compiled out entirely; what runs is the scalar 4x4 element loop. 8UC3 (the default color type) is the most visible case.

### Implementation

The new kernels deinterleave the three channels of several source rows with `vlseg3e{L}` and emit the transposed rows with strided segment stores (`vssseg{6,8}e{L}`). The number of source rows per block was picked experimentally: 8 rows for 8-bit lanes, 2 rows for 16/32-bit lanes. For 16/32-bit lanes, taller blocks e.g. 8 rows will add register pressure and cause regression. A one-row tail covers the remainder; unaligned 16/32-bit inputs fall back to the generic path.

### Performance

SpacemiT K1 / X60, OpenCV 5.x, `--perf_force_samples=20
--perf_min_samples=20`, `BinaryOpTest.transpose2d`:

| type (esz) | 640x480 | 1280x720 | 1920x1080 |
|---|---:|---:|---:|
| `CV_8UC3` (3)  | 2.758 -> 1.648 ms (**1.67x**) | 16.772 -> 10.575 ms (**1.59x**) | 42.901 -> 39.552 ms (1.09x) |
| `CV_16SC3` (6) | 8.384 -> 3.556 ms (**2.36x**) | 31.112 -> 19.450 ms (**1.60x**) | 71.921 -> 62.460 ms (1.15x) |

Untouched element sizes (esz 1/2/4/8, 16 cases at 640x480 + 1280x720): geomean **1.005x**,
range 0.977x ... 1.058x.


### Accuracy

New test `Core_Transpose.C3ElementSizesWithRoi` (`modules/core/test/test_mat.cpp`) sweeps
`CV_8UC3, CV_8UC(6), CV_16SC3, CV_16FC3, CV_8UC(12), CV_32FC3` over sizes `1x1, 2x3, 137x5, 133x4` through non-continuous ROI views, byte-compares every element against the source, and asserts the bytes outside the destination ROI are untouched. On K1:

```
[  PASSED  ] 4 tests.   # Core_Transpose.C3ElementSizesWithRoi
                        # Core_Transpose/ElemWiseTest.accuracy/0
                        # Core_Rotate/ElemWiseTest.accuracy/0
```

`BinaryOpTest.transpose2d` already provides the performance coverage; no `opencv_extra` data is needed.


### 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
- [ ] 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 08:29:36 +03:00
Alexander Smorkalov
8e10da8b2d Fixed accuracy issue in reduce_sum with RISC-V RVV. 2026-09-28 16:39:17 +03:00
Alexander Smorkalov
ef20307d84 Merge pull request #30071 from pranayr710:feat/hal-v-select-64bit
core: hal: add v_select for the 64-bit integer lanes
2026-09-28 09:49:03 +03:00
Abhishek Gola
f34951afc4 Merge pull request #29844 from abhishek-gola:fix-avxvnni-assembler-check
Verify assembler can encode AVX-VNNI before enabling it - #29844

Closes: https://github.com/opencv/opencv/issues/29840

### 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-28 08:35:16 +03:00