core, imgproc: support 0D Mat in LUT and threshold
Give a 0D input a 1x1 header before the row-based code runs, the same way #30704 normalizes 1D inputs in gemm:
threshold / thresholdWithMask: src (and mask) are viewed as 1x1, so the output is 1x1, the same as the other imgproc functions return for 0D input.
LUT: src and dst get 1x1 headers for the HAL and parallel paths. dst is created with createSameSize, so the result itself stays 0D.
dnn: support UINT32 and UINT64 targets in Cast
Map ONNX UINT32 (12) and UINT64 (13) to CV_32U and CV_64U in mapToCvDepth.
Add CV_32U and CV_64U cases to truncateFloatToInt, so float inputs truncate toward zero as ONNX requires, instead of being rounded by convertTo.
Allow CV_32U and CV_64U in the outputType parameter.
dnn: support CV_32U and CV_64U in Reduce layers
Fix
In modules/dnn/src/layers/reduce2_layer.cpp: Add CV_32U and CV_64U to getTypes validation.
In modules/dnn/src/layers/reduce_layer.cpp: Add CV_32U and CV_64U to getTypes and typeDispatch (opDispatch<uint32_t> and opDispatch<uint64_t>).
In modules/dnn/test/test_int.cpp: Extend Test_Reduce_Int to include CV_32U and CV_64U.
In modules/dnn/test/test_layers.cpp: Add Layer_Test_Reduce_Unsigned parameterized test checking MAX, MIN, and SUM on CV_32U and CV_64U with values greater than 2^31 to verify unsigned comparison logic.
dnn: reject zero delta in Range layer
Check that delta is not zero in getRangeParams() before rangeSize() is called: CV_CheckNE for the float branch and CV_CheckTrue(idelta != 0, ...) for the integer branch, since CV_CheckNE has no int64_t overload. Both forward() and getMemoryShapes() go through getRangeParams(), so both are covered.
* imgproc: support 5.x depths in remap/warp with INTER_NEAREST
nn_tab in cv::remap only had entries for CV_8U..CV_64F, so remap,
warpAffine and warpPerspective with INTER_NEAREST failed with
"nnfunc != 0" for CV_16F, CV_16BF, CV_Bool, CV_64U, CV_64S, CV_32U and
both fp8 depths. Nearest neighbor only copies pixels, so add the
remapNearest instances for these types, in both the absolute and the
WARP_RELATIVE_MAP rows. Using the real element types keeps the border
value conversion right (e.g. CV_Bool border 2 becomes 1).
Add an Imgproc_Warp_NearestNewDepths test.
* imgproc: use MatDepth in Imgproc_Warp_NearestNewDepths
A plain int parameter prints a failing case as GetParam() = 13. MatDepth prints the depth name instead.
* imgproc: convert remap nearest border once, dispatch copy by element size
dnn: support CV_32U, CV_64U and CV_Bool values in OneHot
Add the missing case labels, calling the existing runKernel<uint32_t>, runKernel<uint64_t> and runKernel<bool>.
tensorToScalar could not read CV_64U tensors. It now reads them as uint64_t and writes the result without going through int64_t, so values above INT64_MAX are not cut down. The output conversion moved into a small storeScalar template, called with double, int64_t or uint64_t; the results for the other input types are unchanged.
- Implement Col2ImLayer supporting static/dynamic output shape inference and spatial summation
- Enforce CV_32F data input and int32/int64 shape inputs in getTypes() and forward()
- Require 1-D rank and CV_64S value range-checking (rejecting > INT_MAX) for image_shape and block_shape
- Support multi-dimensional spatial blocks, dilations, pads, and strides
- Parse image and block shapes using OpenCV tensorToIntVec()
- Parallelize across batch and channels using a single parallel_for_ with batch*channel <= INT_MAX guard
- Guard wide-coordinate offsets and domain arithmetic against signed overflow
- Add unit and parameterized tests in test_layers for shape inference, type validation, empty inputs, oversized shapes, malformed ranks, coordinate bounds, malformed attributes, and 4-D spatial values
- Add Col2Im performance benchmark baseline in modules/dnn/perf/perf_col2im.cpp
- Skip Col2Im conformance tests in OpenVINO filter
- Un-denylist all 5 official ONNX conformance tests
# Conflicts:
# modules/dnn/test/test_layers.cpp
# Conflicts:
# modules/dnn/test/test_layers.cpp
geometry: respect row stride in triangulatePoints
The fix uses step1(0) to advance between points in a two-channel column matrix, while keeping the existing two-scalar step for row matrices. I applied this separately to both camera inputs and used size_t for the scalar offsets.
The triangulation algorithm itself is unchanged, and packed-column behavior from #28829 is preserved.
I also added a regression test covering float and double inputs, including contiguous columns, cloned ROIs, row layouts, and non-contiguous column ROIs on the left camera, right camera, or both.
core: add the missing CV_Bool kernel to cv::compare
The fix is not simply reusing the uchar kernel. A CV_Bool byte is not guaranteed to be 0 or 1:
Mat wrapping an external buffer performs no conversion, so other values are reachable through
the public API, and comparing the raw bytes would order 2 above 1 when both mean true.
documentation fix 5.0 to 5.x - #30977
Replace stale "OpenCV 5.0" current-version wording with "5.x" in the 5.x docs (landing page, sidebar, prebuilt-binaries and transition-guide tutorials)
### Pull Request Readiness Checklist
See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request
- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [ ] The PR is proposed to the proper branch
- [ ] There is a reference to the original bug report and related work
- [ ] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake
core: non-CPU HAL (cv::accel) with a CUDA backend
What this PR adds: cv::accel, a non-CPU HAL in core, kept to a minimal first version.
Explicit placement: UMat::createOn(device, shape, type), Mat::upload(device) and UMat::upload(device). Mat::upload() returns once the Mat has been read; UMat::upload() returns the same UMat when it is already on that device.
Functions with an accelerator hook (cv::flip and cv::transpose in this PR) run on the device stored in the input's UMatData. Their output is created there with createOn(), also when the backend declines the call and the CPU runs it. Other functions run on the CPU as before.
One allocator per backend; each buffer keeps its device in UMatData::allocatorContext.
One stream per device and CPU thread (Device::threadStream()). Work of one thread runs in order; work of different threads is synchronized explicitly with cv::accel::synchronize(device).
Operations are reached with device.ops<accel::CoreOps>("core") and called directly. A stream keeps the buffers of queued work alive until it finishes (Stream::retain()), as the OpenCL backend does with a running kernel's UMats.
In-place calls are handled by each operation: the CUDA backend swaps mirrored elements for an in-place flip and transposes square matrices in place.
A CUDA backend with flip and transpose kernels. Discrete GPUs get memory from a stream-ordered pool that keeps freed memory for reuse while the pool holds less than a quarter of the device's memory, and returns the rest to the driver. On a GPU the build has no kernels for, the calls fall back to the CPU.
* doc(core): fix output type rules for mulTransposed and calcCovarMatrix
* doc(core): describe calcCovarMatrix mean depth rule per overload
* doc(core): drop redundant gemm note from mulTransposed src
Fix sanitizer bugs in OpenCV image warping
Strip BORDER_ISOLATED and validate borderType (0 <= borderType <= BORDER_TRANSPARENT)
Align cv::borderInterpolate (copy.cpp) and borderInterpolate_fast
Only compute tl_ofs in scalar bicubicCoeffs when all_inliers is true
Comparing two CV_Bool matrices threw "no kernel for this op/type combination" for all six
comparison operations, while the matrix/scalar overload of the same function worked.
compareByType had a case for every other depth, CV_32U, CV_64U and CV_64S included, so
CV_Bool was the only one left out.
The uchar kernel is not a correct substitute. A CV_Bool byte is not guaranteed to hold 0 or
1, since a matrix wrapping an external buffer is never converted, and comparing the raw
bytes would order 2 above 1 when both mean true. countNonZero, norm, sum and the scalar
compare overload all already read CV_Bool logically, and notKernel documents the same rule
for bitwise NOT.
scalarCompareKernel takes an isBool template parameter that normalises each operand to 0/1
before comparing. It is a compile time constant, so the existing instantiations are
unchanged.
photo: weight the CalibrateDebevec gauge equation like the data equations (5.x) 🤖🤖🤖
the CalibrateDebevec gauge equation g(128) = 0 is weighted with the hat weight of the middle value instead of 1, so the offset of the response curve no longer depends on float32 rounding in the solver. calibrate.cpp is identical on 4.x and 5.x.
Remove the Intel-only gate for medianFilter3_u/medianFilter5_u when cn==1 and dimensions meet the alignment requirements.
Port of https://github.com/opencv/opencv/pull/29803.
core: fix pow with zero exponent on high-channel images 🤖🤖🤖
The zero-exponent branch of cv::pow fills the destination with a four-component Scalar. CPU outputs with more than four channels reject it. Use a single numeric input that broadcasts to every channel for this case. CUDA output continues through the four-component path required by its OutputArray implementation.
The 5.1 wheel reproduces the assertion for five and nine channels. A patched ARM64 Release core build passed a native 24-case check across Mat and UMat, CV_8U, CV_16F and CV_32F, and channels 1, 4, 5 and 9. Added a parameterized Core regression test.
The Debevec response curve g is defined only up to an additive constant,
which CalibrateDebevec fixes with one equation g(128) = 0 of weight 1
(as in Debevec and Malik's gsolve.m), while the data and smoothness
equations are weighted by the hat function (up to 127) and lambda times
it (up to 1270). The offset is therefore weakly constrained in the
float32 least-squares solve, and rounding differences between builds
shift the whole curve: depending on the build, response(128) is between
0.86 and 1.07 instead of 1. This is most likely the cause of the
intermittent Photo_CalibrateDebevec.regression failure on Windows x64
(0.2147 > 0.15, see #30063).
Weight the gauge equation with the hat weight of the middle value. The
exact least-squares solution is unchanged; the float32 result now
matches a float64 solve to 3e-4.
Add a test that the middle value is fixed and drop the ARM-only and
non-IPP relaxed thresholds of the regression test.
Photo_CalibrateDebevec.bug_24966 now prints max_diff 1.31 and 1.15 on
every build: the values of an exact float64 solve. The earlier,
build-dependent values (0.98 to 1.25) included the offset noise.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* dnn: add ONNX ReverseSequence layer
- new ReverseSequenceLayer: byte-wise block copy, works for any CV type and rank >= 2
- getTypes(): accept CV_16S as well, grouped by signed/unsigned/float families
- tests: CV_16S rank-2 / rank-3 block copy, both axis layouts, int32 sequence_lens,
out-of-range sequence_lens must throw
# Conflicts:
# modules/dnn/test/test_layers.cpp
* dnn: simplify ReverseSequence layer and tests
Parallelize over (batch, time) pairs, take byte strides from X.step, validate sequence_lens up front and drop the redundant type whitelist. Rework the layer test to check an independent reference implementation.
* dnn: reuse tensorToIntVec in ReverseSequence layer
Read sequence_lens through the shared helper and check its element count, so lengths are narrowed once. Compare the layer test against an index-based reference instead of duplicating the layer's stride computation.
* dnn: state supported opsets and skip ReverseSequence for OpenVINO
Drop the future-opsets claim in the layer header and mark the two conformance cases as skipped for the OpenVINO backend, following the Compress operator.
* dnn: add ReverseSequence to the ONNX importer dispatcher
Register an explicit parseReverseSequence() handler instead of relying on the generic custom-layer path. Drop the constant-only layer tests and fold the sequence_lens length check into the out-of-range test.
cv::stackBlur returns wrong values on 16-bit images whose values use the upper part of the range. A constant image doesn't stay constant, and the output changes with the thread count.
There are two causes, both only in the universal-intrinsics paths for 16-bit data:
opRow<ushort>, opRow<short>, opColumn<ushort, int> and opColumn<short, int> compute (sum * mul) >> shr. stackblurMul is sized for 8-bit sums, so with a 16-bit sum the product overflows 32 bits.
opRow<ushort> and opRow<short> use v_add on two 16-bit samples before the kernel multiply. That add saturates. It's the same loss on any two samples whose sum doesn't fit in 16 bits.
The existing StackBlur.regression test doesn't reach this, because it converts an 8-bit image and the values stay small.
Fix
Add stackblurDivide, which computes trunc(float(sum) * mulVal). That is the same arithmetic the scalar loops already use, so the two now agree, and stripe boundaries no longer change the result. The 8-bit paths are unchanged.
Multiply each 16-bit sample after widening instead of adding two samples first.
Use int64_t sums where the largest sum doesn't fit int: from radius 181 for CV_16U, radius 255 for CV_16S and radius 2901 for CV_8U. Those radii take the scalar loops. Radii that fit keep the 32-bit SIMD paths.
opColumn<uchar, int> multiplies and shifts in v_uint32. From radius 181, sum * stackblurMul[radius] no longer fits a signed 32-bit int for values from 128 up, so vertical CV_8U blurs with kernels 363 to 509 saturated to 255. The largest product fits 32 bits unsigned. This was already on the base; nothing changes below radius 181.
Reject a kernel whose worst-case sum doesn't fit int64_t either, with a CV_Check: radius 11,863,373 and up for CV_16U, 16,777,215 for CV_16S, 190,184,348 for CV_8U. Only images tens of millions of pixels long reach these.
* imgproc: fix warpPolar inverse mapping at the angular seam and for sub-matrix input
* imgproc: use a mask for the ring check in the warpPolar seam test
videoio: port Python stream seek and callback fixes to 5.x 🤖🤖🤖
Forward-port #30798 from 4.x to 5.x. Opening some videos from a Python stream can fail when a seek offset exceeds the signed 32-bit range. This port preserves 64-bit stream arguments, handles Python callback failures and stream cleanup safely, and reports read failures to FFmpeg as I/O errors.
The diff matches the merged 4.x patch. It includes the original Python videoio regressions and the standalone C++ regression for a throwing IStreamReader. The Python tests reuse fixtures already in opencv_extra/5.x.
* dnn: handle min > max in Clip layer and enable ONNX conformance test
Under the ONNX specification, the Clip operator is defined mathematically as
y = min(max(x, min), max). When min > max, the operation clamps identically
to max for all input values.
Previously, ClipLayerImpl asserted minValue <= maxValue in its constructor
and actualMin <= actualMax in forward, causing assertion failures on valid
ONNX models with min > max. Additionally, the adjacency graph fusion interpreter
checked a < min first, returning min instead of max.
This commit:
1. Removes the min <= max assertions in ClipLayerImpl constructor and forward,
allowing ONNX-conforming evaluation where min > max clamps to max.
2. Updates FusionEltwiseOp::CLAMP in AdjacencyGraph interpreter to use
std::min(std::max(a, n.scalar), n.scalar2), matching the ONNX evaluation order.
3. Removes test_clip_min_greater_than_max from the layer parser denylist.
4. Adds unit tests covering static and dynamic min > max clipping.
* dnn: filter test_clip_min_greater_than_max for OpenVINO backend
* dnn(test): address review comments on Clip min > max tests and fusion coverage
promote2() mapped CV_64S and CV_64U to CV_64F, so cv::add and cv::subtract
computed a 64-bit integer array mixed with a narrower integer array in double,
and values above 2^53 lost their low bits: 3074457345618258602 + 5 gave
3074457345618258432.
Two integer depths (CV_IS_INT_TYPE, which includes CV_Bool) of which one is
64-bit now meet at promoteArith()'s integer type, as in NumPy. uint64 with a
signed integer, which no integer type holds, still promotes to CV_64F.
Adds Core_EW_AddSub.mixed_depth_s64_u64_exact and makes the same change to the
promote2() mirror in test_new_arithm_extensive.cpp.
Float rounding can push cosAlpha or cosBeta slightly outside [-1, 1] when one keypoint is just inside the other, so acos() returned NaN. Clamp both cosines before acos and add a regression test.
- Strip BORDER_ISOLATED and validate borderType
(0 <= borderType <= BORDER_TRANSPARENT)
- Align cv::borderInterpolate (copy.cpp) and borderInterpolate_fast
- Only compute tl_ofs in scalar bicubicCoeffs when all_inliers is true
* geometry: reject degenerate minimal samples in estimateAffine2D/estimateAffinePartial2D
RANSACPointSetRegistrator::run() has a fast path used whenever exactly
the minimum number of points is supplied (3 for affine, 2 for
similarity). That path skips checkSubset() and trusts the kernel's
return value, but Affine2DEstimatorCallback::runKernel() and
AffinePartial2DEstimatorCallback::runKernel() always returned success,
even when dividing by a zero or near-zero denominator (collinear or
duplicate points). The result was a matrix full of inf/nan with every
point reported as an inlier, instead of a clean failure.
Both kernels now check the denominator against a threshold scaled by
the square of the point coordinates (matching how far float32 input
can drift from true collinearity/coincidence) and return 0 when it is
degenerate. The existing "<= 0" checks in the fast path and the general
RANSAC loop already handle this correctly.
The general RANSAC loop (more than the minimum points) is unaffected,
since a NaN/Inf model already fails computeError's inlier count.
Add test3CollinearPoints and test2DuplicatePoints, matching the
existing test file style.
* geometry: make the degeneracy tolerance independent of coordinate offset
The tolerance used absolute coordinates, so valid points far from the origin were rejected. estimateAffine2D now measures it against the triangle edges, and estimateAffinePartial2D only rejects coincident points. Add large-offset regression tests.
* geometry: tidy the comment in the similarity kernel
* geometry: test points that are collinear only up to float rounding