* 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.
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.
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.
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.
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.
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.
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.
* 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
Ports the fix from #31174 to 5.x, as requested in the maintainer’s comment.
The calibration sample now skips frames with fewer than four ChArUco corners and continues with the remaining views. If no view has enough corners, it prints No calibration patterns found and exits cleanly.
On OpenCV 5.1, the detector returns corners in an (N, 2) array. The sample reshapes them to (N, 1, 2) for the debug drawing call so that even detections with only one to three corners remain visible.
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).
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.
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.
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.
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.
geometry: reject negative node indexes in buildMST - #31236Fixes#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
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.
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.
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.
* 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
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.
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.
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.
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.
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.