* 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.
* 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.
* 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.
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.
* 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>
* 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
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.
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
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.
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.
* 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.
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.
* 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
core: fix in-place cartToPolar when only the magnitude overwrites an input - #30646Fixes#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
core: throw an error instead of crashing in inRange on CV_16F #30668Fixes#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
`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>
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.
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.
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>
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.