Commit Graph

2832 Commits

Author SHA1 Message Date
Abhishek gola
315ddafc6c Fix Sphinx API targets, navigation and documentation warnings 2026-11-16 20:13:32 +05:30
Shiven Solanki
7a8d99e6b2 doc(core): note unspecified NaN handling in minMaxLoc and minMaxIdx (#30809) 2026-11-16 09:35:26 +05:30
Shiven Solanki
cc26a67b62 doc(core): fix LUT index formula for CV_8S and CV_16S inputs (#30793)
* doc(core): fix LUT index formula for CV_8S and CV_16S inputs

LUT reads CV_8S and CV_16S values as the unsigned numbers with the same bits, so negative values index the upper half of the table (-1 maps to entry 255 for CV_8S). The docs said the index was src + 128 (CV_8S) or src + 32768 (CV_16S), which is wrong for every value. Also remove a stray 'ref' in the compare docs.

* doc(core): fix LUT index rule in HAL interface docs

cv_hal_lut and cv_hal_lut16 docs still said 128 or 32768 is added to the index for 8s and 16s inputs. Use the same rule as the LUT docs: the input is read as unsigned with the same bits, and no offset is added.
2026-11-15 12:49:38 +05:30
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
Shiven Solanki
a20d208db5 doc(core): note unsupported input depths in inRange and addWeighted
inRange rejects CV_Bool and CV_8F inputs and addWeighted rejects CV_Bool inputs, but the docs did not say so. Also fix type-name typos in core.hpp (CV8S, CV_8S1) and two other spelling mistakes.
2026-11-12 07:55:35 +08:00
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
Alexander Smorkalov
07666386e2 Merge branch 'release_5.1.0' into 5.x 2026-11-05 16:14:14 +03:00
Alexander Smorkalov
e4f78fbcf1 release: OpenCV 5.1.0 2026-11-05 14:18:05 +03:00
tanveer-arch
1727c38423 Merge pull request #30072 from tanveer-arch:investigate-30067-tbb-lifetime
core: avoid TBB static destruction during Windows teardown - #30072

## Summary

Avoid destruction of the TBB task arena/scheduler during C++ static teardown.

On Windows with the UCRT and TBB backend, process teardown can involve
interaction between TBB cleanup and the Windows loader/CRT shutdown path.
Keeping the OpenCV-owned TBB arena/scheduler alive until process termination
avoids invoking its destructor during static destruction.

## Validation

- Reproduced the reported teardown deadlock with the MSYS2 packaged
  OpenCV 5.0.0 environment.
- Built OpenCV 5.x locally with TBB enabled.
- The patched local build completed 2,001 stress-test iterations without
  reproducing the deadlock.
- `git diff --check` passes.

The local 5.x baseline did not reproduce the issue during the available
baseline stress run, so the stress result is considered supporting evidence
rather than a definitive reproduction/fix confirmation.

Related issue: #30067
2026-11-05 10:26:42 +03:00
Vincent Rabaud
5bbf4b4b93 fix NaN inequality semantics in v_ne for AVX, AVX-512, LSX, and LASX
Ordered not-equal predicates (_CMP_NEQ_OQ in AVX/AVX-512 and
vfcmp_cne/xvfcmp_cne in LoongArch LSX/LASX) return false when either
operand is NaN, violating IEEE-754 != semantics and diverging from C++,
SSE (_mm_cmpneq_ps/_pd), NEON, MSA, VSX, WASM, and RVV implementations
(as well as callers like intrin_math.hpp that use v_ne(x, x) to detect
NaNs).

Switch floating-point v_ne to unordered not-equal (_CMP_NEQ_UQ and
vfcmp_cune/xvfcmp_cune) and add NaN coverage to test_cmp().
2026-11-04 10:17:08 +01:00
Abhishek Gola
f5fab22f7c Merge pull request #30626 from Prasadayus/optimize/imgproc-arm64-perf
imgproc: recover calcHist ARM64 perf regressions
2026-11-03 13:07:06 +05:30
Prasadayus
ffb4fb40f8 drop bilateralFilter early-exit restoration, no regression found 2026-11-02 18:57:13 +05:30
Prasadayus
24b3a82376 address review feedback on calcHist/bilateralFilter fixes 2026-11-02 16:35:12 +05:30
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
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
Kumataro
75c70dfc46 Merge pull request #30598 from Kumataro:doc/update_intro_for_v5_1_0
core(doc): update introduction for OpenCV 5.1 - #30598

- Remove redundant highgui and videoio modules.
- Add geometry and ptcloud modules.
- Document new 8-bit floating-point types (CV_8F_E4M3FN and CV_8F_E4M3FNUZ).

### 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.
- [x] The feature is well documented and sample code can be built with the project CMake
2026-10-30 10:10:54 +03: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
Alexander Smorkalov
54fbb6bd86 Pre-release 5.1.0 versions update 2026-10-23 14:28:38 +03:00
Sun Haiyong
330c0dbfd5 core: Add the missing <climits> include to intrin_lsx.hpp.
When compiling with GCC 16.2.0, I encountered the following error:

modules/core/include/opencv2/core/hal/intrin_forward.hpp:204:49: error: 'INT_MAX' was not declared in this scope
  204 |     SV32 sat  = v_xor(v_shr<31>(hi), SETALL_S32(INT_MAX)); \
2026-10-23 10:10:05 +08:00
Vincent Rabaud
a8584653db Fix wasm compilation
Move v_pack_trunc down after v_shr is declared. Otherwise, the error is:
error: use of undeclared identifier 'v_shr'
  474 | OPENCV_HAL_IMPL_SATURATING_PACK_64(v_int64x2, v_uint64x2, v_int32x4, v_uint32x4, v_setall_s32, v_pack_trunc, v_pack_trunc)
      | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
OpenCV/core/hal/intrin_forward.hpp:202:28: note: expanded from macro 'OPENCV_HAL_IMPL_SATURATING_PACK_64'
  202 |     SV32 hi = PACK_TRUNC_S(v_shr<32>(a), v_shr<32>(b)); \
2026-10-21 17:34:39 +02:00
Abhishek Gola
2e1e9e6f5f Merge pull request #30345 from Prasadayus/fix/neon-dotprod-overflow
core: fix int16 overflow in NEON and MSA v_dotprod_expand for int8
2026-10-20 12:40:51 +05:30
Prasadayus
0f990c5333 fix int16 overflow in MSA v_dotprod_expand for int8 2026-10-19 14:49:30 +05:30
harjoth
92fba91828 core: fix Mat vector constructor docs for 1D matrices
Mat(const std::vector<_Tp>&, bool) in 5.x creates a 1D matrix
(dims == 1, rows == 1, cols == vec.size()), not a single column.
Update the doc to match the implementation and the Mat_ overload wording.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 23:19:01 -07:00
Prasadayus
6fa897e2ee fix int16 overflow in NEON v_dotprod_expand for int8 2026-10-16 20:16:55 +05:30
A Aswanth Raj
88a3a3f240 core: Fix small-vector quaternion limits 2026-10-16 08:16:14 +05:30
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
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
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
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
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
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
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
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
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
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
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