mirror of
https://github.com/opencv/opencv.git
synced 2026-11-16 06:17:53 -06:00
cd3dc424fbec0e1bc54bf58cd8a2385d09065be6
172 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
e552fd3c2d | Updated test data for division to satisfy armv7a. | ||
|
|
781f49134b |
Merge pull request #30430 from sshivensolanki/opt-findnonzero-simd
core: SIMD fast path for findNonZero on 8-bit inputs |
||
|
|
4943b4d65a | core: simplify findNonZero accuracy test | ||
|
|
155f4e18fd | core: SIMD fast path for findNonZero on 8-bit inputs | ||
|
|
afa5b1b5f3 |
core: saturate cv::absdiff on CV_64S instead of letting it return a negative
getAbsdiffFunc_() documents that a signed depth has two outputs: R == T, the saturating |a-b| kept
in the signed range, which is the depth cv::absdiff returns; and R == the unsigned type of the same
width. CV_8S, CV_16S and CV_32S each have both. CV_64S only had the unsigned one, so the signed
form fell through to a path that wraps:
absdiff(INT64_MIN, 0) -> -9223372036854775808
absdiff(INT64_MIN, INT64_MAX) -> -1
at every length, scalar included, in a CV_64S destination. The narrower depths all saturate at
their maximum: absdiff(INT_MIN, INT_MAX) on CV_32S is INT_MAX.
The missing row now uses EwAbsdiffS, whose scalar step gains a 64-bit overload. The generic one
widens into the work type, which the narrower depths have (short, int, int64_t) and 64-bit does not,
and |INT64_MIN - b| does not fit in int64_t anyway. The difference is therefore taken in uint64,
which is exact for every pair, and clamped to INT64_MAX. The narrower depths reach that overload
only through their int64 work type, where |a - b| is at most 2^32 and the clamp is a no-op.
Core_AbsdiffSigned checks both properties - never negative, and saturating at the depth's maximum -
across CV_8S, CV_16S, CV_32S and CV_64S.
|
||
|
|
56d8dcb149 |
Merge pull request #30206 from pranayr710/fix/convert-64u-signed
core: stop convertTo() treating CV_64U as signed |
||
|
|
22d61d85da |
Merge pull request #30341 from sshivensolanki:fix-findnonzero-fp8
core: fix findNonZero for fp8 depths |
||
|
|
32b8669583 |
core: stop convertTo() treating CV_64U as signed
CV_64U is the only unsigned depth whose range does not fit in the signed type of the same width, so reading its bit pattern as signed goes unnoticed until the top bit is set. Three places did. 1. CV_64U -> CV_64S dispatched to cvt64s, a raw byte copy, so nothing saturated: 2^63 became INT64_MIN and UINT64_MAX became -1, at every length. CV_32U -> CV_32S saturates, so this is now a saturating conversion like the rest. 2. vx_load_pair_as(const uint64_t*, v_float64&, v_float64&) and vx_load_as(const uint64_t*, v_float32&) both converted with v_cvt_f64(), which takes signed lanes, so CV_64U to CV_64F, CV_32F, CV_16F and CV_16BF returned negative values above INT64_MAX. Vector body only, so the same value was right at length 1 and wrong at length 16. The unsigned conversion splits into two halves below 2^32: each converts exactly, scaling the high half by 2^32 is exact, and the single add is the only rounding, so the result matches (double)x. Converting the bit pattern as signed and adding 2^64 back would round twice - for 2^63 + 1025 that gives 2^63 where (double)x is 2^63 + 2048. Core_ConvertFrom64U covers the integer and floating-point destinations, with 2^63 + 1025 among the values since it is the case that distinguishes one rounding from two. |
||
|
|
b1a94cda72 | core: fix findNonZero for fp8 depths | ||
|
|
f365611686 | core: report the unsupported type in cv::sum error message | ||
|
|
ec1ee5a5fb |
Merge pull request #30199 from pranayr710:fix/convert-32u-signed-and-precision
core: fix convertTo() from CV_32U returning negative values for CV_16BF and losing precision for CV_64F - #30199 Fixes #30198. Two entries in the `32u` block of `convert.simd.hpp` pick the wrong type. Both make `convertTo()` from `CV_32U` return something an unsigned source cannot produce, and both are one-line changes. ### 1. `CV_32U -> CV_16BF` declared its source as `int` ```cpp DEF_CVT_FUNC(32u16bf, cvt1_, int, bfloat, v_float32) ``` Every other entry in the block says `unsigned`, including the neighbouring `CV_32U -> CV_16F`, which is correct. So everything above `INT_MAX` was read as negative - `UINT_MAX` converted to `-1`, `3000000000` to `-1291845600`. This one is wrong at **every length, scalar path included**, because the type is wrong at the declaration rather than in the vector code. ### 2. `CV_32U -> CV_64F` widened through `float` ```cpp DEF_CVT_FUNC(32u64f, cvt_, unsigned, double, v_float32) ``` `float` has a 24-bit mantissa and cannot hold a `uint32`, so values above 2^24 were rounded on the way to a destination that represents all of them exactly: `16777217` came back as `16777216`, `UINT_MAX` as `4294967296`. Only the vector body was affected, so the same value was correct at length 8 and wrong at length 16. `CV_32U` was the only integer depth converting to `CV_64F` through `float` - `8U`, `8S`, `16U`, `16S` and `32S` go via `v_int32`, `64U` and `64S` via `v_float64`. It now uses the exact 64-bit path like the rest. ### One thing that needed care `vx_load_pair_as(const unsigned*, v_float64&, v_float64&)` backed that exact path with a scalar spill through a buffer, so simply switching to it would have traded precision for speed - which is not a trade worth offering. It now widens to 64 bits and uses the existing signed conversion, exact because every `uint32` is a non-negative `int64`, and stays vectorized: ```cpp v_uint64 lo, hi; v_expand(vx_load(ptr), lo, hi); a = v_cvt_f64(v_reinterpret_as_s64(lo)); b = v_cvt_f64(v_reinterpret_as_s64(hi)); ``` No new HAL primitive is needed - `v_cvt_f64(v_int64)` exists on every backend. ### How these were found A length-independence sweep over the element-wise operations: 2688 combinations of depth, boundary value and length, checking that an element's result never depends on how many elements sit beside it. Worth recording that the sweep's first output was misleading. It reported `add`, `absdiff` and `multiply` on `CV_32U` as broken, because it compared results via `convertTo(CV_64F)` - which is defect 2. Reading the raw `uint32` lanes instead showed all three are exact, and that the readback was the bug. I would have filed three imaginary bugs by trusting the first run. ### Testing `Core_ConvertFrom32U` asserts that no conversion from `CV_32U` is ever negative, and that `CV_64F` - the only destination here that can represent every `uint32` - is exact. Lengths straddle the vector width so the body, the tail and the two together are covered. Checked it fails without the patch rather than assuming: **36 of its 224 cases fail** on current 5.x with only the test applied. With the patch: 228/228 on `*ConvertTo*` and `*ConvertFrom32U*` at both the default dispatch and `OPENCV_CPU_DISABLE=AVX2,AVX,FP16`. Full `opencv_test_core` 17185 passed, with only the 7 filestorage/globbing failures this machine always has. ### Note on overlap #30178 also touches `convert.hpp` and `test_arithm.cpp`, but in the other direction (16-bit float sources into wide integer destinations) and in different regions of both files, so there is no functional overlap - only a possible textual conflict in the test file, which I am happy to rebase around. ### Pull Request Readiness Checklist - [x] I agree to contribute to the project under Apache 2 License. - [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV - [x] The PR is proposed to the proper branch - [x] There is a reference to the original bug report and related work - [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable - [x] The feature is well documented and sample code can be built with the project CMake |
||
|
|
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 |
||
|
|
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. |
||
|
|
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 |
||
|
|
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 |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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.
|
||
|
|
0f0b88d926 |
Merge pull request #29965 from pranayr710/fix/convert-64bit-saturation
core: saturate when narrowing 64-bit and 32U sources in convertTo |
||
|
|
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 |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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 |
||
|
|
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 |
||
|
|
551dbcac54 |
Merge pull request #29948 from vrabaud:comma_initializer
Remove deprecated CommaInitializer API - #29948 This goes hand in hand with https://github.com/opencv/opencv_contrib/pull/4217 ### Pull Request Readiness Checklist See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request - [x] I agree to contribute to the project under Apache 2 License. - [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV - [x] The PR is proposed to the proper branch - [x] There is a reference to the original bug report and related work - [ ] There is accuracy test, performance test and test data in opencv_extra repository, if applicable Patch to opencv_extra has the same branch name. - [ ] The feature is well documented and sample code can be built with the project CMake |
||
|
|
9940db5599 |
Merge pull request #29911 from sridhar-git05:fix-broadcast-zero-dimension-5x
core: handle zero-sized broadcast dimensions - #29911 ### Pull Request Readiness Checklist See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request - [x] I agree to contribute to the project under Apache 2 License. - [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV - [x] The PR is proposed to the proper branch - [x] There is a reference to the original bug report and related work - [ ] There is accuracy test, performance test and test data in opencv_extra repository, if applicable Patch to opencv_extra has the same branch name. - [ ] The feature is well documented and sample code can be built with the project CMake Port the fix from #29878 to the 5.x branch. This adds a guard for zero-sized destination matrices in cv::broadcast() and a regression test covering broadcasting from {1, 0} to {3, 0}. The relevant BroadcastTo.* tests pass locally. Related: #29878 |
||
|
|
24c45b01ab |
Merge pull request #29883 from lazerg:fix/issue-29880-addweighted-null-kernel
core: fix addWeighted null kernel crash for f64 dtype and bool inputs - #29883 Fixes #29880. `cv::addWeighted` segfaults for `CV_8U`, `CV_8S`, `CV_16U`, `CV_16S`, `CV_16F`, `CV_16BF` and `CV_32F` inputs with `dtype=CV_64F`, and for `CV_Bool` inputs with any dtype. When no direct `T -> rdepth` kernel exists, `TExpr::emitBinary()` picks a wide work type and looks the kernel up again, but for those input types only `T -> T` and `T -> f32` kernels are generated, so the second lookup returns a null function pointer too. The `addInsn()` overload that takes an already resolved kernel stores it without checking, and `runInsn()` then calls through the null pointer. Cast the operands to the work type when there is no kernel for them either, so the f64 (or f32) kernel runs on widened inputs. That is also what 4.x did, it converted the sources to the working type before computing, so an f64 destination keeps full precision instead of going through an f32 intermediate. Added the `CV_Assert` on the resolved kernel that the other emit paths already carry. ### 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`, the element-wise engine this regressed in does not exist on `4.x`) - [x] There is a reference to the original bug report and related work (#29880, regressed by #29426) - [x] There is an accuracy test (`Core_Arithm.addWeighted_dtype_29880`, 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 |
||
|
|
c818ba8a81 |
Fix min with empty matrices.
Fixes https://github.com/opencv/opencv/issues/29739 |
||
|
|
f968fb969f |
Broadcasting element-wise engine for cv::Mat (+ cv::texpr) (#29426)
* experimental new arithmetics; work-in-progress * continue working on new-gen arithmetic expressions * * improved performance of the new add on small arrays * added sub * extended tests * fixed potential bug when adding multi-channel array and a single-channel scalar * improved const handling * * added copyMask * added mul/dev (without scale so far) * * accelerated mul * addedd scale to mul and div * * done substantial refactoring; however a few more rounds of refactoring are ahead. * added min, max, absdiff, addweighted. * improved performance of the new arithmetic functions, but some of them are still slow, e.g. operations with mask have some bugs (that affect speed, not accuracy). * * further (significantly) accelerated several functions, especially on small arrays: mul, binary ops with mask * further polished the new arithmetic engine * started integration of the new element-wise arithmetic engine into core * big step forward. We now use the new engine inside cv::add, subtract, multiply, divide, absdiff, min and max. * big progress: * added bitwise operations * fixed and accelerated compare * ported regression tests to test new broadcasting behaviour of arithmetic functions * lot's of improvements in compare, divide, addWeighted! * lot's of small and big performance improvements in the new arithmetics * * some more optimizations; parsing texpr-expressions is now faster as well * port new_arithm to Linux/x86: dispatch guards, scalar-Mat compat fallback, dnn shape-contract fixes Core: - arithm.simd.hpp: CV_CPU_OPTIMIZATION_DECLARATIONS_ONLY guards (the file is included once per dispatched mode on x86), vx_load_expand instead of the 128-bit v_load_expand, VTraits::vlanes() instead of ::nlanes - arithm.cpp/precomp.hpp: compat fallback for scalar-like Mat operands (1x1, 1xcn/cnx1, 4x1 CV_64F - java/python tuples, operator-(Mat, Matx)): treated as a per-channel scalar ONLY when the shapes are not broadcast-compatible, so every valid numpy-style broadcast keeps its meaning and calls that would otherwise throw get the 4.x semantics DNN (fallout of the stricter shape semantics, found by the new engine): - dict.hpp: DictValue relied on fresh AutoBuffer having size()==fixed_size; allocate explicitly - batch_norm: weights_/bias_ are 1-D [n] now; 0/1-D forward runs on exact-shape 1-D views - net_impl2: extend the post-forward sanity check to non-temp outputs - a layer that reallocates its preallocated output tensor now fails loudly instead of silently detaching the result from the graph - LSTM/LSTM2 batchwise (layout=1): getMemoryShapes now matches what forward() writes (ONNX: Y=(batch,seq,dirs,hid), Yh/Yc=(batch,dirs,hid)); forward assembles seq-major results in a local buffer and transposes INTO the preallocated outputs in place Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * u8/s8 multiply: exact integer SIMD path on non-FP16 builds (3-10x vs 5.x) The unit-scale branch of vecBinaryKernel already supported a separate work-vector type Wvec1 (used by the ARM f16 build and by u16/s16 everywhere), but on x86 the u8/s8 same-type multiply still went through the f32 hub. Route it through v_uint16/v_int16: products of 8-bit values fit exactly (255^2 < 2^16), the saturating pack on store gives bit-exact results at half the vector traffic. Also fix a latent kernel bug this exposed: the unit-scale branch stepped by Wvec's lane count while loading/storing Wvec1 vectors. All previous Wvec1 instantiations had equal lane counts, but u8's v_uint16 has 2x the lanes of v_float32 - the pairs overlapped (50% redundant work) and the tail backoff could write VECSZ bytes past the row end. The branch now derives its step, offsets and tail condition from Wvec1 itself. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * vecBinaryKernel: constexpr Op::useScalar instead of a runtime-only scale check Every binary op functor now declares whether it consumes the scale scalar (params[0]): true only for mul and the two div variants. Ops that ignore it (add/sub/min/max/absdiff) take the fast 2-arg branch unconditionally - the 'scalar == 1' check used to fail for them (their params[0] is 0), sending them through the preproc branch, and the condition now folds at compile time. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * restore cv::hal::mul8u as a wrapper over the element-wise engine The symbol is still declared in core/hal/hal.hpp and called directly by external code (the G-API fluid backend in opencv_contrib), but its implementation went away with the old arithm kernels. Forward it to getMulFunc(CV_8U, CV_8U) - with scale==1 it lands on the new exact integer SIMD path. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * silence every new-arithm warning reported by CI (ARM64/Mac) and gcc 15 - arithm.cpp: bitwise_op_ocl and the actualScalarDepth/coerceTypes helpers are consumed only by the OpenCL paths - guard them with HAVE_OPENCL; haveScalar in cv::compare is read only inside CV_OCL_RUN - CV_UNUSED for OpenCL-less builds - arithm_expr.hpp: declare getBitwiseFunc/getNotFunc/getAddWeightedFunc next to the other per-op entry points (-Wmissing-prototypes in arithm.dispatch.cpp) - arithm.simd.hpp: define CV_SIMD_16F to 0 when FP16 SIMD is absent (-Wundef); {}-init the expandScalar staging buffers (-Wmaybe-uninitialized: they are fully written before use, but the compiler cannot prove it with runtime vector widths); rename the compare kernel's lambda parameter (-Wshadow) - arithm_expr.cpp: rename the exec tile-lambda's hot-field locals that shadowed TExpr members and outer locals (-Wshadow) - test_new_arithm_extensive.cpp: rename the name-generator lambdas' parameter shadowing the INSTANTIATE macro's own (-Wshadow), drop an unused variable Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * restore 4.x scalar semantics for the bindings' 4x1 CV_64F Scalar columns The python/java bindings materialize numbers and tuples as a 2-D 4x1 CV_64F Mat - or UMat, when the call carries UMat arguments. Three CI-reported python failures came from those pseudo-scalars reaching the engine as arrays: - absdiff(int_arr, 0): the (4,1) column is broadcast-COMPATIBLE with a 1-D array, so numpy semantics silently won - an outer-product f64 result instead of the int per-channel-scalar one; - subtract(u8 4x8x4, (40,)): same, by the rows==4 coincidence; - multiply(UMat, 2., dst=UMat): the scalar arrives as a UMAT, which the scalar detection did not recognize at all. isScalarArg now treats the exact bindings shape - 2-D 4x1 CV_64F single-channel Mat/UMat against a <=4-channel array - as a scalar UNCONDITIONALLY (a 1-D [4] array has dims==1 and still broadcasts). One exception, decided in arithm_op: when the partner is itself a tiny scalar-shaped array, both are honest data and ride the broadcast (compare(Mat 4x1, Mat 1x1) - issue #8999 - stays elementwise). Small-array discipline, this all runs per engine call: the probes read Mat/UMat fields directly (rows == 4 alone rejects almost everything, no _InputArray getter dispatch), and a UMAT scalar's 32 bytes are copied into a caller-stack buffer - no heap, no getMat mapping. Measured: no latency change on 4x4/16x16 element-wise calls. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * cv::texpr: std::string_view -> const std::string& in the public API string_view in an exported signature breaks some CUDA toolchain builds, and for short expression strings the difference is immaterial (SSO, parsed once). The parser internals keep string_view - the argument converts implicitly. Also drop the now-unused <string_view> include from cvstd.hpp, so the header does not reach every nvcc TU. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * compare boundary-rewrite: fixed 4-slot kind/bound arrays instead of AutoBuffers A CONST operand is capped at 4 channels (addConst), so the per-channel kind/bound staging needs no dynamic buffers - plain int[4]/double[4], with a CV_Assert on the contract. This is also what gcc's -Wmaybe-uninitialized was flagging (it could not see the AutoBuffer's inline storage get filled). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * element-wise engine: unary math kernels (sqrt/exp/log/sin/cos/tanh/erf/relu) + select New dispatched pair math.simd.hpp / math.dispatch.cpp - the unary/ternary sibling of arithm.simd.hpp: - vecUnaryKernel: T -> T over f16/bf16/f32/f64 on top of the intrin_math primitives (v_exp/v_log/v_sin/v_cos/v_sqrt/v_erf/v_max). f32/f64 compute natively, f16/bf16 ride the f32 hub inside the kernel (vx_load_pair_as / v_store_pair_as) - no materialized casts. Continuity collapse + the halide right-edge backoff, suppressed in-place (it would re-apply Op to already-written values). tanh = (e^2x-1)/(e^2x+1) with the input clamped to +/-10 (f32) / +/-20 (f64) - unclamped saturation hits inf/inf = NaN. erf has no f64 SIMD primitive: std::erf per lane. - selectKernel(mask, x, y): 1-byte mask expanded to lane width and tested against zero in the INTEGER domain (immune to DAZ/FTZ), branches of any depth by element size, broadcast branches supported. - emitUnary: math over a float input is T -> T now (f16 in -> f16 out, native kernel when input and result depths match); integer inputs still compute in the float domain and land in f32. - emitTernary/select: literal branches are typed via typedConstFrom (an OP_CAST of a depth-less flex const crashed); a non-1-byte mask is normalized by an explicit "mask != 0" compare, never a value cast. texpr already parsed the function names - they now execute. Tests: per-depth accuracy of all 8 ops against the double std:: reference, integer input, in-place, select over 4 depths / const branch / float mask. Perf vs the classic kernels (1920x1080 f32, 16 threads, AVX2): exp 3.7x, log 2.6x, sqrt 5.7x faster; polarToCart expressed as (r*cos(a), r*sin(a)) 4.0x. Accuracy improves too (max rel err vs f64 reference): exp 8.1e-8 vs 2.1e-7, log 8.0e-8 vs 1.5e-7. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * engine: OP_COPY_MASK folded into OP_SELECT; selectKernel moved to arithm.simd.hpp copyMask(dst, mask, src) is select(mask, src, dst) - one masking primitive instead of two. The compiler emits the masked-op tail as addInsn(OP_SELECT, mask, r, out, out): the output slot rides as both arg2 and the result, so unmasked elements are preserved by reading them back through the b-branch. OP_COPY_MASK, copyMaskKernel and getCopyMaskFunc are gone. selectKernel (moved from math.simd.hpp to arithm.simd.hpp) inherits every copyMaskKernel optimization: - the interleaved multichannel fast path (2..4 channels under a per-pixel mask: expand the mask once per VECSZ rows, v_store_interleave across lanes); - the per-row scalar path with the row-skip when the selected source row IS dst (the "leave the output untouched" half of copyMask); - plus the select-specific ones: branch broadcasts (stepx == 0) and the right-edge tail backoff under dst-aliases-a-branch - safe because re-running select over already-blended elements is idempotent; only dst == mask keeps the backoff off (the store would rewrite mask bytes before the re-read). Masked-add perf is on par with the old copyMask (1280x720, 1 thread: 8UC3 204 -> 198 us, 32FC3 1395 -> 1344, 8UC1/32FC1 within noise). Full core suite 24117 green. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * engine: dedicated vectorized pow kernel (moved from arithm to math.simd.hpp) pow was the last scalar-only binary op (scalarBinaryKernel + std::pow, f32/f64 only). The new powKernel keeps exact std::pow semantics and is T x T -> T over all four float depths (f16/bf16 via the f32 hub): - scalar exponent (the dominant call shape - texpr literals ride as 0-dim broadcast consts) is dispatched PER ROW to the special cases: y==2 -> x*x, y==3 -> x*x*x, y==0.5 -> v_sqrt, y==1 -> copy, y==0 -> fill 1; - everything else - including a per-element exponent array - runs the general vectorized exp(y * log(x)) path, valid for x > 0; a vector pair containing any x <= 0 lane falls back to scalar std::pow for that pair (v_check_any), which preserves every std::pow subtlety: signed results for integer y on negative bases, NaN for fractional y, the x == 0 family; - no right-edge tail backoff: pow is not idempotent, in-place calls finish rows in the scalar tail. Perf vs the classic cv::pow (1920x1080 f32, 16 threads, AVX2): p=2 1.4x (classic special-cases it too), p=3 6.1x, p=0.5 6.3x, fractional p 4.5x with slightly better accuracy (6.1e-7 vs 7.4e-7 max rel err). Tests: exponent sweep 2/3/0.5/1/0/2.5/-1.5 vs the double std::pow reference on f32/f64, negative bases (exact signed cubes, NaN for fractional), array exponent. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * powKernel: halide right-edge tail backoff in every SIMD loop Same shape as vecBinaryKernel: the final partial vector re-processes [width - VECSZ*2, width) instead of finishing scalar, suppressed when dst aliases an input (pow is not idempotent - the overlap region must be recomputed from an untouched source, which the no-alias case guarantees). Modest measured win (~2% on ROI rows for the special-cased exponents; the general path tail was already cheap - modern libm powf is fast), no regressions; mainly aligns the kernel with the house style, where every SIMD loop ends vector-wide. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix MSVC 2019 C2975: function-local constexpr as a template argument inside a lambda MSVC 2019 loses the constexpr-ness of function-local constants (LOCAL_OPS, MAX_DIMS, ...) when they are used as template arguments inside a lambda body (AutoBuffer<Slice, LOCAL_OPS> / std::array<int, MAX_DIMS> in the parallel bodies of BroadcastOp::run and TExpr::exec). Hoist them to namespace scope - no behavior change. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * ocl_arithm_op: route 16U multiply to the CPU engine on Apple OpenCL The Apple OpenCL driver miscompiles the 16U multiply kernel: products near the top of the u16 range come back wrapped instead of saturated (CPU vs GPU NORM_INF up to 65535 in OCL_Arithm/Mul.Mat CV_16U cases). The same arithm.cl kernel is correct on Intel NEO and NVIDIA drivers - verified not to reproduce on Linux/Intel iGPU - so gate the decline to __APPLE__ only; the CPU engine computes 16u multiply exactly (integer SIMD path). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * engine: neg/abs as compositions, clamp kernel, ** and ?: operators, abs(a-b) peephole - OP_NEG and OP_ABS need no kernels: neg = sub(0, a), abs = absdiff(a, 0) - including the engine absdiff auto-type rule (signed |a| lands in the UNSIGNED type of the same width: |SHRT_MIN| fits u16 exactly instead of saturating; NB the public cv::absdiff auto depth keeps the source type for 4.x compatibility - values agree, the depth rule is the engine own). - peephole: abs(x - y) rewrites to absdiff(x, y) ALWAYS. On integers the literal semantics differ (the subtract saturates first: u8 gives max(x-y, 0)), but whoever writes abs(a - b) means absdiff - we deliberately hand out the useful semantics instead of the saturation artifact. The just- emitted OP_SUB is retired via the moveToOutput manoeuvre, so the program shrinks to the single absdiff instruction. abs(x), abs(x - 0) and absdiff(x, 0) all give one result. - OP_CLAMP kernel (arithm.simd.hpp): v_min(v_max(x, lo), hi) over u8/s8/u16/s16/u32/s32/f32 (+f64 with 64-bit SIMD), scalar f16/bf16/64-bit ints; lo/hi may broadcast (the common clamp(img, a, b) shape) or be full arrays; the tail backoff stays on under dst-aliases-x (clamp is idempotent). emitTernary types literal bounds via typedConstFrom (same flex-const crash select had) and keeps the auto result type pinned to x. - parser: "a ** b" == pow(a, b), precedence above * /, RIGHT-associative (a ** 2 ** 3 == a ** 8); "cond ? a : b" == select(cond, a, b), precedence below everything, right-associative chains (f1 ? a : f2 ? b : c) work without parentheses. parseTernary() is the expression entry point now. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * cv::exp/log/sqrt on the engine via math_op; hal functions wrapped as engine kernels math_op is the master function of the unary math family (the arithm_op analogue): same-shape same-type output over f16/bf16/f32/f64 (classic exp/log accepted f32/f64 only - the half floats are new), two tiers: - small (<= 100000 elements) and continuous: call the kernel DIRECTLY over the flattened data - no TExpr, no broadcastOp, no parallel_for setup; - everything else: the usual single-instruction program via compile()/exec() (parallelism for large arrays, real steps for ROIs). getMathFunc routes OP_EXP/OP_LOG at f32/f64 through the full cv::hal stack - an external vendor HAL (CALL_HAL), IPP, or the built-in table kernels, whichever is installed - by wrapping hal::exp32f/exp64f/log32f/log64f as engine kernels with the function pointer in TKernel::userdata, the same mechanism castKernel uses for core BinaryFuncs. The engine adds tiling and parallelism on top, so every tier gets the best available scalar-span implementation. v_exp/v_log remain for f16/bf16 (the f32 hub) and the ops hal has no entry points for. v_log_default_32f: the degree-8 polynomial is evaluated by Estrin pairing (4 dependent levels) instead of an 8-FMA Horner chain (~5% on the f16 hub path). An exp64 Taylor-without-division rewrite was tried and benched SLOWER than the Cephes Pade scheme (the evaluation is FMA-throughput-bound, and vdivpd pipelines well enough) - reverted; a table-based reduction is the only way further there. cv::exp f32 (16 threads, AVX2+IPP build), old -> new: 640 elements 0.16 -> 0.15 us, 16k 2.79 -> 2.49, 640x480 47 -> 20, 1920x1080 452 -> 60 us (the old CPU loops were single-threaded); f64 exp 1080p 1295 -> 161 us. No size regresses; small arrays now run at installed-HAL speed. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * getMathFunc: IPP tier + raw-HAL probing; the exp/log table kernels are deleted The raw cv_hal_* entry points return int for a reason: without an installed HAL they are stubs returning CV_HAL_ERROR_NOT_IMPLEMENTED. getMathFunc now selects the exp/log implementation in three tiers: 1. HAVE_IPP && ipp::useIPP(): ippsExp/ippsLn through thin int adapters (IPP is not routed through the cv_hal_ hooks, so it needs its own tier); 2. the raw cv_hal_exp32f/... hook, PROBED once with a 1-element call on the safe input 1.0 (cached in magic statics): implemented -> wrapped as an engine kernel with the function pointer in TKernel::userdata; 3. the engine own v_exp/v_log kernels. Whichever wins, the engine adds tiling and parallelism on top. The EXPTAB/LOGTAB table kernels and their tables (~790 lines in mathfuncs_core.simd.hpp + mathfuncs.cpp) are DELETED: they benched within ~15% of v_exp/v_log, not worth a second implementation. The public cv::hal::exp32f/exp64f/log32f/log64f keep their contract - CALL_HAL, then IPP, then the built-in implementation - but the built-in is now the engine vector kernel via ew::mathSpanEngine (one contiguous span, exported from math.dispatch.cpp). All unary math kernels (vec/scalar/hal wrappers, pow) also handle the vertical-broadcast tile (s0y == 0, a row expanded into a matrix): the first row is computed, the rest are memcpy of it - transcendentals cost far more than a row copy. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * texpr: hypot(x, y) binary op (alias: mag) hypot = sqrt(x^2 + y^2), NAIVE like cv::magnitude (not the overflow-safe std::hypot), computed in the float work type; kernels for the four float depths only (T x T -> T; integer inputs ride the usual f32-compute + cast). A 10-line EwHypot functor on top of vecBinaryKernel in arithm.simd.hpp - broadcast branches, continuity collapse and the tail backoff come for free. Registered in the parser as both "hypot" (the C/numpy name) and "mag" (the cv::magnitude-flavored alias). A building block for the future cartToPolar. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * texpr: atan2(y, x) binary op - radians, standard C range v_atan2 (arithm.simd.hpp, generic over the universal-intrinsic float vector): the fastAtan2 minimax polynomial from mathfuncs_core v_atan_f32 reworked to plain radians - the 180/pi factor dropped from the coefficients and the C quadrant logic instead of the [0, 360) wrap, so the result matches std::atan2 over (-pi, pi]. Measured absolute accuracy ~1.6e-4 rad. (v_atan_f32 itself is untouched - cv::phase/fastAtan2 keep their degree semantics.) EwAtan2 rides vecBinaryKernel: f16/bf16/f32 through v_atan2 (the f32 hub), f64 through exact scalar std::atan2. arg0 = y, arg1 = x, like std::atan2; float depths only, same emitBinary policy as pow/hypot. Parser name "atan2". Together with hypot this completes the cartToPolar building blocks. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix the RISC-V RVV build and two ARM64 warnings The new f64 kernel registrations (hypot, pow, the unary math family) gate on CV_SIMD_64F || CV_SIMD_SCALABLE_64F, but the vx_setall_as(const double*, v_float64&) helper family in arithm.simd.hpp was still CV_SIMD_64F-only - scalable platforms (RVV) have v_float64 with CV_SIMD_64F == 0, so vecBinaryKernel<double, ...> failed to instantiate there. Widen the helper gate to match (verified with a riscv64 rv64gcv cross-build of opencv_core - the engine f64 paths now vectorize on RVV instead of not compiling). cv::exp/cv::log: the depth local is consumed by CV_OCL_RUN only - CV_UNUSED for OpenCL-less builds (ARM64 -Wunused-variable). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * silence the remaining ARM64 gcc warnings - compare boundary-rewrite: {}-init the fixed kind/bound arrays (filled for every channel used below, but gcc cannot prove it across the cn <= 4 loop); - cv::exp/log: [[maybe_unused]] on the depth local (consumed by CV_OCL_RUN only), instead of the CV_UNUSED idiom; - AutoBuffer::reserve: a targeted -Wmaybe-uninitialized suppression around the live-element copy loop - only [0, sz) is read, all written before, but gcc inlining a grow-from-inline-storage chain cannot see that. An annotation for the analyzer, no behavior change. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * saturating 32-bit add/sub kernels; cv::texpr python binding; two CI warnings - v_add_sat/v_sub_sat for v_int32/v_uint32, local to arithm.simd.hpp for now (the plan is to grow them into proper universal intrinsics later): NEON single-instruction vqadd/vqsub, elsewhere the Hacker Delight bit tricks over universal intrinsics (u32 add is 2 ops: or with the wrapped-compare mask). EwAdd/EwSub overload vec() for the 32-bit lanes and getAddSubFunc routes 32S/32U T->T through vecBinaryKernel instead of the former pure scalar kernel. Semantics unchanged - the scalar int64 tail already saturated; directed boundary tests added (both rails, 0 - INT_MIN, u32 cases, a full-range random block vs an exact int64 reference). 640x480 32S add: 0.48x of 5.x -> parity (memory-bound); 1080p: 6-8x. - cv::texpr becomes CV_EXPORTS_W: python gets cv.texpr(expr, [inputs]) -> tuple of ndarrays, so `res, = cv.texpr(...)` and `mag, ang = cv.texpr(...)` unpacking both work. modules/python/test/test_expr.py covers arithmetic, the fused abs(a-b), casts, broadcasting, ?: and ** operators, math functions vs numpy, clamp, named temporaries, tuple outputs, the one-line cartToPolar and the int32 saturation cases. - warnings: {}-init the parser args array (gcc -Wmaybe-uninitialized on Ubuntu 20/22); the compare short-row block gates sizeof(T) <= 4 as constexpr so the f64 instantiation does not leave set-but-unused locals (gcc 9 -Wunused-but-set-variable). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * arithm_op: direct-kernel fast path for small continuous arrays Building and compiling the 1-instruction program plus the BroadcastOp setup costs ~40-250ns per call - negligible on big images, dominant at 127x61-class sizes where the classic 5.x functions were 1.3-2x faster. Mirror math_op two tiers in arithm_op: two same-type same-shape continuous arrays, no mask, no scalar, result depth == input depth, <= 100k elements -> call the T x T -> T kernel directly over the flattened elements (checks ordered cheapest-first). Applies to add/subtract/min/max/absdiff/multiply/addWeighted/and/or/xor; compare and divide lower to more than a single kernel (boundary rewrites, int guards) and keep the ordinary path. addWeighted falls through automatically for the 32/64-bit int types whose lowering is wide-compute + cast (getElemwiseFunc returns no direct kernel there). 127x61 vs 5.x, was -> now: add/subtract 8UC1 0.76x -> 1.3x, min/max u8 0.6x -> ~1x, addWeighted 1.0x -> 1.1-1.4x (32SC1 stays 4.5x); the one remaining laggard is add/sub 32SC1 (0.74-0.82x) - the price of the new SATURATING semantics (7-instruction AVX2 emulation vs the wrapping single add of 5.x; single-instruction on NEON). The 127x61 size is ADDED PERMANENTLY to the arithmetic/addWeighted/compare perf grids: per-call overhead regressions in these base functions must be caught by CI, not discovered by users. dst creation goes through createSameSize (whole-shape transfer including layout and future metadata, not piecemeal dims+sizes) here and in math_op. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * cv::pow rebuilt on the engine; integer-exponent and 1/sqrt(x) kernel branches Routing: p = 0/1/2 keep their early special cases (fill/copy/multiply); an INTEGER array with an INTEGER power keeps the classic iPow multiply chain - bit-exact compatibility, including its wrap-around quirks (iPow squares in int, so e.g. pow(255,4) on u8 wraps negative and saturates to 0 - somebody may rely on that). Everything else goes through the engine with the math_op two-tier scheme: small continuous arrays call powKernel directly (the exponent rides as a broadcast T scalar), the rest run the tiled parallel program. Integer arrays with fractional powers compute in the float domain and saturate back; the 32U/64-bit depths (classic iPow asserted on them) and f16/bf16 (the classic float path misread them) now just work. powKernel gets two new per-row exponent branches: - p == -0.5: 1/v_sqrt(x) (the classic path used IPP ippsInvSqrt_A21, a 21-bit approximation; ours is exact - slightly slower on small arrays, 4.5x faster at 1080p via parallelism); - any other INTEGER p (|p| <= 65536): LSB-first binary exponentiation, the same multiply chain and order as iPow, fully vectorized - a few ulp accurate vs ~2e-7 of exp(p*log x), and exact on non-positive bases (the sign falls out of the multiplies, 0^negative divides to inf) - no scalar patching. cv::pow f32 vs 5.x: p=0.5 365 -> 61 us at 1080p (6x), p=3 7.7x, p=5 7x AND faster at every size (the old scalar chain: 0.81 -> 0.47 us at 127x61), p=2.5 5.3x. The s16^5 iPow path is untouched (118.7 == 118.5 us). pow_exponents accuracy tests extended to 11 exponents x f32/f64 against the double std::pow reference. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * perf: SANITY_CHECK_NOTHING for the tests whose grids got the 127x61 size The 127x61 entry added to guard per-call overhead has no regression data in opencv_extra, so the legacy SANITY_CHECK in addWeighted/compare failed on CI (locally it passes silently without the test-data path). Accuracy of both functions is covered by the accuracy suite; the perf tests should measure time. PatchNaNs/finiteMask keep their SANITY_CHECK - their grids are untouched. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix a temp-buffer double release in the liveness pass ("d*d" crash) When the same temp is passed as SEVERAL arguments of its last-use instruction (e.g. the named-intermediate expression "d = {0} - {1}; d*d", where the MUL consumes slot d twice), the buffer-reuse scan pushed the temp's physical buffer onto the free list once per argument. That overflows the ntemps-sized freeBufs array (caught by the AutoBuffer range check in Debug: python test_expr.py::test_named_temporary) and, in larger programs, would hand the same physical buffer to two live temps. Release the buffer once by retiring lastUse[t] after the first hit. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * executor: recalibrate opCost to vectorized cycles + clamp the stripe count The per-element op costs fed into the parallel_for_ stripe hint were scalar-era estimates (~20x above the vectorized reality: the atan2/exp polynomials run at ~1.5 cycles/element, not 30). The hint therefore split transcendental/divide work into hundreds of ~1 us jobs, which the macOS/GCD backend dispatches poorly under sustained load, on top of the P/E-core equal-share straggler effect. Measured on M4 Max (12P+4E), sustained medians @1920x1080 f32: texpr atan2 320 -> 133 us, cv::exp 280 -> 141 us, cv::log 301 -> ~200 us, cv::pow(x,2.5) 388 -> 376 us; the PR tables' math rows improved ~1.5-2x across the board. - opCost is now in units of ~1/4 cycle/element of the SIMD kernels: cheap ops 1 (unchanged), div/sqrt/hypot/convert_scale 10 -> 3, transcendentals 30 -> 6. - the stripe hint is clamped by min(4*nthreads, max(32, 3*nthreads)): ~4 stripes/thread is plenty of granularity for element-wise work, and the ceiling is 32 pieces except on machines with many (heterogeneous) cores, where anything coarser than ~3 pieces/worker turns the slow cores into equal-share bottlenecks (measured: 32 stripes on 16 threads is the worst point of the curve - 193 us vs 137 us at 48 for atan2). getNumThreads() is clamped from below (WINRT/plugin backends may report 0). Not addressed here (needs cross-machine data, M2/M3 Ultra): streaming memory-bound ops saturate the M4 Max fabric at ~8 fat stripes and E-core participation only adds contention - a cost model cannot express that; candidate follow-up is a bytes-aware clamp or a GCD-backend-level fix. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * multiply: v_mul_sat integer kernels (full product clamped to the type) v_mul_sat(V, V) -> V for u8/s8/u16/s16/u32/s32 - the full-precision product clamped to the lane type, which is exactly cv::multiply's integer semantics at scale == 1. Local to arithm.simd.hpp for now, next to v_add_sat/v_sub_sat, to be promoted into proper universal intrinsics later. NEON: widening vmull + saturating narrow (vqmovn); other backends: the portable v_mul_expand + saturating v_pack composition for 8/16-bit lanes. 32-bit lanes have no universal widening multiply (no v_mul_expand for s32), so the 32-bit integer fast path is NEON-only for now and the other backends keep the previous f64 work-vector kernels (which measure well on x86 with IPP-free AVX2). EwMul::vec() now routes the integer lane types through v_mul_sat, and getMulFunc_ passes the NATIVE lane vector as the scale==1 fast-path type: whole-register loads/stores, the widening happens inside the multiply. Replaces both the half-register widening loads (u8/s8/u16/s16) and the scalar-equivalent f64 path for 32S/32U on NEON. M4 Max, 640x480 (the sizes where the old kernels lost to carotene): 8U 22.0 -> 13.6 us, 8S 15.0 -> 11.1, 16S 21.2 -> 17.4, 32S 84.8 -> 30.5 (parity with the classic path everywhere, 32S was 0.38x). 1920x1080: 8S 1.30x -> 1.78x, 16S 2.57x -> 2.98x, 32S 2.20x -> 4.02x vs 5.x. Correctness: exhaustive 8-bit (all 65536 pairs per sign), directed saturation corners for 16/32-bit (46341^2, INT_MIN*-1, 65536*65536, all sign combinations) against an exact int64 reference. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * NEON: make v_cvt_f64(v_int32) exact (was via f32, losing bits > 2^24) The NEON implementations of v_cvt_f64/v_cvt_f64_high for v_int32 did s32 -> f32 -> f64 (vcvt_f32_s32 + vcvt_f64_f32), silently rounding any |x| > 2^24. Every vectorized f64 work path with int32 inputs on AArch64 was affected: the engine's addWeighted/divide 32S kernels, convertTo 32S -> 64F, etc. Found via addWeighted 32SC1 on values ~1e9: max error was 32 vs the exact double reference (the classic carotene path is worse still - it computes in f32 end-to-end with f32-truncated weights, max error 96 on the same data). The exact sequence sxtl + scvtf (vmovl_s32 + vcvtq_f64_s64) is the same 2 instructions, so there is no cost. addWeighted 32SC1 on the engine now matches the exact-double reference bit-for-bit and stays at parity/1.4x vs the classic path (640x480/1920x1080). Pre-existing upstream bug (same code in 4.x) - worth a standalone backport with directed large-value tests. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * math_op: drop the temporary direct-IPP tier for exp/log Upstream moved the IPP math wrappers into the hal/ipp HAL module (cv_hal_exp32f/ log32f & co now resolve to ipp_hal_* which honor cv::ipp::useIPP via CV_HAL_CHECK_USE_IPP). The engine's single probeHalUnary(cv_hal_*) probe already picks that up uniformly, so the stopgap #ifdef HAVE_IPP ippExp/ippLog tier and its ipp::useIPP() branch in getMathFunc are now redundant - removed. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * arithm: restore cv::hal::and8u/or8u/xor8u/not8u as engine wrappers These public CV_EXPORTS entry points (core/hal/hal.hpp) lost their definitions when the bitwise ops moved to the element-wise engine, but they are still declared and called by other modules (opencv_objdetect's aruco) and external code - the link broke with undefined references to cv::hal::and8u/xor8u. Restore them as thin forwarders over the engine's byte-wise bitwise kernels (getBitwiseFunc / getNotFunc), mirroring the existing mul8u wrapper. CV_Assert guards the kernel lookup. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * blobdetector: guard empty contour when computing blob radius The new AutoBuffer leaves its tail uninitialized for trivial types, which surfaced a -Wmaybe-uninitialized in findBlobs where the median of per-point distances is read. Use a std::vector, default the radius to 0, and compute the median only for a non-empty contour - no unproven size invariant. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
34074075b2 |
Merge pull request #29369 from abhishek-gola:fp8_support
FP8 support in core module #29369 Core part of https://github.com/opencv/opencv/issues/29313 ### 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 |
||
|
|
c9070f9f35 | Merge branch 4.x | ||
|
|
66263c5952 |
Merge pull request #29057 from Teddy-Yangjiale:rvv-core-norm
Rvv core norm #29057 Fixes opencv/opencv#29052 ### Problem `Core_Norm/ElemWiseTest.accuracy/0` failed on RISC-V with RVV enabled when computing norm for `CV_16S` data. The reported failing case was: ```text src[0] ~ 16sC4 3-dim (1 x 116 x 40) ``` The expected norm result was a large positive `double`, but the RVV path returned an incorrect value: ```text expected: 3370900308417 actual: -173296 ``` This indicates that the problem was not in the public `cv::norm()` API, but in the RVV HAL implementation used for the `CV_16S` L2/L2SQR accumulation path. ### Root Cause The RVV HAL has a specialized implementation for `CV_16S` L2 norm: ```cpp NormL2_RVV<short, double> ``` The implementation widens `int16` values, squares them, converts the widened products to `float64`, accumulates them in an `f64m8` vector, and finally reduces the vector to a scalar `double`: ```cpp auto s = __riscv_vfmv_v_f_f64m8(0, vlmax); ... auto v_mul = __riscv_vwmul(v, v, vl); s = __riscv_vfadd_tu(s, s, __riscv_vfwcvt_f(v_mul, vl), vl); ... return __riscv_vfmv_f(__riscv_vfredosum(...)); ``` The bug was in the scalar initializer passed to `__riscv_vfredosum`. Before this patch, the code created an `f64m1` scalar vector but used the maximum vector length for `e32m1`: ```cpp __riscv_vfmv_s_f_f64m1(0, __riscv_vsetvlmax_e32m1()) ``` This is inconsistent: the vector type is `f64m1`, so the VL used to initialize it must correspond to `e64m1`, not `e32m1`. |
||
|
|
8cc3f68cd4 |
Merge pull request #28964 from abhishek-gola:extend_primitive_core_ops
Extended primitive core operations to support new types #28964 The support was already there, this PR tests them on edge cases and patch the fix. closes: https://github.com/opencv/opencv/issues/24580 ### 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 |
||
|
|
2d15169ab5 |
Merge pull request #28692 from YangGuanyuhan:fix-lightglue-assertion-fail
dnn: fix dst_dp assertion in broadcast for size-1 dims causing crash in lightglue.onnx model #28692 The original assertion CV_Assert(dst_dp == 1) does not handle valid cases where the innermost dimension size is 1 like [10, 5, 1], resulting in dst_dp == 0. This occurs during broadcasting in LightGlue ONNX model and leads to assertion failure. Allow dst_dp == 0 for size-1 dimensions to handle this edge case correctly. ### 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 |
||
|
|
b5a7e0c662 | Merge branch 4.x | ||
|
|
01320ab612 | Fixed cv::mul overflow for U16 type. | ||
|
|
82ff8e45e9 | Merge branch 4.x | ||
|
|
912d27a7b7 |
Merge pull request #28180 from fengyuentau:rvv_hal/flip
rvv_hal: fix flip inplace #28180 Fixes https://github.com/opencv/opencv/issues/28124 ### 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 |
||
|
|
879218500d |
Merge pull request #27918 from Kumataro:fix26899_5.x
core: support 16 bit LUT for 5.x #27918 Porting from https://github.com/opencv/opencv/pull/27890 Porting from https://github.com/opencv/opencv/pull/27911 And support new OpenCV5 types for 16 bit LUT. ### 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 |
||
|
|
d0d9bd20ed |
Merge pull request #27890 from Kumataro:fix26899
core: support 16 bit LUT #27890 Close https://github.com/opencv/opencv/issues/26899 ### 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 |
||
|
|
bdab54f79e |
Merge pull request #27757 from vpisarev:matshape_inside_mat
Use MatShape instead of MatSize inside cv::Mat/cv::UMat #27757 **Merge together with https://github.com/opencv/opencv_contrib/pull/3996** --- This PR continues cv::Mat/cv::UMat refactoring. See #26056, where `MatShape` was introduced. Now it's put inside cv::Mat/cv::UMat instead of a weird `MatSize`. MatSize is now an alias for MatShape: **before:** ``` struct MatShape { ... }; struct MatSize { ... }; struct Mat { ... int dims; int rows; int cols; ... MatShape shape() const { ... /* constructs MatShape out of MatSize and returns it; layout is always 'unknown', because we don't store it */ } MatSize size; // size is not valid without the parent cv::Mat, // because size.p may point to Mat::rows or to Mat::cols, // depending on the dimensionality, and dims() returns Mat::dims. MatStep step; // may allocate memory, depending on the dimensionality. ... }; ``` **after:** ``` struct MatShape { ... }; typedef MatShape MatSize; // they are now synonyms struct Mat { ... int dims; int rows; int cols; ... MatShape shape() const { return size; } // just return the embedded shape (including the proper layout information) MatSize size; // size is self-contained data structure that can be used without the parent cv::Mat. // size.dims is now a copy of dims; size.p[*] contains copies of Mat::rows and Mat::cols when dims <= 2. MatStep step; // does not allocate extra memory buffers. ... }; ``` There are several reasons to do that: 1. the main reason is to be able to store data layout (MatShape::layout) inside each cv::Mat/cv::UMat. This is necessary for the proper shape inference in DNN module. In particular, it's necessary for the next step of DNN inference optimization where we introduce block-layout-optimized convolution and other operations. Later on, we can use layout information to support non-interleaved images (e.g. RRR...GGG...BBB...) or even batches of such images in core/imgproc modules. 2. the other reason is to represent 3D/4D/5D etc. tensors as cv::Mat/cv::UMat instances more conveniently, without extra dynamic memory allocation. Before this patch we allocated some memory buffers dynamically to store shape & steps for more than 2D arrays. Now the whole cv::Mat/cv::UMat header can be stored completely on stack/in a container. Creating another copy of Mat/UMat header is now done more efficiently. 3. the third reason is to introduce the new coding pattern: `dst.create(src.size, <dst_type>);`. The pattern is suitable for most of element-wise (including cloning) and filtering operations. This pattern does not only look crisp and self-documenting, it will also automatically copy shape (including layout) from the source tensor into the destination matrix/tensor. 4. in the future we might add `colorspace` member to MatShape that will allow to distinguish RGB from BGR or NV12. `dst.create(src.size, <dst_type>);` will then copy the colorspace information as well. ### 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 |
||
|
|
59c87f3206 | Out of buffer access fix in the new 5.x tests. | ||
|
|
4919cda8b2 | Merge branch 4.x | ||
|
|
0fed1fa184 |
fix exp, log | enable ui for log | strengthen test
Co-authored-by: Liutong HAN <liutong2020@iscas.ac.cn> |
||
|
|
57a78cb9df |
Merge pull request #26941 from GenshinImpactStarts:lut_hal_rvv
Impl hal_rvv LUT | Add more LUT test #26941 Implement through the existing `cv_hal_lut` interfaces. Add more LUT accuracy and performance tests: - **Accuracy test**: Multi-channel table tests are added, and the boundary of `randu` used for generating test data is broadened to make the test more robust. - **Performance test**: Multi-channel input and multi-channel table tests are added. Perf test done on - MUSE-PI (vlen=256) - Compiler: gcc 14.2 (riscv-collab/riscv-gnu-toolchain Nightly: December 16, 2024) ```sh $ opencv_test_core --gtest_filter="Core_LUT*" $ opencv_perf_core --gtest_filter="SizePrm_LUT*" --perf_min_samples=300 --perf_force_samples=300 ``` ```sh Geometric mean (ms) Name of Test scalar ui rvv ui rvv vs vs scalar scalar (x-factor) (x-factor) LUT::SizePrm::320x240 0.248 0.249 0.052 1.00 4.74 LUT::SizePrm::640x480 0.277 0.275 0.085 1.01 3.28 LUT::SizePrm::1920x1080 0.950 0.947 0.634 1.00 1.50 LUT_multi2::SizePrm::320x240 2.051 2.045 2.049 1.00 1.00 LUT_multi2::SizePrm::640x480 2.128 2.134 2.125 1.00 1.00 LUT_multi2::SizePrm::1920x1080 7.397 7.380 7.390 1.00 1.00 LUT_multi::SizePrm::320x240 0.715 0.747 0.154 0.96 4.64 LUT_multi::SizePrm::640x480 0.741 0.766 0.257 0.97 2.88 LUT_multi::SizePrm::1920x1080 2.766 2.765 1.925 1.00 1.44 ``` This optimization is achieved by loading the entire lookup table into vector registers. Due to register size limitations, the optimization is only effective under the following conditions: - For the U8C1 table type, the optimization works when `vlen >= 256` - For U16C1, it works when `vlen >= 512` - For U32C1, it works when `vlen >= 1024` Since I don’t have real hardware with `vlen > 256`, the corresponding accuracy tests were conducted on QEMU built from the `riscv-collab/riscv-gnu-toolchain`. This patch does not implement optimizations for multi-channel tables. Previous attempts: 1. For the U8C1 table type, when `vlen = 128`, it is possible to use four `u8m4` vectors to load the entire table, perform gathering, and merge the results. However, the performance is almost the same as the scalar version. 2. Loading part of the table and repeatedly loading the source data is faster for small sizes. But as the table size grows, the performance quickly degrades compared to the scalar version. 3. Using `vluxei8` as a general solution does not show any performance improvement. ### 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 |
||
|
|
1483504702 | Merge branch 4.x |