SVM::predict is dominated by the per-feature kernel reduction over the
support vectors. Vectorize the four reduction kernels in svm.cpp with
universal intrinsics (two independent accumulators + scalar tail):
calc_non_rbf_base (dot product), calc_rbf (squared distance),
calc_intersec (min-sum) and calc_chi2. Same approach as the KNN
findNearest reduction in #29380. Adds modules/ml/perf/perf_svm.cpp
covering the RBF/POLY/INTER/CHI2 kernels.
core: fix Unicode temp path handling on Windows (fix#21960) #28935
## Summary
Fixes getCacheDirectoryForDownloads and related temp file functions failing when the user home directory contains Unicode characters like C:\\Users\\テスト\\AppData\\Local\\Temp.
## Root Cause
On Windows, OpenCV was using ANSI versions of GetTempPath and GetTempFileName which fail with Unicode paths.
## Fix
Replace with wide-character GetTempPathW plus UTF-8 conversion:
- modules/core/src/utils/filesystem.cpp - getCacheDirectory for cache paths
- modules/core/src/system.cpp - temporary file creation
- modules/ts/src/ts_gtest.cpp - test stream capture
## Testing
The fix has been verified compiles. Manual testing on Windows with Unicode username required.
## Risk
Low: Uses same output format, just different encoding path. Existing ASCII functionality preserved.
---
Fixesopencv/opencv#21960
bound alphanumeric values in qr decodeAlpha before map lookup #29378
decodeAlpha in the no-quirc QR backend reads alphanumeric symbols from the post-ECC bitstream and indexes a fixed 45-entry map[] with the raw values. The 11-bit pair from next(11) goes up to 2047, so tuple/45 lands on 45 once the pair passes 2024, and the 6-bit trailing char from next(6) goes up to 63, so map[value] runs out to map[63]. A QR whose data codewords carry an alphanumeric segment with one of those out-of-range values reads past the static array, and the stray byte lands in the string returned by detectAndDecode. WITH_QUIRC defaults off, so this is the decoder a stock build runs.
Before, the only guard was on the encode side, which never emits those values, so the decoder trusted the stream and indexed map[] directly. New version checks value range and return empty string for malformed qr codes.
### Pull Request Readiness Checklist
- [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
- [ ] 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
- [ ] The feature is well documented and sample code can be built with the project CMake
bound tile axis and repeats length in onnx parseTile #29345
OpenCV Extra: https://github.com/opencv/opencv_extra/pull/1385
parseTile sizes repeats_vec from the input-0 rank, then fills it from fields of the model that are never checked against that size. In the tile-1 path the axis taken from the third input indexes repeats_vec directly, and in the tile>1 path the loop writes one entry per element of the repeats tensor. A crafted ONNX with an out-of-range axis, or a repeats tensor longer than the input rank, writes past repeats_vec while loading the model through readNetFromONNX.
The fix runs axis through normalize_axis, the same helper the squeeze and concat paths in this file already use, so a negative or oversized axis is rejected before the write, and it checks the repeats length equals the input rank before the loop. Keeping both bounds in the parser puts the check next to the write instead of trusting the model to be well formed. Before, a repeats tensor shorter than the rank was silently accepted; after, it is rejected, which matches the ONNX rule that repeats carries one entry per input dimension.
- [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
- [ ] 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
- [ ] The feature is well documented and sample code can be built with the project CMake
dnn: SIMD for transcendental activation layers (15 functors) 🧑💻🤖#2937
# dnn: SIMD for transcendental activation layers (15 functors) 🧑💻🤖
### Summary
Many `BaseDefaultFunctor`-based activation functors fall back to the scalar `BaseDefaultFunctor::apply`
— one `libm` call per element. This PR adds vectorized `apply()` overrides (universal intrinsics,
matching the existing `MishFunctor`/`GeluFunctor`/`SigmoidFunctor` pattern, each with a scalar tail) to
the **15 transcendental activations** that have a clean SIMD path:
| functor | uses | | functor | uses |
|---|---|---|---|---|
| TanH | `v_exp` (1−2/(e²ˣ+1)) | | Asinh | `v_log`,`v_sqrt` (sign·log(\|x\|+√(x²+1))) |
| Log | `v_log` | | Acosh | `v_log`,`v_sqrt` |
| Erf | `v_erf` | | Atanh | `v_log` |
| Exp | `v_exp` | | Softplus | `v_exp`,`v_log` |
| Sin | `v_sin` | | BNLL | `v_exp`,`v_log` (max(x,0)+log1p(e^−\|x\|)) |
| Cos | `v_cos` | | GeluApproximation | `v_exp` (tanh) |
| Tan | `v_sin`/`v_cos` | | Sinh / Cosh | `v_exp` |
Functors compile at the baseline SIMD width (SSE on x86, NEON on ARM — same as the existing SIMD
functors). `Sqrt`/`Floor`/`Ceil`/`Round`/`Abs`/etc. are intentionally **not** included — those are
single cheap ops the compiler already auto-vectorizes (measured `Sqrt` at 0.95×). `Asin`/`Acos`/`Atan`
are omitted (no `v_atan`/`v_asin`/`v_acos` intrinsic).
### Performance
Real `opencv_perf_dnn` `Layer_Activation` (added here), 8×256×128×100 = 26.2 M-elem CV_32F blob, A/B
vs the scalar fallback, median speedup:
| functor | M4 clang/NEON | A76 gcc/NEON | Threadripper gcc | Xeon W-2235 gcc | functor | M4 | A76 | TR | Xeon |
|---|---|---|---|---|---|---|---|---|---|
| TanH | 9.1× | 2.3× | 7.3× | 7.3× | Sinh | 3.3× | 3.2× | 5.2× | 5.0× |
| Cos | 8.8× | 3.0× | 3.3× | 3.0× | Acosh | 3.2× | 2.9× | 2.7× | 2.6× |
| Log | 7.8× | 3.0× | 2.5× | 2.4× | Cosh | 2.8× | 3.2× | 2.6× | 2.5× |
| Sin | 7.8× | 3.0× | 3.4× | 2.9× | Exp | 2.4× | 2.5× | 1.4× | 1.5× |
| GeluApprox | 7.6× | 2.4× | 6.6× | 5.8× | BNLL | 4.2× | 2.0× | 1.6× | 1.4× |
| Atanh | 7.0× | 3.6× | 6.0× | 5.2× | Softplus | 2.0× | 2.0× | 3.3× | 2.7× |
| Tan | 6.8× | 3.6× | 6.6× | 6.0× | Erf | 4.2× | 2.4× | 3.9× | 3.5× |
| Asinh | 3.9× | 2.4× | 5.8× | 5.7× | | | | | |
Every functor is a win on every tested out-of-order core (worst case 1.4×). On the **in-order
Cortex-A55** (a55-tuned build) all 15 measure 0.985–0.99× — neutral, within noise: the SIMD
polynomials are dependency-chain-bound, which an in-order pipeline can neither accelerate nor (here)
slow down. So: meaningful wins on out-of-order ARM + x86, no regression on in-order ARM.
### Accuracy
Uses the `v_exp`/`v_log`/`v_erf`/`v_sin`/`v_cos` polynomials OpenCV already ships and relies on (Gelu
via `v_erf`, Mish/Sigmoid via `v_exp`). Verified vs scalar `libm` on 320 K random elements per functor
with domain-correct inputs (Acosh x≥1, Atanh |x|<1, …): **max abs error ≤ 3e-5** (most ≤ 2e-6), zero
elements exceeding rel>1e-3 & abs>1e-4. ONNX conformance and the layer accuracy tests exercise these ops.
### Pull Request Readiness Checklist
- [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 (4.x)
- [ ] There is a reference to the original bug report and related work — N/A (perf improvement)
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable — perf test added (`Layer_Activation`, `SANITY_CHECK_NOTHING`); accuracy covered by existing ONNX conformance/layer tests
- [ ] The feature is well documented and sample code can be built with the project CMake — N/A (internal optimization, no new API)
Fix js ximgproc edge drawing #29387
## Summary
This PR fixes OpenCV.js binding generation for factory functions that return `cv::Ptr<T>` where `T` is a namespaced class exported with a module-prefixed JavaScript binding name.
The failure is reproduced with OpenCV.js plus `opencv_contrib/modules/ximgproc`. The generated binding for `cv::ximgproc::EdgeDrawing` currently contains:
```cpp
.constructor(select_overload<Ptr<EdgeDrawing>()>(&cv::ximgproc::createEdgeDrawing))
```
but `EdgeDrawing` is not available in the generated C++ scope as an unqualified type. The generated constructor should use:
```cpp
.constructor(select_overload<Ptr<cv::ximgproc::EdgeDrawing>()>(&cv::ximgproc::createEdgeDrawing))
```
## Related issues
Fixesopencv/opencv_contrib#4161.
Related to #27963, #28130, and #28143.
#28143 added namespace qualification for factory `Ptr<...>` return types when the inner `Ptr` type matches the generator class key. The remaining `ximgproc::EdgeDrawing` case is different:
```text
inner Ptr type: EdgeDrawing
generator class key: ximgproc_EdgeDrawing
C++ class name: cv::ximgproc::EdgeDrawing
```
Because `EdgeDrawing` does not match `ximgproc_EdgeDrawing`, the previous condition does not handle this case.
## Fix approach
The JS generator now centralizes factory `Ptr<...>` return-type qualification in a helper used by both generator paths:
* `gen_function_binding_with_wrapper`
* `gen_function_binding`
The helper keeps the existing behavior for already qualified types and for the existing class-key match. It additionally handles the case where the inner `Ptr` type matches the basename of the C++ class name:
```text
cv::ximgproc::EdgeDrawing -> EdgeDrawing
```
This allows the generator to emit `Ptr<cv::ximgproc::EdgeDrawing>` for `createEdgeDrawing()` without changing generated files directly.
## Necessity as an opencv code change
The failing API is exposed by `opencv_contrib/modules/ximgproc`, but the invalid C++ line is emitted by OpenCV core's JavaScript binding generator in `modules/js/generator/embindgen.py`.
A contrib-only workaround would have to change the `ximgproc` public declaration or special-case the JS export list for `createEdgeDrawing`. That would only work around one symbol and would not fix the generator's handling of namespaced factory `Ptr` return types. The generator already has the class metadata needed to produce the correct fully qualified C++ type, so the fix belongs in OpenCV core.
## Verification
Tested with:
* OpenCV core `4.x`
* opencv_contrib `4.x`
* Emscripten `6.0.1`
* CMake generator: Ninja
* Build list: `core,imgproc,imgcodecs,video,calib3d,ximgproc,js`
Generator target:
```bash
emcmake cmake \
-S /path/to/opencv \
-B /path/to/build \
-G Ninja \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_CXX_STANDARD=17 \
-DOPENCV_EXTRA_MODULES_PATH=/path/to/opencv_contrib/modules \
-DBUILD_LIST=core,imgproc,imgcodecs,video,calib3d,ximgproc,js \
-DBUILD_SHARED_LIBS=OFF \
-DBUILD_opencv_js=ON \
-DBUILD_TESTS=OFF \
-DBUILD_PERF_TESTS=OFF \
-DBUILD_EXAMPLES=OFF \
-DBUILD_DOCS=OFF
ninja -C /path/to/build gen_opencv_js_source
```
This generated the expected binding:
```cpp
.constructor(select_overload<Ptr<cv::ximgproc::EdgeDrawing>()>(&cv::ximgproc::createEdgeDrawing))
.smart_ptr<Ptr<cv::ximgproc::EdgeDrawing>>("Ptr<ximgproc_EdgeDrawing>")
```
The same patch was also verified with the full OpenCV.js target:
```bash
ninja -C /path/to/build opencv.js
```
fix MSVC warning for minMaxIdx_simd #29379
### 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
- [ ] 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.
- [x] The feature is well documented and sample code can be built with the project CMake
Perf test for gemm #28706
OpenCV Extra: https://github.com/opencv/opencv_extra/pull/1336
- Added perf test to verify gemm performance.
- small sizes, square & rectangular matrix shapes are added.
- special case of n=1 and m=1 are added.
### 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
- [ ] 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
Vectorize the per-sample squared-Euclidean distance in
BruteForceImpl::findNearestCore with universal intrinsics (two
independent v_fma accumulators + scalar tail). The scalar reduction
accumulates in float in strict order, which the compiler cannot
auto-vectorize without -ffast-math; independent SIMD accumulators
break that serial-accumulation dependency.
Accumulates in float exactly as before (only summation order changes,
~1e-7, below stored float precision); selected neighbors and distances
matched scalar on all test data, ML_KNearest tests pass. Real
findNearest A/B: 3.76x M4, 3.47x Threadripper, 3.73x Xeon, 4.10x A76,
2.82x A55 (in-order).
Adds modules/ml/perf with a findNearest perf test.
Migrate the ushort specialization from CV_SIMD128 to (CV_SIMD ||
CV_SIMD_SCALABLE), enabling AVX2/AVX512/RVV widths instead of 128-bit only.
uchar specialization left at CV_SIMD128 — initial migration regressed on
RVV (Muse Pi v3.0, 0.77~0.85x) when vlanes16 == TILE_SIZE collapses the
SIMD loop to one iteration and per-tile setup overhead dominates.
- replace v_int32x4/v_uint32x4/v_uint64x2 with scalable v_int32/v_uint32/v_uint64
- iota vector in static const sized by VTraits::max_nlanes (initialized once at program load)
- drop buf64; use v_reduce_sum(v_uint64) directly (defined on all backends)
- vx_cleanup() at operator() tail for RVV vsetvl hygiene
Fast-path transposeND for identity and 2D transpose orders #29172
### 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
- [ ] 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.
- [x] The feature is well documented and sample code can be built with the project CMake
<!-- Note!!! If you are an automated agent, we have a special process for you: add 🤖🤖🤖 to the end of the PR title. -->
This PR adds fast paths to cv::transposeND() for two common cases:
- identity permutation: dispatch to copyTo()
- 2D permutation {1, 0}: dispatch to transpose()
All other permutations continue to use the existing generic ND implementation.
Why:
transposeND() currently falls back to the generic memcpy/index-update loop even for the common 2D transpose case, while OpenCV already has an optimized transpose() path. Reusing that path avoids unnecessary index arithmetic and improves performance for 2D inputs passed through transposeND().
Performance:
[BinaryOpTest.transposeND/21 (1920x1080, 8UC3): 28.21 ms -> 0.66 ms (-97.7%)]
[BinaryOpTest.transposeND/22 (1920x1080, 8UC4): 37.61 ms -> 0.88 ms (-97.7%)]
[BinaryOpTest.transposeND/29 (1920x1080, 32FC1): 10.26 ms -> 0.75 ms (-92.7%)]
Full transposeND perf subset: 6760 ms -> 592 ms (-91.2%)
guard the parsePadding NHWC swap on paddings.total()==8 and require the parseResize size tensor to hold height and width, matching the existing parseStridedSlice check
core: Vectorize meanStdDev #29339
- Add SIMD SumSqr_SIMD reductions (previously scalar) plus AVX-512 dispatch for the mean TU.
- Uses universal intrinsics, so all SIMD backends benefit.
### 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
- [ ] 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.
- [x] The feature is well documented and sample code can be built with the project CMake
FileNode::operator double() and operator float() read an INT node via readInt()
(32-bit), truncating values above INT_MAX -- e.g. an integer 6662329666 from an
externally-produced json/yaml/xml is read back as -1927604926. The node stores
the value as int64 (operator int64_t() already reads it correctly via readLong),
so use readLong() for the floating-point conversions too. Values that fit in
int32 are unchanged (sign-extended); larger ones are now correct.
Reader side of #29363 (the writer side was #29364).
dnn: optimize blobFromImages using NEON intrinsics on ARM64 #29316
- This PR optimizes the HWC-to-NCHW conversion in blobFromImages() by adding NEON implementation.
- On x64, the MSVC compiler automatically vectorizes the existing scalar implementation, resulting in significantly better performance.
- On Windows ARM64, MSVC does not auto-vectorize this stride-3 access pattern, leading to a noticeable performance gap compared to x64.
- Added CV_NEON macro guard to ensure SIMD optimization is enabled on ARM64 architecture, leaving behavior on other platforms completely unchanged.
**Performance Improvements**
- This optimization significantly improves the performance of HWC-to-NCHW conversion on Windows ARM64.
<img width="823" height="254" alt="image" src="https://github.com/user-attachments/assets/84b22deb-22da-4607-8009-3405c2529b80" />
- [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
- Replace the fixed-128-bit per-depth minMaxIdx kernels with a single templated universal-intrinsic core
- added simd dispatch AVX-512 dispatch
- A dual-accumulator inner loop added
Uses universal intrinsics, so all SIMD backends benefit.
Follow-up to the recent "reject under-length raw exif profile" change.
The declared length in a PNG raw exif profile (tEXt/zTXt "Raw profile type
exif" chunk) is fully attacker controlled. The < 6 guard stops the underflow,
but a large positive value still passes it and reaches HexStringToBytes(),
which does raw_data.resize(expected_length) before reading anything. So a few
bytes in a text chunk can force a ~2GB allocation -> easy memory-amplification
DoS while decoding an otherwise small PNG.
The payload is hex encoded (two characters per byte), so a valid length can
never exceed the profile text carrying it. Reject any declared length greater
than profile_len. This bounds the allocation to the input size and doesn't
reject any valid profile; the valid decode path is unchanged.
imgproc: optimized LUT and equalizeHist with SIMD #29250
- optimized lut with SIMD
- support equalizeHist with v_lut
### 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
- [ ] 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.
- [x] The feature is well documented and sample code can be built with the project CMake
Improved color convert and AVX512 dispatch added #28992
### 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
- [ ] 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.
- [x] The feature is well documented and sample code can be built with the project CMake
Optimization ArUco: get border errors in one pass for both normal and inverted markers #29329
This PR is a follow up to optimization in https://github.com/opencv/opencv/pull/29267.
## Context:
When detecting inverted markers, we call `_getBorderErrors` twice:
- `int borderErrors = _getBorderErrors(cellPixelRatio, ...);`
- `Mat invCellPixelRatio = 1.f - cellPixelRatio;`
- `int invBError = _getBorderErrors(invCellPixelRatio, ...);`
meaning:
1. Scan border cells once.
2. Allocate a new Mat.
3. Invert the entire `cellPixelRatio` matrix, not just the border.
4. Scan border cells again on the inverted matrix.
5. If inverted marker is better, copy the full inverted matrix back
## Solution
only call `_getBorderErrors` once and compute both
- borderErrors: `cellPixelRatio > validBitIdThreshold`
- invBorderErrors: `1 - cellPixelRatio > validBitIdThreshold`
This saves:
1. full invert into temporary Mat: (`Mat invCellPixelRatio = 1.f - cellPixelRatio;`)
2. scan temporary border: the second `_getBorderErrors`
3. copy temporary Mat back into `cellPixelRatio`: `invCellPixelRatio.copyTo(cellPixelRatio);`
Note that the solution does not implement:
```
if(params.detectInvertedMarker) {
_getBorderErrorsBoth(...);
} else {
borderErrors = _getBorderErrors(...);
}
```
because the extra cost to computing invBorderErrors: `if(1.f - ratio > validBitIdThreshold) invBorderErrors++;` is negligible. this also avoids having to maintain two functions: `_getBorderErrorsBoth` and `_getBorderErrors`
## Tests:
No visible results when testing the full marker detection pipeline because this step is not expensive. There is a roughly 8% noise when re-running the marker detections making it hard to spot small speed diffs.
When testing only this specific step with a float matrix of size: `(markerSize + 2*border)^2` on a AMD Ryzen 7 (8 cores / 16 threads):
- The new code is 30-45× faster at this stage depending on the marker size and whether the candidate was actually an inverted one, saving ~530-580 ns per candidate, mainly because we removed `Mat invCellPixelRatio = 1.f - cellPixelRatio`
- The new code is equivalent when detecting non-inverted markers +/- 3 ns
---
### 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
Restricting the condition with _M_IX86/_M_X64 so it only applies to x86/x64 MSVC builds. MSVC ARM64 now falls through to the existing `#else` branch, which already has a portable CV_SIMD-based exp32f/exp64f implementation
**Performance Benchmarks:**
<img width="976" height="486" alt="image" src="https://github.com/user-attachments/assets/62daf2c3-34ac-4fc7-92d0-268073f746f3" />
- [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
More use of AutoBuffer #28907
When possible, AutoBuffer should be faster than std::vector<>, and should not be worse if it requires a heap allocation rather than a stack allocation.
### 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
- [ ] 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
Reject initializers whose declared shape claims more elements than the tensor payload (raw_data or a typed *_data field) actually holds, before the Mat copy/convert reads them.
Fix remap nearest rounding #29145
Thanks, I checked the Windows x64 test logs. The imgproc failures are from the OpenCL `Remap_INTER_NEAREST` tests with `(16SC2, 16UC1)` maps. I missed the OpenCL fixed-point path in the first patch.
I updated `modules/imgproc/src/opencl/remap.cl` to use the same nearest rounding condition as the CPU path. This should address the OCL remap failures.
The `opencv_test_video` failure seems unrelated to this PR (`ECCfixtures/Video_ECC.accuracy/6` invalid memory access), since this PR only touches remap rounding in imgproc.
### 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
- [ ] 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
imgcodecs(pam): fix out-of-bounds write when reading 2-channel PAM #29296
While poking at the PAM decoder I noticed basic_conversion() writes past the
end of the destination buffer when a GRAYSCALE_ALPHA (2 channel) image is read
with IMREAD_GRAYSCALE.
The 1-channel branch was written as if the destination had 3 channels:
for( ; s < end; d += 3, s += src_sampe_size )
d[0] = d[1] = d[2] = s[layout->graychan];
So for every source pixel it writes 3 bytes and advances d by 3, even though
the output row only has m_width bytes (1 channel). With m_channels == 2 that
ends up writing ~1.5 * m_width bytes per row, which runs off the row and, on
the last row, off the end of the Mat. m_width is taken straight from the file
header (up to 2^20), so the overflow size and contents are attacker controlled.
It's reachable with a plain imread(file, IMREAD_GRAYSCALE) on a crafted file.
While looking at it I also realised the loop bound was off for any multi
channel source: end was set to src + src_width, but the source has
src_width * channels samples, so it only ever processed m_width/channels pixels
instead of all of them. That's why GRAYSCALE_ALPHA / RGB_ALPHA come out only
partially filled.
Fix both at once:
- end now covers the whole row (src_width * src_sampe_size)
- the 1-channel branch writes one byte and advances d by 1
For the common grayscale->color case (channels == 1) the new end is identical
to the old one (m_width * 1 == m_width), so that path is byte for byte the same
and the existing PAM read_write test is unaffected. The only outputs that
change are the GRAYSCALE_ALPHA/RGB_ALPHA conversions, which were already broken.
Added a regression test (Imgcodecs_Pam.decode_graya_as_gray) that builds a small
2-channel PAM with an odd width, decodes it as grayscale and checks the result
matches the gray channel. It overflows/crashes on the old code and passes now.