FlattenLayerImpl::finalize previously overwrote _startAxis and _endAxis in place with normalize_axis(..., numAxes) for the rank of the first input. Because end_axis defaults to -1 (and axis can also be negative), this permanently replaced relative negative axes with positive indices bound to the first input rank.
Reusing the same Flatten layer with an input of a different rank then failed in two ways:
Increasing rank (e.g., default axis=1, end_axis=-1: 3D [2, 3, 4] followed by 4D [2, 3, 4, 5]): silently flattened only axes [1, 2] and returned shape [2, 12, 5] instead of [2, 60].
Decreasing rank (e.g., 4D [2, 3, 4, 5] followed by 3D [2, 3, 4]): threw an assertion error in normalize_axis because the stale _endAxis = 3 was out of range for a 3D input.
Fix
Keep _startAxis and _endAxis unmodified in FlattenLayerImpl::finalize, while still validating the normalized axis range (0 <= startAxis <= endAxis < numAxes).
All backends already handle raw axis attributes cleanly: getMemoryShapes, initCann, and initNgraph normalize _startAxis and _endAxis into local variables, and forward, forward_ocl, and initCUDA operate directly on the output shapes.
* dnn: fix int8 depthwise 3x3 convolution with dilation and small heights
The first output column of each row read the input samples at 0 and dilation_w instead of dilation_w - pad_left and 2*dilation_w - pad_left, and with a small height only the top taps were skipped, so the bottom taps read the row below the input. Same change as in the float kernels, applied to the int8 kernels; adds an accuracy test against a direct computation.
* dnn: test int8 depthwise edge cases through the AVX2/LASX vector loop
The test widths 20 and 33 left fewer than 32 outputs, so only the scalar
code of the AVX2 and LASX kernels was run. Use widths 20, 40 and 71 so
that the 32-output vector loop (stride 1, and stride 2 with dilation_w 1)
and the scalar tail both run for the edge configurations.
FlattenLayerImpl::finalize previously overwrote _startAxis and _endAxis
with normalize_axis(..., numAxes) for the rank of the first input.
Since end_axis defaults to -1 (and axis can also be negative), this
replaced relative negative indices with positive indices bound to the
first input rank.
Reusing the same Flatten layer on an input of a different rank then:
- flattened the wrong range of dimensions when rank increased (e.g.
[2, 3, 4, 5] flattened to [2, 12, 5] instead of [2, 60] for default
axis=1, end_axis=-1), or
- triggered an assertion failure in normalize_axis when rank decreased
(e.g. stale end_axis=3 on a 3D input).
getMemoryShapes, initCann, and initNgraph already normalize _startAxis
and _endAxis locally, and forward/forward_ocl/initCUDA use the output
shapes directly. Keep _startAxis and _endAxis unchanged in finalize
while still validating the normalized axis range.
* imgproc: fix RGB2Gray tail for overlapping buffers
The vector kernels cover a remainder by rewinding the final block, which re-reads source pixels. An overlapping destination can overwrite those bytes before the re-read.
Take the AVX-512 kernels only when the source and destination byte ranges are disjoint, and finish an overlapping remainder with the scalar loop. Use 'i <= n - 16' so the loop check cannot overflow for very large rows.
* imgproc: apply disjoint check to all gray conversion tails
- Add rgbRowsDisjoint() helper (byte ranges) shared by the gray kernels
- RGB2Gray (float, ushort, uchar) and RGB5x52Gray rewind the final block
only when src/dst are disjoint, replacing the ineffective src == dst
- Document that overlapping conversion is supported only for dst <= src
- Add regression tests converting into a header aliasing the source for
BGR(A)2GRAY (8U/16U/32F) and BGR565/555 2GRAY, widths 1..100
* imgproc: use shared RNG and drop no-op IPP toggle in gray alias tests
- checkGrayDstAliasesSrc: use theRNG() instead of a fixed-seed local RNG
- rgb5x52gray_dst_aliases_src: remove IPP toggle (no IPP HAL for cvtBGR5x5toGray)
Problem
GatherElementsLayerImpl::finalize normalized the axis attribute by overwriting this->axis with normalize_axis(axis, data.dims).
When the layer was created with a negative relative axis (such as -1, supported by the ONNX GatherElements specification), this replaced the relative index with a positive index fixed to the rank of the first input.
Subsequent evaluations on an input of different rank on the same layer then:
evaluated GatherElements along the wrong axis (e.g. axis 1 instead of axis 2 when moving from a 2D tensor [3, 4] to a 3D tensor [2, 3, 4]), silently corrupting outputs, or
triggered an assertion failure in normalize_axis (axis >= -dims && axis < dims, where axis is 2 and dims is 2) when moving from a higher-rank tensor to a lower-rank tensor (e.g. 3D [2, 3, 4] followed by 2D [3, 4]).
Fix
Keep this->axis unmodified so that relative axis attributes are preserved across evaluations. Store the normalized axis separately in normalized_axis for execution.
Three changes:
intrin_neon.hpp — MSVC versions of v_load_expand / v_pack_store over the raw intrinsics
system.cpp — report FP16 on Windows ARM64, matching the aarch64 branch at line 585. Baseline
features are verified at startup, so without this the library builds and then refuses to run
cpu_fp16.cpp — MSVC ARM64 branch for the check, written with _ARM64_DISTINCT_NEON_TYPES set
so the check and the library agree. The old one did not, which is why it passed while the build
failed
* video: parallelize FarnebackPolyExp and FarnebackUpdateMatrices using parallel_for_
* tune Farneback parallel_for_ stripes and extend tests
* use scoped thread count in Farneback threading test
* hoist Farneback matrices update and parallelize Gaussian flow loop
* bound Farneback PolyExp stripes and consolidate thread test
* add large odd-size case to Farneback multithread test
Replace the std::pow calls with repeated multiplication (decolorPow), which for exponents 0/1/2 is the exact same arithmetic, not an approximation.
Take row pointers (Mat::ptr) instead of Mat::at in both polynomial loops.
Transpose dest/dest1 once in gradvector and read them row-major instead of walking columns.
Thread the full-resolution pass in grayImContruct with parallel_for_ over image rows, the polynomial terms are gathered once up front and each row accumulates independently, so the result is scheduler-independent. Below the element-count cutoff it runs as a single invocation.
Added a perf test (modules/photo/perf/perf_decolor.cpp).
GatherElementsLayerImpl::finalize previously normalized the axis attribute
by overwriting this->axis with normalize_axis(axis, data.dims).
When the layer was created with a negative axis (such as -1, supported by
the ONNX GatherElements specification), this replaced the relative index
with a positive index fixed to the rank of the first input.
Subsequent evaluations on an input of different rank on the same layer then:
- evaluated GatherElements along the wrong axis (e.g. axis 1 instead of axis 2
when moving from a 2D tensor to a 3D tensor), leading to silent data corruption, or
- triggered an assertion failure in normalize_axis (e.g. axis 2 on a 2D tensor
when moving from a 3D tensor to a 2D tensor).
Fix this by keeping this->axis unmodified and storing the normalized axis
separately for execution. Add regression tests covering both decreasing and
increasing rank on the same GatherElements layer instance.
In cv::warpPolar(), the forward path (no WARP_INVERSE_MAP) builds both remap tables, mapx and mapy, in a serial scalar loop over the output rows before calling remap(). Every output row is independent, so this loop can be threaded and vectorized.
TopKLayerImpl::finalize previously normalized the axis attribute by
overwriting this->axis with normalize_axis(axis, input_shape.size()).
When the layer was created with a negative axis (such as the default -1),
this replaced the relative index with a positive index fixed to the rank
of the first input.
Subsequent runs on an input of different rank then either:
- evaluated TopK along the wrong axis (e.g. axis 1 instead of axis 2
when moving from a 2D tensor to a 3D tensor), or
- triggered an out-of-range assertion in getMemoryShapes (e.g. axis 2
on a 2D tensor when moving from a 3D tensor to a 2D tensor).
Fix this by keeping this->axis unmodified and storing the normalized axis
separately for execution. Add unit tests for both increasing and decreasing
rank inputs on the same TopK layer instance.
TopKLayerImpl::finalize previously normalized the axis attribute by
overwriting this->axis with normalize_axis(axis, input_shape.size()).
When the layer was created with a negative axis (such as the default -1),
this replaced the relative index with a positive index fixed to the rank
of the first input.
Subsequent runs on an input of different rank then either:
- evaluated TopK along the wrong axis (e.g. axis 1 instead of axis 2
when moving from a 2D tensor to a 3D tensor), or
- triggered an out-of-range assertion in getMemoryShapes (e.g. axis 2
on a 2D tensor when moving from a 3D tensor to a 2D tensor).
Fix this by keeping this->axis unmodified and storing the normalized axis
separately for execution. Add unit tests for both increasing and decreasing
rank inputs on the same TopK layer instance.
* imgcodecs(jpegxl): preserve alpha channel on uniform opaque alpha with libjxl >= 0.13
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.
* Update warning message to be human readable.
* imgcodecs: fix PFM dimensions under grouped numeric locales
* Keep PFM formatting local and isolate locale regression tests
* Remove locale test and test-runner change as requested
core: preserve solvePoly roots under coefficient rescaling
This PR makes it so that a shared power of two is now applied to scale the internal polynomial coefficients before degree determination and root initialisation. The shift is limited to preserve non-zero components. Leading terms with exactly zero coefficients are removed, while the iteration method, input coefficients and output format are the same as before.
- Route 32F and 64F to blockSum for kernels up to 5x5
- Restore pre-#28224 out-of-place path in blockSum
- Keep the in-place ROI fix from #28224
- Drop float paths unused by fused 3x3/5x5 kernels
Android SDK 36, NDK 30 in 4.x - #31146
CI: https://github.com/opencv/ci-gha-workflow/pull/365
### 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
- [ ] The PR is proposed to the proper branch
- [ ] 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
* imgproc: improve blur and box filter with combined row+column separable filter
- Combined row+column separable filter for small filter sizes (3x3 and 5x5) added to avoid intermediate row buffer storage.
- FilterEngine has been modified to use combined rowColumnFilter.
- Vectorize separable row sums.
- Fix normalized 8U/16U/16S/32S scaling in ColumnSum.
- Pass an inner-region flag to row and column filters.
- Use the fused path on x86 for out-of-place, centered-anchor 3x3/5x5.
- Add AVX512_ICL dispatch for box_filter.
* imgproc: fix in-place boxFilter on ROI
- Drop unused kcn/processInnerRegion column-filter args
- Skip fused path when src and dst overlap
- Add Imgproc_Blur.inplace_roi test
* imgproc: deduplicate box filter kernels
- Share row-slide helpers between RowSum and templates
- Merge ColumnSum specializations
- Share Sum3x3/Sum5x5 setup and tails
- Round CV_16S power-of-two normalization
- Use ptrdiff_t for dst row offsets
- Initialize Cn4 row-sum carry in native lane order
- Keep scalar int -> short column sum on RISC-V (GCC 13 ICE)
* imgproc: run fused box filter on row bands on all platforms
- Split the fused 3x3/5x5 pass into bands of ~256 KB of rows (min 8)
- Fixes the large-image slowdowns vs 4.x; output unchanged
- Route out-of-place 3x3/5x5 32F/64F boxFilter/blur to the fused kernels everywhere, not only x86
- Fixes the 32F slowdowns vs 4.x on Mac M5
* imgproc: address box filter review comments
- Drop always-true processInnerRegion arg from row filters and fillRowData
- Gate 8U/16U/16S fused box kernels on !CV_NEON instead of x86-only
* imgproc: run fused box filter bands in parallel
- Split fused 3x3/5x5 bands across threads when there is >= 1 MB of work per thread
- Fix false src/dst overlap detection that sent the fused path to the row-buffered fallback
* calib3d: fix USAC getLambda out-of-bounds on single support vectors
Fixes#27487
In usac::getLambda(), the median calculation had an inverted odd/even
parity check and accessed supports[size/2 + 1] when size % 2 was
non-zero. When evaluating a single model (supports.size() == 1),
supports[1] was accessed out of bounds, which triggered a debug
assertion (vector subscript out of range) in debug builds and caused
undefined reads in release builds.
This patch:
- Inlines getLambda in usac.hpp without CV_EXPORTS to avoid altering
the 4.x shared library ABI.
- Corrects the median calculation to use supports[size/2] for odd sizes
and (supports[size/2 - 1] + supports[size/2]) * 0.5 for even sizes.
- Guards empty support vectors and clamps denominators to avoid
divisions by zero.
* calib3d: add deterministic test coverage for getLambda
Add direct regression tests in test_usac.cpp:
- Empty support vector returns 1.0 and sets min_non_random_inliers to 1.
- Single-element vector (supports.size() == 1) validates fix against out-of-bounds read and crash.
- Even-sized vector (supports.size() == 4) validates two-middle-element median.
- Odd-sized vector (supports.size() == 3) validates middle-element median.
- Validates denominator handling and min_non_random_inliers when is_independent is true.
This PR replaces it with an 85 compare-exchange network that needs 146 min/max operations. The network is from Bert Dobbelaere's list of median selection networks (https://bertdobbelaere.github.io/median_networks.html), found with his SorterHunter program, and is also in the SorterHunter repository under the MIT License (https://github.com/bertdobbelaere/SorterHunter/blob/master/Networks/Median/Median_25_85_16.json). I checked with Bert Dobbelaere before opening this, and he is fine with it being used here. The PR reorders its compare-exchanges to reduce register pressure on targets with 16 vector registers. Nothing else changes: loads, stores, border and tail handling are untouched. For integer types the output is bit-identical. For floating point it is identical except in the NaN and signed-zero cases described in the notes below.
flann: handle non-multiple of 16 vector sizes in NEON Hamming distance - #31055Fixes#30940
On ARM NEON, \cvflann::Hamming<unsigned char>\ loaded 16 bytes per iteration using \or (size_t i = 0; i < size; i += 16)\ without tail handling. Whenever \size\ was not a multiple of 16, the final iteration read up to 15 bytes past each vector (\ld1q_u8\), adding those unrelated bits to the distance calculation and causing \heap-buffer-overflow\ under AddressSanitizer. This affected AKAZE descriptors (61 bytes) and any non-multiple-of-16 binary feature vector.
### Changes
- Adjust the main loop termination condition to \i + 16 <= size\.
- Process remaining 0..15 tail bytes directly with scalar \cvflann::HammingLUT\ after the vector reduction for both binary vector comparison and the \ZeroIterator\ overload.
- Add regression tests in \ est_hamming.cpp\ verifying tail bounds across vector lengths from 1 to 65 (including AKAZE's 61 bytes) and checking consistency against \cvflann::HammingLUT\ and \cv::norm(..., NORM_HAMMING)\.
### 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
This PR extends the RVV fused rotation implementation from #30057 to three-channel images, including RGB/BGR images.
Three-channel images currently fall back to separate transpose and flip operations for 90-degree rotation. The new implementation combines these operations into a single vectorized pass and writes directly to the final output positions.
It supports 1-, 2-, 4-, and 8-byte channels, corresponding to pixel sizes of 3, 6, 12, and 24 bytes. No public API changes are required.
videoio: fix the scale of grayscale frames in the built-in MJPEG encoder
Raised the tolerance from 10 to 16. The ARM64 difference comes from the encoder, not the decoder: the NEON DCT truncates the quantized coefficients where the scalar code rounds. For this frame the maximum error at quality 75, 90 and 100 is 11, 6 and 7 on AArch64 (under qemu) and 2 on x86. Without the fix the error is 255 at quality 75, so the test still fails on both.
* imgproc: do not put a bogus vertex into the result of approxPolyN
A vertex can only be contracted if the lines of the two edges next to the removed edge meet beyond it. For parallel edges, as in a rectangle, the code marked the vertex with the area FLT_MAX and the point (-1, -1), but still contracted it when nothing else was left, so the point (-1, -1) ended in the result. Nearly parallel edges, like in a regular octagon, gave a vertex billions of units away, because the check for parallel edges used a fixed threshold. Test for parallel edges relative to the edge lengths, treat edges that diverge the same way, and stop when no vertex can be contracted, as the documentation already allows for the epsilon limit. The result for any polygon that could be contracted is unchanged. Add tests and a note to the documentation.
* imgproc: add tests with nearly parallel sides for approxPolyN
The tests with a rectangle and an octagon with integer coordinates only have exactly parallel sides, which the old check for 1e-8 rejected as well. Add a test with a square whose top side is tilted by about 2e-7 radians, which gave a vertex 4e8 units away, and a test with regular octagons computed with float cos and sin for 16 rotations, which gave vertices billions of units away for some of them.
Earlier wrong cv::multiply api usage has been fixed. Scale param has been set to 6 by mistake by passing CV_64F.
cv::abs returns tiny negative value due to float32 sign-bit problem. This issue has been fixed.
Relative errors has been adjusted in perf_dot, perf_stat, perf_moments to avoid introducing new error while changing scale from 6 to 1 in cv::multiply.
The docs list the required order of the 4 object points for SOLVEPNP_IPPE_SQUARE, but do not say anything about the image points. In ippe.cpp (PoseSolver::solveSquare) the image points are used by index, so they must be given in the same order as the object points.
This PR adds that sentence everywhere the object point order is listed (SolvePnPMethod enum, solvePnP, solvePnPGeneric, solvePnPRefine docs and solvePnP.markdown). In solvePnP.markdown I also added that, when the marker faces the camera, this order is top-left, top-right, bottom-right, bottom-left, which is the same corner order returned by ArucoDetector::detectMarkers.
I checked this with a small script: with the same order solvePnP returns the true pose, with reversed image points the rotation is wrong.
Docs only, no code changes.