Commit Graph

27848 Commits

Author SHA1 Message Date
Abhishek Gola
ffd7b6d9d4 Merge pull request #31312 from saanvimundra/fix/commandlineparser-key-validation-5x
core: report malformed CommandLineParser key descriptions
2026-12-02 20:44:04 +05:30
sanjayk9
395a67b1b7 dnn: fix Pow with an integer base and a float exponent (#31280)
* dnn: fix Pow with an integer base and a float exponent

The output keeps the base type, and the exponent was converted to it before
the power was computed, so x^0.5 became x^0. Compute in double and truncate
toward zero, as onnxruntime does.

Florence-2's vision encoder computes sqrt(num_patches) this way to build a
Reshape shape, which made the Reshape fail.

* dnn: call std::pow for Pow with an integer base and a float exponent

A single exponent went through cv::pow, whose exp(y*log(x)) can land one
ulp below an exact integer (4^1.5 = 7.99..), and truncation then gave
7 instead of 8. Compute each element with std::pow, as onnxruntime does.
The new test uses a constant scalar exponent, as Florence-2 does.
2026-12-02 19:36:00 +05:30
Abhishek Gola
fcd8b96e64 Merge pull request #31314 from blank-0007/fix-dnn-cpu-target-warning-30806
dnn: accept DNN_TARGET_CPU on mainGraph when HAVE_CUDA is disabled
2026-12-02 19:25:17 +05:30
Abhishek Gola
a282408291 Merge pull request #31307 from ish1416/fix-gather2-int64-bounds-5x
Problem
In gather2_layer.cpp, CPU gather() casts CV_64S indices to 32-bit int before bounds checking (int k = ind32 ? (int)ind32[j] : (int)ind64[j]), so out-of-range 64-bit indices such as 1LL << 32 or (1LL << 32) - 1 silently truncate to 0 or -1 and gather valid slices instead of raising Error::StsOutOfRange (unlike CUDA GatherOp, which already validates in int64_t). Related to the Gather2 note in #30575.

The error flag volatile bool globOutOfRangeIdx is also shared across parallel_for_ threads without atomicity, and the index bounds check ran inside the nslices loop.

Fix
Keep k and shape_a in int64_t, hoist negative-index normalization and bounds validation out of the nslices loop, guard memcpy on sliceSize > 0, and use std::atomic<bool> for globOutOfRangeIdx. Added regression test Layer_Test_Gather2.Int64IndexBoundsCheck.
2026-12-02 18:15:55 +05:30
Karnajeet Gosavi
659b7829c6 core: Prevent overflow in wide sums of 8-bit inputs (#31255)
On the CPU, reducing a row of 8,421,505 unsigned bytes set to 255 into CV_64F returns -2,147,483,521. The integer accumulator overflows before the result is stored. The correct sum is 2,147,483,775.

This patch uses a double accumulator for signed and unsigned 8-bit input with CV_64F output. For CV_32F, it keeps the existing fast path for lengths that are safe to sum in an int and uses double for longer reductions.

The regression test covers positive overflow and negative underflow on both axes and with both floating-point outputs. All 48 selected CPU reduction tests passed on Windows with MSVC. A separate strided, three-channel check failed before the fix and passed afterward.

The unsigned SUM case overlaps with #31079. This draft also exercises the signed 8-bit paths on 5.x. The 4.x PR covers additional SUM2 and default-output AVG cases. This draft can be reassessed when that change is ported.
2026-12-02 16:35:43 +05:30
Abhishek Gola
6519977a19 Merge pull request #31103 from wzy712/fix-file_storage_overload
Problem
cv2.FileStorage.write() stores any Python integer outside the int32 range as a
boolean instead of a 64-bit integer: YAML gets true, XML/JSON get 1, and
reading the node back yields 1.0. The write(const String&, int64_t)
overload is exposed to Python but is unreachable.

The C++ API is not affected — FileStorage::write(name, (int64_t)value) stores
the exact value, as already covered by FileStorage_exact_type.long_int in
modules/core/test/test_io.cpp.

Root cause
The Python binding resolves FileStorage::write() overloads in declaration
order (modules/core/include/opencv2/core/persistence.hpp):

CV_WRAP void write(const String& name, int val);
CV_WRAP void write(const String& name, bool val);
CV_WRAP void write(const String& name, int64_t val);
For a Python integer outside int32, pyopencv_to(int&) fails the range check
and pyopencv_to(bool&) (modules/python/src2/cv2_convert.cpp, accepts any
integer scalar) consumes the value before the int64_t overload is tried.

Fix
Declare the int64_t overload before bool.
2026-12-02 16:32:53 +05:30
Kaushal Dhaked
7cd2e794c2 dnn: accept DNN_TARGET_CPU on mainGraph when HAVE_CUDA is disabled 2026-12-02 16:24:59 +05:30
Andrei Fedorov
aaaaf213a5 [IPP] Reworked IPP-based pyramids and moved it to HAL (#30417)
* enabling pyrup and prparing pyrdown

* move pyramids to hal

* updated build pyramid

* aligning with 5.x

* removed ipp_buildpyramid
2026-12-02 16:03:34 +05:30
uwezkhan
ca53fa88bd photo: check polyfit coefficients in ccm Polyfit::read 🤖🤖🤖 (#30878)
ASan, ColorCorrectionModel::read + correctImage on a model whose polyfit linearization has deg: 3 and a 1x1 coefficient Mat:

ERROR: AddressSanitizer: heap-buffer-overflow
READ of size 8 in cv::ccm::Polyfit::fromEW(double) linearize.cpp:64
0x609000000a48 is located 0 bytes after 8-byte region
Polyfit::read takes deg and the coefficient Mat p from the file without checking them against each other, and fromEW then reads p.at<double>(d, 0) for every d <= deg. This affects all four polyfit linearizations (LogPolyfit stores a Polyfit). A CV_32F coefficient Mat of the right length overruns the buffer the same way.

The fix checks deg >= 0, a CV_64FC1 coefficient Mat and deg + 1 coefficients in Polyfit::read. This matches what the fitting constructor produces (cv::solve on an n x (deg+1) CV_64F system), so models saved by ColorCorrectionModel::write load as before. The regression test fails on the unpatched tree and passes with the fix. All Photo_ColorCorrection tests pass under ASan with opencv_extra data.
2026-12-02 15:45:13 +05:30
Vladimir Iglovikov
5608a3b4ae core: accelerate interleaved mixChannels permutations 🤖🤖🤖 (#30883)
cv::mixChannels copies each channel pair separately. This patch processes full permutations of a single interleaved matrix into a disjoint output in one pass over pixel blocks.

Use universal SIMD for 2–4 channels with 1-, 2-, or 4-byte elements.
Use dispatched byte shuffles for 5–16 channels on x86 and for 5–8 and 13–16 on AArch64. Start at 1,024 pixels and require at least 16 pixels per iterator plane. The NEON byte-shuffle code requires a 64-bit Arm target. ARMv7 uses the pairwise fallback for these wide byte maps. Preparing a shuffle costs more than it saves on smaller inputs. The AArch64 route for 9–12 channels regressed in the 512 × 512 tests.
Traverse pixels directly for CV_32F, CV_32S, and CV_32U with at least 32 channels and 65,536 pixels. This keeps reads local to each pixel and copies the 32-bit values without conversion. The size threshold avoids the slowdown seen on smaller wide matrices.
Overlap checks use the actual byte ranges of contiguous views and parent bounds for strided views. Partial maps and views that may overlap use the existing pairwise copy order. Identity mappings copy each iterator plane with a size_t byte count.
2026-12-02 15:28:29 +05:30
Ishita Singh
4abaaa33e2 dnn: avoid int64 index truncation in Gather2 bounds check 2026-12-02 15:15:31 +05:30
Nakamura
471c4bc46b dnn: honor pre-13 ONNX Hardmax flattening 🤖🤖🤖 (#31256)
Before opset 13, Hardmax groups every trailing dimension from the selected axis into one reduction. The importer currently applies the modern single-axis rule. Share the existing opset and default-axis handling with Softmax and pass the flattened-tail mode through to the Hardmax layer.

A rank-three input with shape [2,2,3] and axis 1 should produce two ones, one per flattened row. Added a DNN accuracy regression and checked legacy and modern ONNX graphs on the CPU backend.
2026-12-02 14:53:31 +05:30
saanvimundra
4f9fa9d199 core: report malformed CommandLineParser key descriptions
A key without all three parts (names | default | help) read past the end of the split result. Throw StsParseError instead.
2026-12-02 07:16:09 +00:00
SWETANK KUMAR
8b5e51541d dnn: add the ONNX DeformConv operator (#31214)
* dnn: add the ONNX DeformConv operator

Adds a CPU DeformConv layer for the new engine (2D, opsets 19-22). Each
kernel tap samples the input bilinearly at its offset position (corners
outside the image count as zero, like the ONNX reference), the optional
mask scales the samples, and each group is then one fastGemm. group,
offset_group, strides, dilations, pads and the optional B and mask
inputs are supported.

Enables the 4 DeformConv conformance tests and adds two tests for groups,
strides, dilations, asymmetric pads, batch 2, and a mask without a bias.

* dnn: DeformConv review fixes

- compute the 4 corner indices and weights once per (offset group, k, i, j)
  and reuse them for all channels of the offset group (branch-free inner loop)
- read kernel_size/stride/dilation/pad with params.getVector<int>()
- take the output size from convInferShape()

* dnn: DeformConv: keep the im2col buffer in the engine scratch pool, use cvFloor, parallel bias
2026-12-02 11:50:49 +05:30
Abhishek Gola
24d37ecc01 Merge pull request #31291 from poojithparchuri-iiitk/mat-negative-size
Why
In 4.x, setSize has CV_Assert( s >= 0 ) for every dimension. On 5.x, setSize copies the sizes into a MatShape and the check is gone. Mat::create then leaves a matrix without memory and the caller writes into it. I did not find an issue or PR about this.

What I changed
The same check in setSize, with a guard for a null pointer, as 4.x did (5 lines). A size of 0 is still allowed. I added two tests: Core_Mat.create_negative_size (Mat::create and the Mat constructor) and Imgproc_Hist_Calc.regression_negative_hist_size (calcHist with negative bins in 1D, 2D and with a mask, and a normal call afterwards).
2026-12-02 11:33:39 +05:30
Madan mohan Manokar
585746dd60 core: Port 4.x Optimized JacobiSVD to 5.x (#30874)
Changes
Move the Jacobi SVD body into lapack.dispatch.cpp and lapack.simd.hpp, and dispatch it for AVX512_SKX and AVX512_ICL.
Accumulate float dot products in double, and vectorize dotD and givensD for both float and double.
2026-12-02 09:59:38 +05:30
Shiven Solanki
3e729646e6 core: fill the second index for 1D Mat in minMaxIdx (#31276)
Problem
For a 1D Mat, minMaxIdx writes only the first element of minIdx and maxIdx and leaves the second one unset, even though the docs require 2 elements. minMaxLoc hid this by forcing y = 0, which returns (-1, 0) instead of (-1, -1) when nothing is found.

Fix
ofs2idx now also sets idx[1] for a 1D Mat: 0 when a value is found, -1 when not. The y = 0 override in minMaxLoc is removed, so a 1D "not found" result matches 2D.
2026-12-02 09:58:48 +05:30
Shiven Solanki
702832f0c8 geometry: return 0 from contourArea and arcLength for an empty contour (#31285)
Problem
cv::contourArea and cv::arcLength throw an assertion for an empty std::vector contour, because getMat() drops the vector's type before the depth check.

Fix
Return 0 before calling getMat() when the input is empty.
2026-12-02 09:58:14 +05:30
Abhishek Gola
cc07c72547 Add Batch Resize Support (#29830)
batch resize support
2026-12-01 23:18:38 +05:30
Parchuri Poojith Kumar
24f85c241f core: reject negative sizes in setSize, as 4.x does
On 4.x, setSize asserts that every size is not negative. The check is missing on 5.x, where the sizes are copied into a MatShape. Mat::create then accepts a negative size and leaves the matrix without memory, and the next function that writes into it crashes, for example calcHist with a negative number of bins. Restore the check. Add a core test for Mat::create and the Mat constructor, and a calcHist test with negative bin counts in 1D, 2D and with a mask.
2026-12-01 21:32:23 +05:30
Abhishek Gola
af81fbfbb7 Merge pull request #31014 from vrabaud/remove_using_std
Remove std using-declarations and directives from public headers.
2026-12-01 19:52:01 +05:30
Shiven Solanki
6416566e40 Merge pull request #31236 from sshivensolanki/geometry-mst-negative-index
geometry: reject negative node indexes in buildMST - #31236

Fixes #31235

### Problem

`buildMST` only rejected node indexes `>= numNodes`, so an edge with a negative `source` or `target` was used to index `parent` (Kruskal) or `adj` (Prim) out of bounds.

### Fix

Also reject `u < 0` and `v < 0` in the edge check of both `buildMSTKruskal` and `buildMSTPrim`.

### Tests

Added `MSTInvalidInput.negativeNodeIndex`, which checks that both algorithms return `false` for a graph with a negative target and for one with a negative source. It fails without the fix (both return `true`) and passes with it. All 347 tests in `opencv_test_geometry` pass on macOS arm64.

### 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-12-01 16:00:27 +03:00
Abhishek Gola
45d3bc2808 Merge pull request #30462 from varun-jaiswal17/dnn-fastgemm-kernels
Changes
AVX2 fastGemm uses a 6 × 16 micro-kernel instead of 12 × 8: 8 memory reads per 12 multiply-adds instead of 13, the same shape MLAS uses.
On AVX2, a row-major A is read straight from its rows instead of being packed first.
B packing copies a whole row at once when it is contiguous (row-major B), on all platforms.
Attention layer: when there are fewer (batch, head, Q/K/V) projections than threads, each one's rows are split too, so models with few heads use all threads.
The flash-attention softmax from fastGemm optimizations and add flashattention without MLAS #30423 is also built for AVX2.
2026-12-01 17:09:56 +05:30
Prasad Ayush Kumar
14790c2faa dnn: optimize int4 LLM decode models and support Gemma-3 quantized models (#30258)
MatMulNBits kernel. The op was compiling at the SSE3 baseline, so 128 bits on a 512-bit machine. It now has dispatched SIMD kernels (AVX2, AVX-512, NEON) that unpack the int4 weights straight into the dot product instead of dequantising a whole column into a buffer first, and the parallel stripes follow onnxruntime's 16-column policy rather than issuing 269k dispatches per token. Layer_MatMulNBits in perf_layer.cpp covers M=1/16/128 for 4-bit, 4-bit with zero points and 8-bit.
2026-12-01 17:06:51 +05:30
Nakamura
dbe66b4214 dnn: stabilize CPU Softplus for large and small inputs 🤖🤖🤖 (#31257)
The CPU activation computes log(1 + exp(x)), which overflows at x=120 and loses small negative-tail outputs. Use max(x, 0) + log1p(exp(-abs(x))) and compensate rounding of the SIMD logarithm argument. Route the layer fallback through the same dispatched kernel.

A 129-element imported ONNX model with positive and negative tails had 51 discrepancies before and zero after the change. Three focused native Softplus tests passed.
2026-12-01 15:47:23 +05:30
Abhishek Gola
fb09057c67 Merge pull request #31263 from Kumataro/trial/jxl_donot_drop_alpha_ch_for_uniform_opaque_alpha_5.x
imgcodecs(jpegxl): preserve alpha channel on uniform opaque alpha with libjxl >= 0.13 (5.x)
2026-11-30 19:58:44 +05:30
Abhishek Gola
b37f40377e Merge pull request #31265 from abhishek-gola/fix/rvv-boxfilter-reflect-5x
Fix RVV box filter with reflective ROI borders
2026-11-30 19:50:38 +05:30
Madan mohan Manokar
24b378455a imgproc: fix BGR5x52GRAY tail for overlapping buffers (5.x) (#31184)
* imgproc: fix BGR5x52GRAY tail for overlapping buffers (5.x)

- RGB5x52Gray rewinds its final block only when src/dst are disjoint,
  replacing the ineffective src == dst check
- Move rgb2grayBuffersDisjoint() above RGB5x52Gray so it can be shared
- Add regression tests converting into a header aliasing the source for
  BGR(A)2GRAY (8U/16U/32F) and BGR565/555 2GRAY, widths 1..100, IPP off

* imgproc(test): use theRNG() in gray alias test
2026-11-30 18:13:18 +05:30
Abhishek Gola
3854f11cf6 Fix RVV box filter with reflective ROI borders 2026-11-30 18:07:48 +05:30
Kumataro
040009dfce imgcodecs(jpegxl): preserve alpha channel on uniform opaque alpha with libjxl >= 0.13 (5.x)
Starting with libjxl 0.13.0 (libjxl/libjxl#4981), the default frame setting strips alpha channels when all pixels are opaque during lossy encoding, turning 4-channel input images into 3 channels on decode.

Set JXL_ENC_FRAME_SETTING_STRIP_ALPHA to 0 when building against libjxl 0.13.0 or later to keep 4 channels intact, and add parameterized tests covering 8U/16U/32F, transparent/opaque alpha, and quality 95/100.
2026-11-30 21:05:37 +09:00
Madan mohan Manokar
32eb7ee9a0 Merge pull request #29852 from amd/5x_blobFromImages
Optimize blobFromImages NCHW packing with dispatched universal SIMD.
2026-11-30 17:13:36 +05:30
Abhishek Gola
32ad990723 Merge pull request #31186 from guptaaarushg/fix-pfm-locale-independent-header-5x
Port the PFM locale fix from #31071 to 5.x, as requested

When the application's C++ locale uses digit grouping, a dimension of 1234 can be written as 1.234 and decoded as 1. Use std::to_string(int) for the integer header fields without changing any locale settings.

This PR only changes the PFM encoder. No new tests are added, following the review of #31071.

Tested on Windows x64 with MSVC 19.42 in Release mode. The existing PFM test passes.
2026-11-30 16:44:42 +05:30
Abhishek Gola
627ac36238 Merge pull request #31190 from intel-staging/dev/andreyfe1/5.x/ipp_instrumentation
Implemented a check to enable instrumentation for IPP HAL. From 4.x to 5.x
2026-11-30 13:49:23 +05:30
Abhishek Gola
9778f73011 Merge pull request #31233 from sshivensolanki/geometry-sphere-error-cache
Problem
The error-cache check in SphereModelErrorImpl::setModelParameters compares coeff_y and coeff_z with themselves, so a sphere that only moved in y or z reuses the previous sphere's errors.

Fix
Compare the stored center_y and center_z with the new values, the same way center_x and radius are already compared.
2026-11-30 09:43:51 +05:30
Abhishek Gola
93ced79e0b Merge pull request #31249 from sshivensolanki/dnn-hardmax-stale-axis
Problem
Hardmax::forward wrote the normalized axis back into the axis attribute, so a later input of a different rank used the stale index: the wrong axis for higher rank, an assertion for lower rank.

Fix
Store the result of normalize_axis in a local normAxis and pass it to hardmaxApply. The axis attribute keeps the value from the model.
2026-11-30 09:42:49 +05:30
Abhishek Gola
35b5ce1563 Merge pull request #31230 from ChandraguptSharma07/fix-mat-scalar-fill
Sped up uniform 8-bit fills in Mat::setTo
2026-11-29 23:21:47 +05:30
Shiven Solanki
b946499f3b dnn: keep the Hardmax axis attribute unchanged in forward 2026-11-29 23:00:07 +08:00
Shiven Solanki
da39752709 geometry: fix SphereModelError cache check for the y and z center 2026-11-29 19:31:21 +08:00
abhishek-gola
7aae1af9bd dnn: avoid unsafe fork fallback in NonZero death test 2026-11-29 12:13:08 +05:30
Abhishek Gola
7236b399b8 Merge pull request #31207 from lingyicute/5.x
geometry: don't overwrite custom model constraints in SACSegmentation…
2026-11-29 12:08:31 +05:30
Vincent Rabaud
95844c51cb Remove std using-declarations and directives from public headers.
Re-exporting standard math and algorithm symbols from
modules/core/include/opencv2/core/cvstd.hpp into `namespace cv`
caused overload ambiguity between `cv::` array operations and
`std::` scalar templates, and `using namespace std` in `datasets`
and `hdf` public headers leaked `std` into downstream translation
units. Those conflicts previously required extra `const Mat&` and
`const UMat&` overloads of `cv::min` and `cv::max` in
modules/core/include/opencv2/core.hpp.

Drop `using std::min`, `std::max`, `std::swap`, `std::sqrt`,
`std::exp`, `std::pow`, and `std::log` from `cvstd.hpp` (keeping
`using std::abs`), `using std::nullptr_t` from
`cvstd_wrapper.hpp`, and `using namespace std` from
`track_vot.hpp`, `track_alov.hpp`, and `hdf5.hpp`. Remove the
obsolete `Mat` and `UMat` `min`/`max` overloads, qualify affected
calls across OpenCV modules with `std::`, and drop unused
`using std::*` declarations from module sources. Simplify
`std::pow(x, 0.5)` calls to `std::sqrt(x)`, collapse nested
`std::min`/`std::max` chains to initializer-list calls, and
replace constant-bound `min`/`max` pairs with `std::clamp`.
Existing runtime behavior is unchanged.
2026-11-29 00:00:25 +01:00
ChandraguptSharma07
c2296fcb84 Sped up uniform 8-bit fills in Mat::setTo 2026-11-29 00:42:00 +05:30
Abhishek Gola
c685c9a222 Merge pull request #31206 from poojithparchuri-iiitk/qr-encoder-validate-5x
objdetect: forward-port QR encoder parameter validation
2026-11-28 20:16:34 +05:30
Abhishek Gola
9aa8cebea9 Merge pull request #31204 from poojithparchuri-iiitk/clahe-tile-grid-5x
imgproc: forward-port CLAHE tile grid check
2026-11-28 20:15:53 +05:30
Abhishek Gola
5d4d13b610 Merge pull request #31203 from poojithparchuri-iiitk/hough-circles-nan-5x
imgproc: forward-port NaN argument checks in HoughCircles
2026-11-28 19:26:13 +05:30
lingyicute
9012ae4aa3 geometry: don't overwrite custom model constraints in SACSegmentation::segment
Signed-off-by: lingyicute <xlyxinglinyi@gmail.com>
2026-11-28 13:32:55 +00:00
Parchuri Poojith Kumar
aa49235f97 objdetect: validate the QR encoder version and correction level
QRCodeEncoder::create accepted any version and any correction level, and a version outside of [0, 40] or an unknown level made the encoder read or write out of range. Check the version with CV_CheckGE and CV_CheckLE and the level with CV_Check in the constructor, so that the encoder raises an error. This is the same change and the same tests as #31042 on 4.x.
2026-11-28 18:51:48 +05:30
Abhishek Gola
349eca0280 Merge pull request #31192 from Prasadayus/octree_test_rng_seed
ptcloud: make OctreeTest independent of test execution order
2026-11-28 18:11:59 +05:30
Abhishek Gola
10c5b1f5d3 dnn(onnx): add ONNX TensorScatter operator (opset 24) (#30641)
- Implement TensorScatterLayer supporting linear and circular modes along specified axis

- Register TensorScatter in LayerFactory and ONNX importer

- Copy contiguous slice blocks per outer row with std::memcpy, bounded chunking, and nstripes tuning

- Un-denylist 3 official ONNX conformance tests and shield OpenVINO backend

- Add dedicated unit tests for circular wrapping, default indices, int64 bounds, zero-work domains, and chunk scheduling
2026-11-28 16:54:55 +05:30
Shiven Solanki
8bf44dcd8b Merge pull request #31201 from sshivensolanki/dnn-onnx-denylist-cleanup
dnn: remove passing tests from ONNX conformance parser denylist
2026-11-28 16:52:30 +05:30