* dnn: test LogSoftmax far below the maximum
LogSoftmax must give x - max - log(sum(exp(x - max))) for values about 104 or more below the row maximum, where exp underflows in float32. Covers a short row and one long enough for the SIMD loops, on the CPU and OpenCL targets. Port of the test from #30545.
* dnn: compute LogSoftmax without taking the log of softmax
logSoftmax() took the log of the softmax output, so elements whose exp(x - max) underflows came out as -inf. The dispatched softmax kernel already has the row maximum and the sum of exp((x - max) * scale), so softmax() takes a logSoftmax flag and the log path writes (x - max) * scale - log(sum) directly.
The OpenCL kernels had the same problem with LOG_SOFTMAX: they now keep x - max, add up exp(x - max) and return x - max - log(sum). This covers the generic kernels in softmax.cl and the subgroup kernels in softmax_loss.cl.
Port of #30545 to 5.x.
* doc(core): fix LUT index formula for CV_8S and CV_16S inputs
LUT reads CV_8S and CV_16S values as the unsigned numbers with the same bits, so negative values index the upper half of the table (-1 maps to entry 255 for CV_8S). The docs said the index was src + 128 (CV_8S) or src + 32768 (CV_16S), which is wrong for every value. Also remove a stray 'ref' in the compare docs.
* doc(core): fix LUT index rule in HAL interface docs
cv_hal_lut and cv_hal_lut16 docs still said 128 or 32768 is added to the index for 8s and 16s inputs. Use the same rule as the LUT docs: the input is read as unsigned with the same bits, and no offset is added.
core: fix locateROI and getUMat for 1D Mat and UMat
Problem
For a 1D Mat, Mat::locateROI divides by step[0] (the element size), so it counts every element as a row and returns a wrong wholeSize and offset. Because of this, adjustROI doesn't grow 1D slices, and getUMat on a 1D slice recurses until the stack overflows. UMat::locateROI has the same bug.
Fix
Mat::locateROI and UMat::locateROI: for dims == 1, compute the offset and whole size from the element size: ofs = (delta1 / esz, 0) and wholeSize = (delta2 / esz, 1). The width is clamped to at least ofs.x + cols, like the 2D code.
Mat::getUMat: for a 1D slice, cut the result out of the whole UMat with a Range instead of a Rect, so the returned UMat stays 1D. Cutting with a Rect always made it 2D.
2D Mats and UMats are unchanged.
core: saturate cv::add and cv::subtract on CV_64S and CV_64UProblem
cv::add and cv::subtract are documented to saturate, and they do on every depth up to 32 bits. On 64 bits there is no wider type to hold the result, so add wrapped on CV_64S and CV_64U, and subtract wrapped on CV_64S. For example, INT64_MAX + 1 gave INT64_MIN. Signed overflow is also undefined behaviour in C++.
Fix
Added int64_t and uint64_t overloads of EwAdd::scl and an int64_t overload of EwSub::scl. They check for overflow before computing the result, like the existing uint64_t overload in EwSub.
Updated the comment on EwAdd::scl, which described 32-bit and 64-bit results as wrapping.
Other depths still use the generic scl, so their behaviour does not change.
* dnn: keep INT4/UINT4 QuantizeLinear off the AVX2 per-tensor fast path
The x86 AVX2 path for per-tensor float to int8/uint8 returns before the
4-bit saturation added in #30596, so INT4/UINT4 outputs were still
clamped to the 8-bit range there. Skip it for 4-bit output and add a
per-tensor INT4/UINT4 test that reaches that path on x86.
* dnn: clamp INT4/UINT4 inside the AVX2 per-tensor QuantizeLinear path
Pass the output range into the AVX2 kernel instead of skipping it, so
per-tensor INT4/UINT4 keeps the vectorized, parallel path; the kernel
already clamps in float before converting. The post-pass from #30596
is only reached by the generic path now. Widen the regression test to
35 elements so it covers the 8-lane loop and the scalar tail on x86.
* dnn: drop the PR reference from the INT4 QuantizeLinear test comment
---------
Co-authored-by: Kaustubh Arora <arorakaustubh681@gmail.com>
* video: dis: vectorize Densification_ParBody with scalable intrinsics
* video: dis: address review comments: braces, parameterized test on all platforms
* video: dis: restore useOptimized with a scope guard in the DIS reference test
* core: support CV_16F and CV_16BF in finiteMask
finiteMask asserted CV_32F or CV_64F input, so 16-bit float arrays,
which can hold NaN and infinity too, could not be checked.
Add finiteMask16_, which marks a pixel as finite if no channel has an
all-ones exponent (0x7c00 for CV_16F, 0x7f80 for CV_16BF), for 1 to 4
channels. getFiniteMaskFunc now takes the depth. The OpenCL kernel only
handles float and double, so other depths fall back to the CPU path.
* core: use SIMD and typed templates in 16-bit finiteMask
Use hfloat and bfloat as the template parameter of finiteMask16_ instead
of the raw exponent masks, and add a universal-intrinsics path for 1 to
4 channels.
Add Core_FiniteMask_bits, which checks exact bit patterns at the edges
of the exponent: largest finite, subnormal, signalling, quiet and
negative NaN, and both infinities.
* core: use the scalar loop for 1-channel 16-bit finiteMask
With 1 channel, the compiler vectorizes the scalar loop, and it runs
faster than the explicit SIMD path. Use the SIMD path only for 2 to 4
channels.
* Document transparent border for warpPerspective
* Keep warpPerspective clarification documentation-only
Remove the focused transparent-border test as requested in review. Preserve the documented border behavior and leave the existing image-warp test suite unchanged.
* core: support 1D Mat inputs in gemm
A 1D Mat is a single row, but its step[0] is the element size, not the row size, so gemm passed a too-small row step to the HAL kernels and failed with "_step >= minstep". Give 1D A, B and C an ordinary 2D one-row header before calling the kernels.
Fixes#30703
* core: support preallocated 1D output in gemm
When the caller passes a 1D Mat of the right size as the output, _matD.create() keeps it as is, so D still had step[0] == elemSize() and the kernel failed with "_step >= minstep". Give a 1D D a 2D one-row header too. The result is still written into the caller's buffer.
* core: use TEST_P for the 1D gemm test
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
Add OPTFLOW_FARNEBACK_REUSE_EXPANSION, an opt-in flag set through
FarnebackOpticalFlow::setFlags() / create(..., flags). When set, calc() keeps
the polynomial expansion of the previous call's next frame and reuses it as
the expansion of the following call's prev frame, which saves roughly 9-14%
on consecutive-frame sequences. Results are bit-identical with reuse on and
off. The flag adds no virtual methods, is ignored by calcOpticalFlowFarneback()
and by the OpenCL path, and clearing it or calling collectGarbage() frees the
cache.
Tests go into test_OF_accuracy.cpp and test_OF_reproducibility.cpp and seed
their data from theRNG(). Includes a perf test and a tutorial section.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
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