imgproc: reject unsupported depths in OpenCL threshold - #30252Fixes#30251
### Problem
`ocl_threshold()` does not check the input depth. On 5.x a `UMat` of depth `CV_64U`, `CV_64S` or `CV_32U` gets through, because `ocl::typeToStr()` maps those depths to valid OpenCL types and the kernel compiles. The function then indexes the 8-entry `min_vals[]` table with a depth of 10, 11 or 12, which reads past the end of the array, and skips the `depth <= CV_32S` flooring of `thresh`.
The CPU implementation rejects these depths with `StsUnsupportedFormat`, so the same call throws for a `Mat` and returns an image for a `UMat`, depending on whether an OpenCL device is available.
`CV_16BF` and `CV_Bool` did not reach the table, but failed with `Assertion failed (result) in typeToStr` instead of `StsUnsupportedFormat`.
### Fix
Return `false` from `ocl_threshold()` for every depth above `CV_64F`, before the kernel is built. Those inputs now fall through to the CPU path, which reports `StsUnsupportedFormat` as it does for `Mat` input.
The depths the OpenCL branch accepted in 4.x (`CV_8U` to `CV_64F`) behave as before.
### Tests
`Imgproc_Threshold_Unsupported_Depth.umat` is parameterized over `CV_16F`, `CV_16BF`, `CV_Bool`, `CV_64U`, `CV_64S`, `CV_32U` and `THRESH_BINARY`, `THRESH_TRUNC`. It checks that `threshold()` on `Mat` and `UMat`, and `thresholdWithMask()` on `UMat`, throw.
On current 5.x with an OpenCL device (Apple M1 Pro, OpenCL 1.2) it fails for `threshold()` on `UMat` with `CV_64U`, `CV_64S` and `CV_32U`. With this patch it passes with OpenCL enabled and with `OPENCV_OPENCL_DEVICE=disabled`. The other `threshold()` tests in `opencv_test_imgproc`, including the OpenCL ones, still pass locally (the `Imgproc_AdaptiveThreshold` tests were not run, they need `opencv_extra` data).
### Pull Request Readiness Checklist
See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request
- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake
core: reduceND, used by the DNN Reduce2 layer - #30157
Split out of #30082, which now carries only the resize half.
Adds `cv::reduceND`, which reduces an n-dimensional array over a set of axes with any of the `ReduceTypes`, extended with `REDUCE_PROD`, `REDUCE_L1`, `REDUCE_L2`, `REDUCE_LOG_SUM` and `REDUCE_LOG_SUM_EXP`. `cv::reduce` accepts n-dimensional input through it.
`sum`, `mean` and `minMaxIdx` now share one parallel driver (`stat_parallel.hpp`), so they parallelize over large arrays the same way `reduceND` does.
The new graph engine's `Reduce2` layer calls `cv::reduceND` instead of its own kernels, so `reduce2_kernels.simd.hpp` and the hand-written reduction loops in `reduce2_layer.cpp` go away.
### Pull Request Readiness Checklist
See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request
- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
Patch to opencv_extra has the same branch name.
- [x] The feature is well documented and sample code can be built with the project CMake
calib document fix - #30208
Documentation changes - three doxygen blocks in `modules/objdetect`.
- **`findChessboardCorners`** (PR#22083): whether the returned order pins down a unique
physical corner depends on the **parity** of the two `patternSize` dimensions, not on
whether they differ. Quads are built from the dark squares only (`calibinit.cpp:755`
`THRESH_BINARY`, `:796` white frame, `:1919` holes-only), so a rotation is admissible
only if it maps dark squares onto dark squares. For `patternSize` of w x h interior
corners the squares form a (w+1) x (h+1) grid, so 180° preserves the colouring exactly
when w and h share parity:
| `patternSize` | distinct origins | ambiguity |
|--------------------------------|------------------|---------------|
| different parity (9x6, 8x5) | 1 | none |
| same parity, w != h (8x6, 7x5) | 2 | 180° |
| w == h (7x7, 8x8) | 4 | 90° |
The square case is not colour: the transpose at `calibinit.cpp:1745` is a no-op when
`width == pattern_size.width`, so the detector cannot tell rows from columns. Verified
over 24 in-plane rotations and 60 perspective views per board, zero detection failures;
inverting the square colouring moves the origin but not the count.
Practical consequence is the reverse of what was documented: the common 9x6 board is
unambiguous, while this docstring's own sample `Size patternsize(8,6)` is not. The note
now recommends a board whose dimensions differ in parity first, then
#findChessboardCornersSB + `CALIB_CB_MARKER`, then ChArUco. Still harmless for
intrinsics (each view absorbs the rotation into its own pose); still breaks hand-eye.
- **`findCirclesGrid`** (PR#7312): the returned points are the keypoint locations reported
by `blobDetector` as-is, without refinement - the parameter is a `FeatureDetector` and
`SimpleBlobDetector` is only the default, so the points are not necessarily moment
centroids. Under perspective the apparent centre of a projected circle can be displaced
from the projection of the physical centre; the displacement vanishes when the board is
parallel to the image plane and is not removed by fitting an ellipse. Points at the
`blobDetector = NULL` path for supplying corrected centres. Describes the bias
qualitatively rather than quoting a fixed estimate.
- **`setLegacyPattern` / `detectBoard`** (PR#23152, PR#29636): the flag is a no-op on
odd-row boards, and a wrong setting fails silently - markers detected, zero corners,
only a `CV_LOG_DEBUG` line; notes that calib.io boards use the legacy layout and aligns
the 4.6.0 version wording across both headers.
### 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
- [ ] 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
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.
Calling resize(size() - 1) in pop_back() pulls in the buffer growth path
for the unreachable sz == 0 case in release builds (where size() - 1
underflows to SIZE_MAX), which both bloats codegen and triggers an LLVM
ScalarEvolution assertion on 32-bit Hexagon Clang. Guard and decrement
sz directly instead.
Rebasing onto 5.x picked up facc3fdc7d, which vectorized the masked norm for the remaining depths,
and Core_NormL1_Signed then failed on CI for masked CV_32S at INT_MIN - 13 jobs, every platform.
The new kernel takes the magnitude before widening:
v_int32 s = v_reinterpret_as_s32(v_and(v_abs(vx_load(src + i)), v_normmask_u32(mask + i)));
acc0 = v_add(acc0, v_cvt_f64(s));
v_abs() does give |INT_MIN| correctly, as an unsigned 2147483648, but reinterpreting that back as
int32 turns it negative again and the widening carries the sign into the accumulator, so the norm
came out as -16 * 2^31 for 16 elements. Mask the value instead, widen to double - exact for every
int32 - and take the magnitude there, which is what the unmasked path already does.
The 8- and 16-bit masked kernels are not affected: v_abs() returns the unsigned type there too, and
they accumulate in unsigned without reinterpreting back to signed.
- 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.
- 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.
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.
calib: accept float64 points in calibrateCamera - #30176
Lets calibrateCamera, calibrateCameraRO, stereoCalibrate, initCameraMatrix2D, and registerCameras accept Point3d/Point2d (double) input in addition to Point3f/Point2f. Adds a new test suite (float64Points) exercising each of those entry points with double-precision input and comparing accuracy against the float32 path.
### 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
Mixed point layouts broadcast residuals to an incompatible matrix.
Reshape both observed and projected points to rows before subtraction so
calibration and uncertainty estimation accept either layout.
When running DIS Optical Flow on OpenCL devices supporting `cl_khr_subgroups` (such as ARM Mali GPUs), `dis_flow.cpp` detects subgroup support and appends `-DCV_USE_SUBGROUPS=1` to OpenCL kernel build options.
However, `modules/video/src/opencl/dis_flow.cl` was missing `#pragma OPENCL EXTENSION cl_khr_subgroups : enable`. As a result, OpenCL kernel compilation failed with implicit function declaration errors:
<source>:189:12: error: implicit declaration of function 'sub_group_reduce_add' is invalid in OpenCL
sum_diff = sub_group_reduce_add(sum_diff);
^
<source>:229:11: error: implicit declaration of function 'get_sub_group_local_id' is invalid in OpenCL
int sid = get_sub_group_local_id();
Fix by adding `#pragma OPENCL EXTENSION cl_khr_subgroups : enable` inside `#ifdef CV_USE_SUBGROUPS` in `dis_flow.cl`.
Fixes#27507
Calib: assersion fix of fisheye calib - #30173
Replaces a CV_Assert in fisheye::InitExtrinsics with a graceful failure path (returns bool, caller now throws a descriptive StsBadArg naming the degenerate view) instead of crashing on a hard assert. Also adds validation that rejects legacy numeric flag values passed to fisheye::calibrate/stereoCalibrate, and fixes CALIB_CHECK_COND to actually gate the condition check in stereo calibration. Includes an hdr_parser.py change to resolve using Base::CONST enum aliases for Python bindings.
### 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
objdetect: handle unsupported QR modes gracefully - #30123
### 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
### Description
Resolves#30110.
This PR addresses two related defects in `QRCodeDetector` and Python string conversion bindings:
1. **`objdetect`**: In `QRCodeDecoderImpl::decodeSymbols` (`qrcode_encoder.cpp`), encountering unsupported or unhandled QR mode indicators (such as Hanzi mode 13 or FNC1) previously called `CV_Error(Error::StsNotImplemented, format("mode %d", currMode))`, throwing an unhandled `cv2.error` exception out of high-level detector calls like `detectAndDecodeMulti()`. Replaced `CV_Error` with `return false;` to report symbol decode failure gracefully.
2. **`python`**: In `pyopencv_from(const String& value)` (`cv2_convert.cpp`), converting C++ string payloads to Python `str` previously called `PyString_FromString` (`PyUnicode_FromString`), which raises a `UnicodeDecodeError` when decoding non-UTF-8 payload bytes (e.g. GB2312 or Shift-JIS lead bytes). Updated string conversion to use `PyUnicode_DecodeUTF8(..., "surrogateescape")` with fallback to `PyBytes_FromStringAndSize`.
### Testing
- Added `TEST(Objdetect_QRCode, unsupported_mode_graceful)` in `modules/objdetect/test/test_qrcode.cpp`.
- Move the activation clip clamp and holdFinishedRows into
recurrent_activations.hpp and call them from both GRU and RNN; drop the
redundant useClip flag, since clip > 0 is the switch.
- Select the GRU outputs positionally, matching getMemoryShapes(), instead
of guessing Y / Y_h from their shape and keeping the old single-output
may-be-Y_h policy.
- Reject direction=reverse together with two-direction weights instead of
silently running both sweeps backwards, and drop the unreachable assert.
- Collapse the four inlined GRU references into one shared helper and drop
the stale sentence from the SingleOutputIsSequenceY comment.
- Drop the hand-made hPrev allocation: hInternal.copyTo() already sizes and
types it.
- Gate the GRU reference on the input timestep rather than the loop
position, so reverse + sequence_lens skips the padding instead of the
valid steps, and cover that combination with a test.
Document that fisheye::calibrate forces a fixed K1..K4 coefficient to
0 even when CALIB_USE_INTRINSIC_GUESS supplies a guess for it, and
that CALIB_FIX_INTRINSIC overrides CALIB_FIX_K1..K4 in stereoCalibrate.
Note that the default Schur-complement engine in calibrate() sums
per-view contributions in parallel, so repeated calls are not bit
reproducible; CALIB_DISABLE_SCHUR_COMPLEMENT does not have this issue.
Correct the CALIB_USE_INTRINSIC_GUESS docs for fisheye::calibrate and
fisheye::stereoCalibrate: skew and k1..k4 must also be initialized,
and the default focal length is max(width,height)/2, not /pi.
Document that undistortPoints() runs a fixed 5 iterations by default
and never checks its 0.01 epsilon unless TermCriteria::EPS is set in
the passed criteria, and clarify that fisheye::undistortPoints' default
epsilon is an angular threshold, not comparable to undistortPoints'
pixel-space one. Also name the criteria parameter in
undistortImagePoints().
The test runs DISK plus LightGlue over 1024 keypoints and needs more
memory than the 32-bit Windows x86 build can hand out, so it died with
an OutOfMemoryError on a 512 MB allocation. Every other DNN-backed test
in the module already carries CV_TEST_TAG_MEMORY_2GB; this one was
missing it.