Port of #30434 to 5.x. Since 4.7.0 the final SOLVEPNP_ITERATIVE
refinement starts from the minimal sample model. For a planar object
this model can be the mirrored pose, and Levenberg-Marquardt stays in
that local minimum. For planar inliers, also refine from the homography
based initialization of SOLVEPNP_ITERATIVE and keep the pose with the
lower reprojection error. Non-planar objects are not affected.
Fixes#27098
inRange rejects CV_Bool and CV_8F inputs and addWeighted rejects CV_Bool inputs, but the docs did not say so. Also fix type-name typos in core.hpp (CV8S, CV_8S1) and two other spelling mistakes.
* core: add insertChannel and extractChannel test for all depths
insertChannel had no CPU test that checks its values, and extractChannel
was only checked on CV_8UC3. Add a test for every depth with 2 to 4
channels: inserting into one channel must leave the others unchanged,
and extractChannel must return the inserted channel.
* core: use CV_DEPTH_CURR_MAX in insertChannel test
Cover every depth with a range instead of listing them by hand, so new
depths are tested automatically.
docs(imgproc): correct the documented Sobel kernel size range - #30661
## Problem
`cv::Sobel` and `cv::getDerivKernels` document the kernel size as
> `@param ksize size of the extended Sobel kernel; it must be 1, 3, 5, or 7.`
> `@param ksize Aperture size. It can be FILTER_SCHARR, 1, 3, 5, or 7.`
but `getDerivKernels` (modules/imgproc/src/deriv.cpp) actually enforces a different constraint:
```cpp
if( _ksize % 2 == 0 || _ksize > 31 )
CV_Error( cv::Error::StsOutOfRange, "The kernel size must be odd and not larger than 31" );
```
so every odd size up to 31 is accepted, and `FILTER_SCHARR` (-1) selects the 3x3 Scharr kernels.
Reproduced with opencv-python-headless 5.0.0:
```
getDerivKernels(1, 0, 9) -> OK, 9-tap kernel
getDerivKernels(1, 0, 15) -> OK, 15-tap kernel
getDerivKernels(1, 0, 31) -> OK, 31-tap kernel
getDerivKernels(1, 0, 33) -> error: "The kernel size must be odd and not larger than 31"
getDerivKernels(1, 0, -1) -> OK (Scharr 3x3)
cv2.Sobel(img, cv2.CV_32F, 1, 0, ksize=9/15) -> OK
cv2.Sobel(img, cv2.CV_32F, 1, 0, ksize=101) -> error (out of range)
```
## Change
Documentation-only: the two `@param ksize` entries now state the constraint the
implementation enforces (odd, not larger than 31) while keeping 1, 3, 5, 7 as the typical
choices. No code change.
Signed-off-by: NUAAwqy <162230229@nuaa.edu.cn>
Porting of perf tests extension from 4.x to 5.x - #30663
Following PRs are being ported:
* #29908
* #29922
* #29972
No more changes are introduced.
PR for opencv-extra: https://github.com/opencv/opencv_extra/pull/1458
### 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
* dnn: check weight, bias and past_state in CausalConvWithState
Check the ONNX shapes of weight [C, 1, k], bias [C] and past_state [B, C, k - 1] against the input in getMemoryShapes, and require them to be float in forward, since the kernel indexes all three by input channel and reads them as float.
* dnn: check CausalConvWithState input types before fp16 conversion, require rank-1 bias
* core: support fp8 depths in cv::sum
cv::sum and cv::trace threw for CV_8F_E4M3FN and CV_8F_E4M3FNUZ. Add
sum8f and sum8fnuz to the function table, and collect their float totals
in blocks like CV_16F and CV_16BF.
* core: test cv::sum on fp8 past the block size
Add a (1 << 15) + 1 element case to Core_Sum_FP8, so the float total is
moved to the double result and reset between blocks.
* core: support fp8 depths in cv::mean
cv::mean uses the same adding functions as cv::sum, so adding fp8 to that table made it accept these depths. Its blockSum check still left them out, so the float totals were written straight into the double result and the mean came back wrong. Use the block path for CV_8F_E4M3FN and CV_8F_E4M3FNUZ, as cv::sum does, and check cv::mean in Core_Sum_FP8.
* core: test cv::mean with a mask on fp8
* core: split Core_Sum_FP8 into sum, mean and mean_mask tests
Move the array setup into a fixture, and make the length a test parameter, so each case runs on its own.
core: fix in-place cartToPolar when only the magnitude overwrites an input (5.x) - #30715
5.x port of #30646, as requested in its review. Fixes#30645 on 5.x.
### Problem
`cv::cartToPolar` gives wrong results on `CV_32F` when only the magnitude output is the same `Mat` as `x` or `y`. The SIMD tail handling repeats the last full block, and `cartToPolar32f_` only skipped that for in-place calls when the angle was aliased.
### Fix
Same as #30646: added `mag == X || mag == Y` to the check, so these calls handle the leftover elements with the scalar code.
### Tests
Same `Core_CartToPolar_inplace_mag.accuracy` test as #30646 (`CV_32F`, lengths 1 to 39, magnitude overwriting `x`, then `y`). On Apple M1 Pro it fails without the fix on 5.x and passes with it. The full `opencv_test_core` passes.
### 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: vectorize cv::sum for CV_64F
Sum_SIMD has specializations for the 8-, 16- and 32-bit depths, but not for
CV_64F, so cv::sum and cv::mean on a double matrix fall through to the scalar
unrolled loop in sum_. CV_64FC1 is not in TYPICAL_MAT_TYPES, so no perf test
covered it.
The source type is already the accumulator type, so the specialization needs
neither expansion nor conversion: it loads three vectors at the native width and
adds them. The channel limit matches DEFINE_SUM_SIMD_32 because init_maskbuf can
only build the cn == 4 masks once the vector holds four lanes, which rules the
case out on an SSE2 baseline.
Extend sum_wide with the CV_64F rows so the change is measurable.
* core: reuse DEFINE_SUM_SIMD_16 for CV_64F
Drop the near-duplicate DEFINE_SUM_SIMD_64 and instantiate DEFINE_SUM_SIMD_16
with v_float64 instead, as suggested in review.
The one thing that kept the two apart was the channel guard. DEFINE_SUM_SIMD_16
rejects cn > 4, which is correct only while the vector holds at least four lanes:
init_maskbuf builds the cn == 4 masks under that condition, so with a narrower
vector the reduction runs against all-zero masks and drops the vectorized
elements without reporting anything. Every 32-bit register type has four lanes or
more, so the existing instantiations never saw it; v_float64 has two on an SSE2
baseline.
Widening the guard to the DEFINE_SUM_SIMD_32 form leaves the existing
instantiations unchanged, since 3+(simd_width>=4) is 4 for all of them.
docs(imgproc): medianBlur also accepts ksize = 1 - #30662
## Problem
`cv::medianBlur` documents the aperture as
> `@param ksize aperture linear size; it must be odd and greater than 1, for example: 3, 5, 7 ...`
but the implementation only requires an odd size: the aperture check is
`(ksize % 2 == 1) && (_src0.dims() <= 2)`, and `ksize = 1` is accepted and returns the image
unchanged (a 1x1 median is the pixel itself).
Reproduced with opencv-python-headless 5.0.0:
```
cv2.medianBlur(img, 1) -> OK, output is identical to the input
cv2.medianBlur(img, 2) -> error: "(ksize % 2 == 1) && (_src0.dims() <= 2)" in 'medianBlur'
```
## Change
Documentation-only: mention `ksize = 1` so the docs match the implemented behavior.
No code change.
Signed-off-by: NUAAwqy <162230229@nuaa.edu.cn>
videoio(v4l): return false when MJPEG frame decoding fails - #30672
### 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
When `imdecode` fails on a corrupt MJPEG/JPEG buffer it leaves `frame` untouched, so `retrieveFrame()` handed back the previous frame and returned true. Now the frame is released on decode failure and `retrieveFrame()` returns false for an empty frame, so `read()` returns false too.
I don't have a V4L2 device here, so this is only compile-checked on Linux (videoio with V4L and built-in libjpeg-turbo). The existing V4L tests use vivid and have MJPEG disabled, so I didn't add a test.
Fixes#30666
core: keep large CV_32U values when reading with FileStorage - #30685Fixes#30684
### Problem
When a `CV_32U` `Mat` was loaded with `FileStorage`, values above `INT_MAX` came back as `0`, in YAML, XML and JSON, with and without base64. The saved file had the correct values, so only reading was affected.
### Fix
- `FileNodeIterator::readRaw` read elements of up to 4 bytes through `(int)node`, so these values turned negative and the `CV_32U` case clamped them to 0. It now always reads the node as `int64_t`. Each case still converts the value to its own type.
- The base64 path stored `getInt32()` as signed, so `CV_32U` now uses a new `Base64Decoder::getUInt32()`, like `getUInt8()` and `getUInt16()`.
`CV_64U` values above `INT64_MAX` are also lost in the text formats, but that has a different cause, in the parsers' `strtoll`, so it is not part of this PR.
### Tests
New `Core_InputOutput.filestorage_32u_large_values` saves values on both sides of `INT_MAX` and loads them back, in YAML, XML and JSON, with and without base64. All 6 combinations fail without the fix, and the test passes with it on Apple M1 Pro.
### 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
imgproc: handle empty input image in findContours and findTRUContours - #30690
Since cv::copyMakeBorder now asserts that the source matrix is non-empty, calling cv::findContours or cv::findTRUContours on an empty image threw an exception instead of returning an empty contour list.
Guard against empty input images by clearing the output contours (and hierarchy) and returning early, matching cv::findContoursLinkRuns.
### 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
core: avoid TBB static destruction during Windows teardown - #30072
## Summary
Avoid destruction of the TBB task arena/scheduler during C++ static teardown.
On Windows with the UCRT and TBB backend, process teardown can involve
interaction between TBB cleanup and the Windows loader/CRT shutdown path.
Keeping the OpenCV-owned TBB arena/scheduler alive until process termination
avoids invoking its destructor during static destruction.
## Validation
- Reproduced the reported teardown deadlock with the MSYS2 packaged
OpenCV 5.0.0 environment.
- Built OpenCV 5.x locally with TBB enabled.
- The patched local build completed 2,001 stress-test iterations without
reproducing the deadlock.
- `git diff --check` passes.
The local 5.x baseline did not reproduce the issue during the available
baseline stress run, so the stress result is considered supporting evidence
rather than a definitive reproduction/fix confirmation.
Related issue: #30067
compilation fix: force 256-bit SIMD width under AVX2 in imgwarp - #30678
warp_kernels.simd.hpp and warp_common.vector.hpp only implement up to 256-bit SIMD and mix explicit v256_load* calls with width-generic v_* types. Force CV__SIMD_FORCE_WIDTH=256 when CV_AVX2 is enabled so builds with AVX-512 in CPU_BASELINE (-DCPU_BASELINE=AVX512_SKX) compile cleanly.
The following now compiles:
cmake -B build -DCPU_BASELINE=AVX512_SKX
cmake --build build --target opencv_imgproc --parallel
### 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.
- [ ] The feature is well documented and sample code can be built with the project CMake
Vectorize the contiguous channel dimension of the float32 bilinear inlier loop for C>4. Coordinates, interpolation tables, border handling, and scalar tails keep their existing routes; C1–C4 kernels are unchanged. https://github.com/opencv/opencv/pull/30650
Ordered not-equal predicates (_CMP_NEQ_OQ in AVX/AVX-512 and
vfcmp_cne/xvfcmp_cne in LoongArch LSX/LASX) return false when either
operand is NaN, violating IEEE-754 != semantics and diverging from C++,
SSE (_mm_cmpneq_ps/_pd), NEON, MSA, VSX, WASM, and RVV implementations
(as well as callers like intrin_math.hpp that use v_ne(x, x) to detect
NaNs).
Switch floating-point v_ne to unordered not-equal (_CMP_NEQ_UQ and
vfcmp_cune/xvfcmp_cune) and add NaN coverage to test_cmp().
Even after 0e20693a8d reduced the inline temp scratch buffers from 16KB
to 4KB, Clang hoists the fast-strip `scratchBuf` (~4.3KB) into
`TExpr::exec()`'s prologue when taking the `broadcastOp` path, while the
`broadcastOp` lambda unconditionally reserves another ~4.3KB `tstoreBuf`
on the stack even when `nbuffers == 0`. Together with `arithm_op()` and
`BroadcastOp::run()`, a single `cv::subtract` or `cv::compare` consumes
nearly 19KB of stack space on the calling thread, overflowing 64KB
fiber/coroutine stacks under deep call chains (e.g. `calibrateCameraRO`).
Outline the temp-bearing loops into `noinline` helpers
(`execFastStripWithTemps` and `execTileWithTemps`) and run the
`nbuffers == 0` tile body directly without `tstoreBuf`. This preserves
4KB L1 fragments when temporaries are present while saving ~8.7KB of
stack space on single-op `broadcastOp` calls.
* match SIMD and scalar scale association in EwMul
Restore `EwMul::scl` from `(a * b) * s` to `(a * s) * b` so the scalar
path matches SIMD `vec(preproc(a, s), b)` and avoids premature `float`
overflow on `a * b`.
Canonicalize single-sided `src1` broadcasts (`s1x == 0` or `s1y == 0`)
onto `src0` for `EwMul` in `vecBinaryKernel` and `scalarBinaryKernel`,
preserving loop-hoisted `b * s` in SIMD while matching the `(b * s) * a`
grouping in the scalar tails.
* Add more tests
Even after 0e20693a8d reduced the inline temp scratch buffers from 16KB
to 4KB, Clang hoists the fast-strip `scratchBuf` (~4.3KB) into
`TExpr::exec()`'s prologue when taking the `broadcastOp` path, while the
`broadcastOp` lambda unconditionally reserves another ~4.3KB `tstoreBuf`
on the stack even when `nbuffers == 0`. Together with `arithm_op()` and
`BroadcastOp::run()`, a single `cv::subtract` or `cv::compare` consumes
nearly 19KB of stack space on the calling thread, overflowing 64KB
fiber/coroutine stacks under deep call chains (e.g. `calibrateCameraRO`).
Outline the temp-bearing loops into `noinline` helpers
(`execFastStripWithTemps` and `execTileWithTemps`) and run the
`nbuffers == 0` tile body directly without `tstoreBuf`. This preserves
4KB L1 fragments when temporaries are present while saving ~8.7KB of
stack space on single-op `broadcastOp` calls.
HoughLines, HoughLinesP, and HoughLinesPointSet document that lines are
returned when votes > threshold. Because both accumulator votes and
threshold are integers, threshold = 0 is the only value that selects
1-vote bins (votes >= 1), as already supported by HoughLinesPointSet,
CPU HoughLines, and the OpenCL paths.
PR #30286 added CV_CheckGT(threshold, 0) at the HoughLines/HoughLinesP
entry points to avoid a divide-by-zero (`nz * numangle / threshold`) in
the IPP path. Relax this check to CV_CheckGE(threshold, 0) and guard the
IPP fast paths with `threshold > 0` instead (IPP also requires
threshold > 0).
dnn(cuda): transformer layer coverage and CUDA Graph replay on the new engine - #30439
Follow-up to #30415 (ResNet layer coverage and cuDNN JIT conv/pooling on the new engine). Adds CUDA support on the new DNN engine
for the layers transformer models need, and brings the CUDA path to parity with ONNX Runtime.
**Companion PR** opencv/opencv_extra#1448
**Changes**
- CUDA execs for Attention, Cast, ConstantOfShape, Expand, Gather, Not, Reduce, Shape, Slice, Softmax, Tile, Transpose, Concat,
Gelu, LayerNormalization, MatMul, Split, Squeeze, Unsqueeze and the element-wise activations.
- A graph with static shapes is recorded as one CUDA Graph on the second `forward()` and replayed from then on.
- The cuDNN JIT convolution reads NCHW buffers in place; NHWC staging is kept only for FP16 grouped convolutions.
- TF32 for cuBLAS GEMMs (`OPENCV_DNN_CUDA_ALLOW_TF32`), FP32 accumulation for FP16 GEMMs
(`OPENCV_DNN_CUDA_FP16_HALF_ACCUMULATE`), and fused MatMul/Gemm post-ops.
- Batch-broadcast MatMul and Shape are safe to capture in a CUDA Graph; the unused pointer-array `cublas::gemmBatched` is
removed.
- Tests: `forward()` runs three times on batch-broadcast MatMul and Shape models; `MatMul_init_bcast` runs on CUDA again;
`AttentionSharedShapeReshape` uses the FP16 default tolerance on CUDA FP16.
- Perf: new CUDA-only `*_CUDA_pinned` tests pin the input shapes.
**Performance** (ms, median of 50, FP32 with TF32, RTX PRO 6000 Blackwell, idle GPU)
| Model | CPU | CUDA (cuDNN JIT) | CUDA (full cuDNN) | ORT 1.31 CUDA EP |
|---|---|---|---|---|
| ResNet-50 | 8.02 | 0.80 | 0.80 | 0.88 |
| ResNet-18 | 3.27 | 0.44 | 0.44 | 0.48 |
| MobileNetV2 | 1.99 | 0.28 | 0.27 | 0.40 |
| DenseNet-121 | 17.42 | 1.48 | 1.58 | 1.58 |
| EfficientNet-Lite4 | 5.03 | 0.53 | 0.54 | 0.73 |
| ViT-B/32 | 11.06 | 1.02 | 1.02 | 0.95 |
| ViT-Base/16 | 24.38 | 1.16 | 1.17 | 1.13 |
| DeiT-Tiny | 4.58 | 0.65 | 0.65 | 0.68 |
| MobileViT-XS | 6.93 | 0.72 | 0.72 | 0.77 |
| YOLOv3 | 47.21 | 2.60 | 2.59 | 2.72 |
| YOLOv4 | 109.38 | 3.58 | 3.61 | 4.18 |
| YOLOv4-tiny | 7.31 | 0.64 | 0.64 | 0.66 |
| BEiT-Base | 25.30 | 1.24 | 1.24 | 1.19 |
| BERT | 10.00 | 0.97 | 0.97 | 0.99 |
| SigLIP | 41.14 | 2.09 | 2.09 | 2.44
### 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