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.
- The CV_Bool NOT kernel now computes x == 0 instead of x ^ 1, so a
non-0/1 byte (still true, as in convertTo) becomes 0 instead of 254.
The cvtest::logicOp reference does the same.
- bitwise_not no longer tries OpenCL for CV_Bool. It already ended up
on the CPU kernel, but only because memopTypeToStr() asserts on
CV_Bool and CV_OCL_RUN catches the exception.
- Core_Bitwise.not_bool also checks a UMat input and 255 bytes in both
the SIMD loop and the scalar tail.
The NOT kernel was picked by element size only, so CV_Bool ran the
same ~x kernel as CV_8U and turned 0/1 into 255/254. Both are non-zero,
so every element of ~mask counted as true. Pass the depth to
getNotFunc and use x ^ 1 for CV_Bool. Fix the same ~x in the
cvtest::logicOp reference, which made Core_Not expect 254.
Add a Core_Bitwise regression test.
java: fix Mat get/put JNI for 0D/1D/ND Mats in OpenCV 5 - #29851#29851
## Summary
Fix incorrect behavior of Java `Mat.get()` / `Mat.put()` JNI bindings for
0D (scalar), 1D, and ND `cv::Mat` objects.
The Java JNI layer in `modules/java/generator/src/cpp/Mat.cpp` still assumed
essentially 2D row/col indexing in several get/put code paths. This caused
wrong results or failed access for scalar and 1D Mats, and incorrect bounds
handling for ND Mats accessed via index arrays.
This PR updates the native get/put helpers in `Mat.cpp` and adds regression
tests in `modules/core/misc/java/test/MatTest.java`.
## Problem (before this patch)
### 1. 0D (scalar) Mats
- `Mat::ptr(const int*)` requires `dims >= 1`, so idx-based paths that called
`m->ptr(idx.data())` directly (e.g. `nGetIdx`, `mat_copy_data`, `PUT_ITEM_IDX`)
could not access a true 0D Mat correctly.
- `idx2Offset()` always read `indices[0]` without checking `dims <= 0`.
- Row/col helpers always built a 2-element index `{row, col}` instead of an
empty index vector for 0D Mats.
Although OpenCV 5 supports 0D Mats at the C++ level, the Java wrapper did not
correctly implement idx-based access with an empty index array (`new int[]{}`).
This PR adds explicit JNI support for that case via `mat_elem_ptr()` and
related helpers.
**Example:** For `Mat m = new Mat(new int[]{}, CvType.CV_64F)` (`dims()==0`),
`m.put(new int[]{}, 42.0)` and `m.get(new int[]{}, buf)` could fail or access
the wrong memory.
### 2. 1D Mats (`dims() == 1`)
- Row/col get/put always converted `(row, col)` to `{row, col}` (length 2),
while a 1D Mat requires a single-element index vector.
- For a 1D Mat, OpenCV 5 represents the shape as `dims == rows == 1` and
`cols == total() == N`. The Java row/col access path must therefore interpret
`(row, col)` as the 1D element index represented by `col` (with `row == 0`),
converting internally to `{col}` via `row_col_to_idx()`.
**Example:** For `Mat m = new Mat(new int[]{10}, CvType.CV_32F)`, calling
`m.put(0, 3, values)` could behave incorrectly because native code treated
the access as `{0, 3}` instead of `{3}`.
### 3. ND Mats (`dims() > 2`) via row/col API
- Row/col get/put only checked `rows` and `cols`, without rejecting Mats with
`dims > 2`.
- ND Mats must be accessed via idx-based APIs; using row/col on them could
produce silently wrong results instead of failing early.
### 4. Idx-based API bounds checking
- Old code checked `size[i] <= idx[i]` but did not validate:
- `idx.length == dims`
- negative index values
- `nPutDIdx` computed the number of remaining elements with a per-dimension
product loop (`channels * (size[i] - idx[i]) * ...`). For ND Mats, this did
not correctly account for the current linear index position when determining
how many elements remain from the selected subarray onward. The fix uses
`(total() - idx2Offset(m, idx)) * channels()`, which matches the linear
layout used by `mat_copy_data()`.
## Changes
- Add `mat_elem_ptr()` to support 0D scalar Mats (`Mat::ptr(const int*)`
requires `dims >= 1`).
- Add `check_row_col_access()`, `check_idx_access()`, and `row_col_to_idx()`
to validate access and convert row/col indices according to OpenCV semantics.
- Update `idx2Offset()`, `offset2Idx()`, and `mat_copy_data()` for 0D/1D Mats.
- Route row/col get/put through `row_col_to_idx()` (1D: element index in `col`,
`row == 0`).
- Restrict row/col APIs to Mats with `dims <= 2`; ND Mats must use idx-based
APIs (`nGet*Idx`, `nPut*Idx`, `nGetIdx`, `nPutDIdx`).
- Fix remaining-element calculation in `nPutDIdx` to use `idx2Offset()`.
## Behavior notes
| API | 0D Mat (`dims==0`) | 1D Mat (`dims==1`) | 2D Mat | ND Mat (`dims>2`) |
|-----|-------------------|-------------------|--------|-------------------|
| `get/put(int[] idx, ...)` | supported (`idx.length == 0`; added by this PR) | supported (`idx.length == 1`) | supported | supported |
| `get/put(row, col, ...)` | supported (`row=0`, `col=0`) | supported (index in `col`, `row=0`) | supported | rejected at JNI layer return 0; |
| `get(row, col)` | supported | supported | supported | rejected at JNI layer return 0; |
| `get(int[] idx)` | supported | supported | supported | supported |
## Test plan
Added regression tests in `MatTest.java`:
- `testGetPut0DMat` — idx and row/col get/put on a scalar Mat (`new int[]{}`)
- `testGetPut1DMat` — idx and row/col get/put on `new Mat(new int[]{5}, ...)`
- `testGetPut1DMatDoubleArray` — bulk double put/get via idx on a 1D Mat
- `testGetPut3DMat` — row/col API rejected for 3D Mat; idx API works
### 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
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
core: support fp8 depths in minMaxLoc and minMaxIdx - #30526Fixes#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
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.
Address review: like the CV_32F and CV_64F paths, compare integer keys
instead of decoding each fp8 value. CV_TOGGLE_FP8 maps the sign-magnitude
bytes to int8 keys in the same order; the key range [ia, ib) of
[minVal, maxVal) is found once from the decode table, so bounds that are
not fp8 values are still exact. NaN's key is checked separately, since
the E4M3FNUZ NaN sits between the negative values and zero.
Add a Core_CheckRange_FP8 test that checks all 256 values of both fp8
depths against minVal <= v < maxVal for several ranges.
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.
The reduceR_/reduceC_ dispatch is a chain of explicit sdepth/ddepth pairs and has
never carried a CV_8S or CV_32S source row, so cv::reduce rejected both for every
operation and both dim values. 4.x has the same gap.
CV_8S mirrors CV_8U and accumulates in int. CV_32S accumulates in double: OpAdd<int>
evaluates a + b as int before saturate_cast can clamp it, so an int accumulator
overflows. CV_32S -> CV_32S sums are left unsupported for that reason.
Extend Core_ReduceTest to the new combinations, and add cases for the 32-bit
overflow range and the signed 8-bit extremes, which its randu(0, 100) fill cannot
reach. Its support list also omitted 16U/16S REDUCE_MAX/REDUCE_MIN, which the
existing kernels already handle.
Partially addresses #30569.
checkRange had no branch for CV_8F_E4M3FN and CV_8F_E4M3FNUZ, so it
failed with "Unsupported matrix depth in checkRange". Use
checkTypedRange with fp8_t / fp8a_t, like CV_16F / CV_16BF; NaN values
are reported as out of range.
Add both fp8 depths to the Core_CheckRange_Float test, with a NaN as
the bad value since fp8 has no infinity.
core: support fp8 depths in countNonZero and hasNonZero - #30463Fixes#30461
### Problem
`countNonZeroTab` (`count_non_zero.simd.hpp`) and `hasNonZeroTab` (`has_non_zero.simd.hpp`) have `0` in the `CV_8F_E4M3FN` and `CV_8F_E4M3FNUZ` slots, so `cv::countNonZero` and `cv::hasNonZero` fail with `func != 0` for fp8 input. `cv::findNonZero` already supports both depths since #30341.
### Fix
- `CV_8F_E4M3FN`: new `countNonZero8f` / `hasNonZero8f` kernels. Same as the 8u kernels, but the sign bit is ignored so `-0.0` (`0x80`) counts as zero: the vector path reuses the `v_add_wrap(x, x)` compare of the 16f kernels, and the scalar tail uses `CHECK_NZ_FP8(x) = ((x) & 0x7f) != 0`.
- `CV_8F_E4M3FNUZ`: the existing 8u kernels. This format has no `-0`; `0x80` is its NaN and counts as non-zero, the same as in `findNonZero`.
### Tests
- `CountNonZero1D` now also runs on both fp8 depths.
- `HasNonZeroNegZeros` now also covers `CV_8F_E4M3FNC1`.
- New `CountNonZeroFP8.sign_bit`, a `TEST_P` over both fp8 depths and n = 1, 100, 1031 (scalar tail, single-vector loop, unrolled loop). It fills a `CV_32F` Mat with random values in ±[0.5, 4), sets every 5th element and the last one to `-0.0`, `NaN` or `+0.0`, converts it to fp8, and checks `countNonZero` / `hasNonZero` against the number of non-zero values set. `-0.0` becomes `0x80` in E4M3FN and must count as zero; `NaN` becomes `0x80` in E4M3FNUZ and must count as non-zero.
These fail on current 5.x (`func != 0`) and pass with this patch. All `*NonZero*` and `*FP8*` tests in `opencv_test_core` pass locally on Apple M1 (190 tests), with OpenCL enabled and with `OPENCV_OPENCL_DEVICE=disabled`.
### 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
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.
getLUTFunc had no case for CV_8F_E4M3FN and CV_8F_E4M3FNUZ tables, so
cv::LUT failed with "An unexpected type combination was specified". LUT
only copies table entries, so use the same 1-byte copy as CV_Bool for
both 8-bit and 16-bit indices.
Add both fp8 depths to the LUTAccuracyNewDstTypes test.
core: support 5.x depths in sort and sortIdx - #30506Fixes#30505
### Problem
The kernel tables of `cv::sort` and `cv::sortIdx` (`modules/core/src/matrix_operations.cpp`) only have entries for `CV_8U` to `CV_64F`, so every depth added in 5.x fails with `func != 0`.
### Fix
Both tables now use the existing `sort_<T>` / `sortIdx_<T>` templates for:
- `CV_16F` → `hfloat`, `CV_16BF` → `bfloat`, `CV_8F_E4M3FN` → `fp8_t`, `CV_8F_E4M3FNUZ` → `fp8a_t` (compared through their `float` conversion);
- `CV_Bool` → `uchar`, the same kernel as `CV_8U`;
- `CV_64U` → `uint64_t`, `CV_64S` → `int64_t`, `CV_32U` → `uint32_t`.
### Tests
- `Core/sortIdx.simple` now also runs on `CV_16U`, `CV_16F`, `CV_16BF`, `CV_Bool`, `CV_64U`, `CV_64S`, `CV_32U` and both fp8 depths (`CV_16U` was already supported but not tested), and also checks `cv::sort` against sorting a `CV_64F` copy of the same data; there was no `cv::sort` test before.
- New `Core_sort.large_integers` checks exact `sort` / `sortIdx` results for `CV_32S`, `CV_32U`, `CV_64S` and `CV_64U` with values that need the full type: `INT_MIN` / `INT_MAX`, the unsigned high bit (`0x80000000`, `UINT_MAX`, `2^63`, `UINT64_MAX`) and `2^53` vs `2^53 + 1`. With signed kernels for `CV_32U` / `CV_64U` it fails, while the random `sortIdx` test still passes.
The new cases fail on current 5.x and pass with this patch. All `sortIdx` / `sort` tests in `opencv_test_core` pass locally on Apple M1 Pro (242 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
In modules/core/src/convert.hpp, v_store_as() for 64-bit integer destinations (int64_t and uint64_t) from v_float32 rounded into a 32-bit integer (v_int32) before widening, causing values outside the 32-bit signed range (e.g. >= 2^31 in CV_16BF / CV_16F) to saturate to INT32_MIN/INT32_MAX on the SIMD path.
Use buffer-based saturate_cast<int64_t> / saturate_cast<uint64_t> to preserve the full 64-bit destination range, matching the existing precedent for v_store_pair_as(v_float64) and v_store_pair_as(unsigned, v_float32).
Add Core_ConvertTo64Int regression tests across vector and scalar lengths.
Resolves#29996.
Do not call Lapack for small operations. - #29909
This reduces the cache for GEMM in calibration: the transposed Jacobian is 6 x 2Number points while the result is 6 x 1.
The previous code was only looking at the input number of rows.
### 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
core/dnn: resolve GCC 16 -Wmaybe-uninitialized and -Warray-bounds warnings - #30308
- core(nd_copy): ensure copyBatch only executes runPlans when np > 0.
- dnn(test): add reserve(3) to input vector to quiet compiler bounds checks.
### 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
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)); \
core: accept both float->int saturation results in OCL ConvertToSaturate test - #30448
Fixes the `macOS-x64 / BuildAndTest` failure from #30386, which makes 5.x macOS-x64 CI red for every PR (e.g. #30302):
```
[ RUN ] OCL_MatrixOperation/ConvertToSaturate.Accuracy/16, where GetParam() = (CV_32F, CV_32S)
test_matrix_operation.cpp:247: Failure
cv::countNonZero(diff)
Which is: 2
```
INT_MAX isn't representable in float, so a saturated `CV_32F -> CV_32S` result can legitimately be either value:
- x86 CPU (`v_round` / `cvRound`) clamps to `CV__FLT2INT_MAX_F` = 2147483520 before converting (since #30007).
- OpenCL `convert_int_sat_rte` and NEON `vcvtnq_s32_f32` give INT_MAX = 2147483647.
So on an x86 host the out-of-range inputs `3e9` and `1e20` differ by 127 between `Mat` and `UMat`. On Apple M1 both sides give INT_MAX, which is why it only shows up on macOS-x64.
For this pair the test now clamps both results to 2147483520 before the exact comparison, i.e. it accepts any value in [2147483520, INT_MAX] as saturated. In-range values and all other depth pairs are still compared exactly.
**Testing** (Apple M1 Pro, OpenCL on; native arm64 build and an x86_64 build run under Rosetta 2)
`Mat::convertTo` vs `UMat::convertTo` for `CV_32F -> CV_32S`:
| input | arm64 CPU | x86_64 CPU | OpenCL |
|---|---|---|---|
| 3e9 | 2147483647 | 2147483520 | 2147483647 |
| 1e20 | 2147483647 | 2147483520 | 2147483647 |
The x86_64 build reproduces the CI mismatch. With this change, on both builds:
- `opencv_test_core --gtest_filter=*ConvertToSaturate*`: 135 passed.
- `opencv_test_core --gtest_filter=OCL_*:*ConvertTo*:*convertTo*:*Core_ConvertScale*`: 7549 passed.
### 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