Commit Graph

26299 Commits

Author SHA1 Message Date
Abhishek Gola
90324ef598 Merge pull request #30800 from sohailshk/fix/sum-32s-wraparound
core: stop cv::sum() wrapping at 32 bits for CV_32S
2026-11-14 09:21:00 +05:30
Mohammad Sohail Shaikh
0dd4bf367e imgproc: do not read pixels outside a sub-matrix in CLAHE padding (#30782)
* imgproc: do not read pixels outside a sub-matrix in CLAHE padding

When the size is not a multiple of the tile grid, CLAHE pads the source on the right and bottom with BORDER_REFLECT_101. This padding is internal (CLAHE has no borderType). Without BORDER_ISOLATED, copyMakeBorder takes those rows and columns from the parent matrix when the source is a region of a larger image, so the histograms of the last tiles and the result depended on pixels outside the region. Same pattern as the phaseCorrelate fix in #30725.

* imgproc: extend CLAHE_Padding to cover interior ROIs

Move the ROI regression into CLAHE_Padding: the ROI now has parent pixels to its right and bottom, and the reference padding is isolated.
2026-11-13 20:23:23 +05:30
Mohammad Sohail Shaikh
d73b2f9c87 dnn: fix Reduce over three or more axes (#30781)
* dnn: fix Reduce over three or more axes

Port of #30108 (5.x, reduce2_layer.cpp) to the 4.x Reduce layer.

ReduceInvoker walks the reduced block with an odometer over every reduced axis but the innermost one. On a carry it assigned the step of the next outer axis (j - 1) instead of removing the offset of the axis that wrapped and adding one step of the next. projected_steps is shared by all output elements, so once an outer reduced axis has three or more elements every output was wrong. Carry the same way as the unprojected axes below. This also makes test_mvn_expanded pass, so it is removed from the parser denylist.

* dnn: parameterize the Reduce multi-axis regression test

Pass each (sizes, axes) case to TEST_P instead of looping inside one TEST.
2026-11-13 17:21:33 +05:30
Pratham Kumar
97bd1d2af4 Add ARMPL HAL backend for cv::SVD::backSubst (#30054)
* Add ARMPL HAL backend for cv::SVD::backSubst

* unify SVBackSubst32f/64f into one template
2026-11-13 16:09:29 +05:30
Muhammad Usman Mateen
efe734517f dnn: compute LogSoftmax without taking the log of softmax 🤖🤖🤖 (#30545)
* 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. See #30544.

* 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 softmax kernel already has the row maximum and the sum of exp(x - max), so the log path now writes (x - max) - log(sum) directly. Subtracting max first keeps rows of large, close values exact, as in test_logsoftmax_large_number.

Fixes #30544

* dnn: pass the LogSoftmax flag to softmax() instead of a separate function

Address review: softmax() takes a logSoftmax flag with a default of false, and logSoftmax() calls it with true.

* dnn: run the LogSoftmax underflow test on the OpenCL targets

The test now runs for every target of the OpenCV backend, and uses the default FP16 thresholds for the FP16 targets.

* dnn: compute LogSoftmax in the OpenCL kernels without taking the log of softmax

With LOG_SOFTMAX, the kernels kept exp(x - max) and returned log(exp(x - max) / sum), which is -inf once exp underflows. They now keep x - max, add up exp(x - max), and return x - max - log(sum), like the CPU path. This covers the generic kernels in softmax.cl and the subgroup kernels in softmax_loss.cl.
2026-11-13 15:42:48 +05:30
Abhishek Gola
14a7962180 Merge pull request #30764 from Prasadayus/optimize/ppl-arm64-rebalance-4x (#30764)
core: ARM64 PPL adaptive self-scheduling (4.x backport)

Enabled in-house dynamic partitioning for PPL concurrency.
2026-11-13 14:33:35 +05:30
Abhishek Gola
07125879ee imgcodecs: fix IMREAD_REDUCED_* for images smaller than the scale (#30761)
Codecs without native downscaling are resized after decoding. When a side
was smaller than the scale the target size was 0 and resize() threw. Keep
at least one pixel.
2026-11-13 13:31:29 +05:30
Yixuan Tang
ce4ceac609 ml(svm): fix UB pointer overflow in solve_generic with extreme float data (#29111)
* ml: guard against negative indices in SVM solve_generic

* ml: reject non-finite SVM solver state and invalid working sets

---------

Co-authored-by: example <example@example.com>
2026-11-13 10:47:37 +05:30
Pratham Kumar
02c3be27ee imgproc: parallelize cornerSubPix using parallel_for_ (#30583)
* imgproc: parallelize cornerSubPix using parallel_for_

* restore Rect bounds check and add parallel cornerSubPix test

* force multi-threaded run in cornerSubPix parallel test

* validate cornerSubPix corners before parallel_for_ and restore thread count
2026-11-13 10:42:20 +05:30
sohailshk
4b8832f7d3 core: stop cv::sum() wrapping at 32 bits for CV_32S
Port of #30003 (5.x) to 4.x. The scalar step of sum_() added four elements to each other in the source type before the double accumulator, so 32-bit values overflowed.
2026-11-12 16:17:27 +05:30
Abhishek Gola
38af4e35d7 calib3d: fix solvePnPRansac returning the mirrored pose of planar objects (#30434)
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
2026-11-11 19:25:52 +05:30
Mohammad Sohail Shaikh
2e7478cdc9 imgproc: fix medianBlur for ksize >= 257 on 8-bit images (#30727)
* imgproc: fix medianBlur for ksize >= 257 on 8-bit images

* imgproc: keep the medianBlur O(1) kernel size check in release builds
2026-11-11 17:54:30 +05:30
Abhishek Gola
1886073f95 imgproc: speed up RGB2Gray and RGB2YCrCb on ARM NEON (#30758)
Summary
In cv::cvtColor, the 8-bit BGR/RGB → Gray and BGR/RGB → YCrCb/YUV kernels interleave each channel with its pair (v_zip), then call v_dotprod. On x86 this pair is a single pmaddwd instruction. NEON has no such instruction, so v_dotprod first un-interleaves the operands again, and the interleave is wasted work.
Changes
Added a CV_NEON branch in RGB2Gray, RGB2Gray (color_rgb.simd.hpp) and RGB2YCrCb_i (color_yuv.simd.hpp). The existing v_zip + v_dotprod path is unchanged in the #else branch, so x86 is not affected.
The NEON branch skips the interleave. It multiplies each channel by a broadcast coefficient with v_mul_expand, adds the results in 32-bit lanes, and shifts at the end.
In RGB2Gray, the NEON branch is used only when all coefficients are non-negative, which covers the default case. Custom negative coefficients fall back to the existing path.
2026-11-11 17:46:21 +05:30
Prasadayus
5d51262f1a core: replace ARM64 PPL's static partitioning with adaptive self-scheduling 2026-11-11 17:26:02 +05:30
Owais Mahmood
d55d3a4a73 imgcodecs: fix IMREAD_REDUCED_* for images smaller than the scale
Codecs without native downscaling are resized after decoding. When a side
was smaller than the scale the target size was 0 and resize() threw. Keep
at least one pixel.
2026-11-11 15:55:38 +05:00
Mohammad Sohail Shaikh
c807cf9bca imgproc: fix stackBlur on sub-matrices and in place (#30739)
* imgproc: fix stackBlur on sub-matrices and in place

The vertical pass stepped between rows by the row width, so a destination
that is a region of a larger image was read and written at the wrong
rows, and pixels outside the region were overwritten. Step by the real
row stride instead.

The horizontal pass with a kernel of 9 or fewer pixels reads pixels left
of the one it writes, so stackBlur(img, img, ksize) blurred already
blurred values. Copy the row first when the blur runs in place.

* imgproc: limit the stackBlur in-place copy, parameterize its tests

In place, only the row pass for kernels up to 9 pixels wide reads pixels
it has already written. A kernel width of 1 skips the row pass, the row
branch for wider kernels reads the whole row before writing it, and the
column pass always works in place on the destination, so these calls no
longer copy the image.

Split the sub-matrix and in-place test into two TEST_P tests over depth,
channels and kernel size.
2026-11-11 14:44:47 +05:30
Pratham Kumar
cb0cb69a65 imgproc: speed up RGB2Gray and RGB2YCrCb on ARM NEON 2026-11-10 23:15:03 +05:30
Abhishek Gola
2853bdce0d Merge pull request #30681 from pratham-mcw/sorIdx_opt
core: parallelize sortIdx over independent rows/columns
2026-11-10 17:35:48 +05:30
Abhishek Gola
a0fbf9c283 Merge pull request #30509 from mh-masum6875/docs-drawmatches-python-note
doc: note that Python callers can pass None as outImg in drawMatches/drawKeypoints
2026-11-10 16:21:29 +05:30
Mohammad Sohail Shaikh
55ff746075 Merge pull request #30728 from sohailshk/fix/dnn-matmul-broadcast-packedb (#30728)
dnn: fix packed-B offsets for broadcast batched MatMul

When the constant B of a MatMul has more than one batch slice but fewer than the output batch (B broadcasts over A's leading dims), updatePackedBOffsets derived the packed slice stride from the output batch, so every slice after the first read the wrong packed data. matmul_layer.cpp now passes fastGemmPackBSize(N, K, opt), the size of one packed slice, as the stride.
2026-11-10 08:43:16 +05:30
Abhishek Gola
4bea6a5f0e Merge pull request #30723 from pbkx/fix-knnmatch-output-replacement-4x
features2d: clear knnMatch output before matching
2026-11-10 08:37:21 +05:30
Abhishek Gola
b41241fa41 Merge pull request #30725 from pbkx/fix-phasecorr-roi-padding-4x
imgproc: fix phaseCorrelate ROI padding
2026-11-10 08:36:22 +05:30
Pratham Kumar
db0380a7a0 imgproc: parallelize calcHist using stripe-based parallel_for_ (#30585)
* imgproc: parallelize calcHist using stripe-based parallel_for_

* backport calcHist parallelization from 5.x
2026-11-09 12:21:40 +05:30
NIKHIL
54142329e9 imgproc: fix stackBlur results on full-range 16-bit images 🤖🤖🤖 (#30671)
* imgproc: fix stackBlur results on full-range 16-bit images

The 16-bit SIMD paths overflowed 32 bits in (sum * mul) >> shr and saturated when adding two 16-bit samples before the kernel multiply. Add the samples after widening, and divide as the scalar loops do, so SIMD and scalar agree and the result no longer depends on the thread count.

* imgproc: scale the stackBlur thread test with the machine's thread count

Restore the count with a guard so a throw can't leak it. Use an odd image width: with a width of 160, stripes at some thread counts, including 12, leave nothing to the scalar loop and the test passes on the unfixed code.

* imgproc: use 64-bit sums for large stackBlur kernels on 16-bit images

The largest sum is the largest absolute value times (radius + 1)^2, which no longer fits an int from radius 181 for CV_16U and radius 255 for CV_16S. Those radii now take the scalar loops with int64_t sums. Radii that fit keep the 32-bit SIMD paths.

* imgproc: use 64-bit sums for large stackBlur kernels on 8-bit images
2026-11-09 12:20:20 +05:30
pbkx
9231ce54bf fix phaseCorrelate ROI padding 2026-11-08 14:45:14 -08:00
pbkx
b0af5ebf70 features2d: clear knnMatch output before matching 2026-11-08 14:02:42 -08:00
Alexander Smorkalov
e7d32cb9db Merge pull request #30716 from Kumataro:trial/fix_build_warnings_with_cxx20_4.x
dnn, features2d, imgproc: fix build warnings with GCC 15 / C++20(4.x)
2026-11-08 11:39:52 +03:00
Shiven Solanki
0cbde9ceeb Merge pull request #30646 from sshivensolanki:core-carttopolar-inplace
core: fix in-place cartToPolar when only the magnitude overwrites an input - #30646

Fixes #30645

### Problem

`cv::cartToPolar` gives wrong results on `CV_32F` when only the magnitude output is the same `Mat` as `x` or `y`. The SIMD loop handles the leftover elements by repeating the last full block. In-place calls must skip this, but `cartToPolar32f_` only checked the angle, so the repeated block read magnitudes as inputs.

### Fix

Added `mag == X || mag == Y` to the check, so these calls handle the leftover elements with the scalar code. `polarToCart` and `magnitude` already check all their outputs.

### Tests

New `Core_CartToPolar_inplace_mag.accuracy` for `CV_32F` with lengths 1 to 39: the magnitude overwrites `x`, then `y`, and the results are compared with a call using separate outputs. The existing `Core_CartToPolar_inplace` test overwrites both inputs, so it never reached this case. `CV_64F` is not tested, because it works on separate float buffers and can't hit this bug.

On Apple M1 Pro, 28 of the 39 cases fail without the fix. All pass with the fix, along with the related `cartToPolar`, `polarToCart`, `magnitude` and `phase` tests, with OpenCL on and off.

### 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
2026-11-08 09:16:50 +03:00
Kumataro
173a1cf711 dnn, features2d, imgproc: fix build warnings with GCC 15 / C++20
- dnn: suppress false-positive std::vector::insert warning in ONNX GRU parser
- features2d: simplify indexChange initialization in BRISK kernel generation
- imgproc: fix implicit conversion warnings with INTER_TAB_SIZE in SIMD remap and warp tests
2026-11-08 10:48:56 +09:00
Alexander Smorkalov
ccf4ca3243 Merge pull request #30676 from Lurie97:fix_mapcount
Fix(core): correct UMat mapcount handling in OpenCL path
2026-11-07 21:24:40 +03:00
Alexander Smorkalov
9d4808bef8 Merge pull request #30677 from saanvimundra:fix-commandlineparser-short-key-spec
core: reject CommandLineParser keys with fewer than three fields
2026-11-06 18:21:51 +03:00
Alexander Smorkalov
103f61f252 Merge pull request #30682 from NUAAwqy:docs/deriv-kernel-size-range-4x
docs(imgproc): correct the documented Sobel kernel size range (4.x)
2026-11-06 18:20:12 +03:00
Shiven Solanki
6fa237896a Merge pull request #30668 from sshivensolanki:core-inrange-16f
core: throw an error instead of crashing in inRange on CV_16F #30668

Fixes #30667

### Problem

`cv::inRange` crashed with a segmentation fault on `CV_16F` input. `inRangeTab` has `0` for `CV_16F`, and the code called the returned function without checking it.

### Fix

If no function is found, `cv::inRange` now raises `CV_Error` with `StsNotImplemented` and a message saying that `CV_16F` is not supported, like 5.x does for its unsupported depths.

### Tests

New `Core_InRange.unsupported_depth_throws` checks scalar and array bounds on `CV_16F`. Without the fix, the test program crashes. With the fix, it passes, and all `opencv_test_core` tests pass on Apple M1 Pro.

`inRange` supports `CV_16F` on 5.x, so this test does not throw there. It needs to be removed or changed when 4.x is merged into 5.x.

### 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
2026-11-06 14:01:19 +03:00
jiajia Qian
5f20f48a5b Fix(core): correct UMat mapcount handling in OpenCL path
`u->mapcount` was incremented before `clEnqueueMapBuffer()`.

If mapping failed, the counter remained incremented even though no
mapping was established, leaving `UMatData` in an inconsistent state
and potentially triggering later assertions such as:

    (-215:Assertion failed) u->mapcount == 0 in function 'deallocate'

Update the logic to increment `mapcount` only after a successful
`clEnqueueMapBuffer()` call.

The issue was observed while running:

    OCL_PyrDownFixture_PyrDown.PyrDown/6 from opencv_perf_imgproc.

Assisted-by: LLM
Signed-off-by: jiajia Qian <jiajia.qian@nxp.com>
2026-11-05 17:43:10 +08:00
NUAAwqy
131f1745a9 docs(imgproc): correct the documented Sobel kernel size range
Backport of #30661 to the 4.x branch: getDerivKernels and Sobel accept any odd
aperture size up to 31, not only 1, 3, 5, or 7.
2026-11-04 14:10:07 +00:00
Pratham Kumar
a1f93dd19c core: parallelize sortIdx over independent rows/columns 2026-11-04 18:40:31 +05:30
Saanvi Mundra
e4b73b28e2 core: reject CommandLineParser keys with fewer than three fields
Each key block must have the form "{names | default | help}". The
constructor read the second and third fields without checking that they
exist, so a block such as "{help h}" or "{help h|}" read past the end
of a vector and crashed. Throw a parse error instead, as is already done
for other malformed key strings.
2026-11-04 08:05:08 +00:00
Abhishek Gola
199fd78571 Merge pull request #30351 from spicysharkco/fix/filestorage-release-state
core: fix FileStorage release leaks, state and unbalanced closing
2026-11-03 13:45:51 +05:30
Abhishek Gola
d195a5ad7e Merge pull request #30577 from professor-moody/fix-torch-padding-dim-bounds-4x
dnn(torch): validate nn.Padding dimension and pad bounds
2026-10-30 15:24:05 +05:30
Abhishek Gola
af3b2f2b80 Merge pull request #30432 from sshivensolanki/opt-copymask-8byte
core: SIMD masked copy for 8-byte elements
2026-10-30 13:13:28 +05:30
Shiven Solanki
c7c32d37eb imgproc: fix heap overflow in Laplacian for CV_16F
Laplacian picked the kernel type as max(CV_32F, ddepth, sdepth), which
is CV_16F for a CV_16F image because CV_16F > CV_64F. The 3x3 kernel
was then allocated as CV_16F (18 bytes) and filled with 9 doubles. Use
CV_64F when the source or destination is CV_64F and CV_32F otherwise,
so filter2D rejects the unsupported depth without the overflow.

Add an Imgproc_Laplacian regression test.
2026-10-29 23:24:14 +08:00
Abhishek Gola
5584875dba Merge pull request #30532 from gksks1029/fix/tracker-vit-roi-crop-4x
video: isolate TrackerVit crops from parent images
2026-10-29 19:41:46 +05:30
Abhishek Gola
c55f0e9418 Merge pull request #30445 from 3nK1i/fix/convertmaps-empty-output
imgproc: fix convertMaps with an empty second output
2026-10-29 13:39:54 +05:30
Abhishek Gola
099dde0419 Merge pull request #30452 from pbkx/fix-seamless-cloning-mask-preservation-4x
photo: preserve input masks in seamless cloning APIs
2026-10-29 13:37:55 +05:30
Abhishek Gola
981ff0ff05 Merge pull request #30508 from mh-masum6875/docs-python-manual-signatures
python: add documentation signatures for manually wrapped highgui functions
2026-10-29 13:36:36 +05:30
Abhishek Gola
57a97025ef Merge pull request #30498 from pbkx/fix-tonemap-reinhard-intensity-4x
photo: preserve TonemapReinhard intensity during processing
2026-10-29 12:50:43 +05:30
Nathan Keys
50cfa93293 dnn(torch): validate nn.Padding dimension and pad bounds
Validate the one-based Padding dimension before converting it to an
array index, and reject the minimum integer pad before negating it.
Add a serialized Torch7 regression test for valid and invalid bounds.

Signed-off-by: Nathan Keys <professor.moody@pm.me>
2026-10-28 22:02:46 -05:00
Maidul Hasan Masum
77d9a8e69c python: align setMouseCallback argument names with its keywords
Same change as the 5.x port, to keep the two branches in sync.

The wrapper parses window_name, on_mouse and param, but the cv2.cpp help
text and the typing stub in api_refinement.py both say windowName and
onMouse, so the stub promises keywords the runtime rejects:

    >>> cv2.setMouseCallback(windowName="w", onMouse=cb)
    TypeError: function missing required argument 'window_name' (pos 1)

createTrackbar is left alone: it is registered METH_VARARGS, so its
arguments cannot be passed by keyword at all.
2026-10-28 14:13:46 +00:00
Shiven Solanki
f2efb42906 core: use TEST_P for the 8-byte copyTo/setTo mask test 2026-10-27 18:03:23 +08:00
Shih Kai Siang
58e52e9d3c video: isolate TrackerVit crops from parent images 2026-10-26 23:18:41 +08:00