Libpng warning fix on Windows #29120
CI warning:
```
Warning: C:\GHA-OCV-3\_work\opencv\opencv\opencv\3rdparty\libpng\pngread.c(4114,21): warning C4146: unary minus operator applied to unsigned type, result still unsigned [C:\GHA-OCV-3\_work\opencv\opencv\build\3rdparty\libpng\libpng.vcxproj]
Warning: C:\GHA-OCV-3\_work\opencv\opencv\opencv\3rdparty\libpng\pngwrite.c(2033,21): warning C4146: unary minus operator applied to unsigned type, result still unsigned [C:\GHA-OCV-3\_work\opencv\opencv\build\3rdparty\libpng\libpng.vcxproj]
```
### 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
- Replaced scalar fallback and legacy CV_SIMD128 with modern scalable CV_SIMD.
- Added support for multi-channel (2/3/4) and 16-bit (ushort/short) configurations.
- Utilized v_select for branchless execution and vx_load_expand for mixed-bitwidth mask handling.
- Updated accuracy and perf tests.
Fix JPEG chroma configuration & Standardize component settings #28667
### Problem
Incorrectly treated Chroma as a single channel. In $YC_bC_r$, chroma must be set in both separate channels ($C_b$ and $C_r$).
### Fix
- Explicit Setup: Configured all three components ($Y$, $C_b$, $C_r$) individually.
- Standardization: Removed reliance on library defaults to prevent undefined behavior.
### 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
Better Durand-Kerner Initialization #29109
While investigating issue #23644, I have found [this paper](https://link.springer.com/article/10.1007/BF01935059) which presents a good initialization for the Durand-Kerner algorithm. Basically the idea is to put the initial points equidistantly on a circle on the complex plane. The radius of the circle is computed as
<img width="607" height="178" alt="image" src="https://github.com/user-attachments/assets/ea31b002-c924-4b93-9334-3e59597c896b" />
Note that the $a_i$ coefficients in that paper are reversed compared to OpenCV. That's where the `(n - i)` in the code comes from.
I have implemented just the mean of the $u_i$'s for the sake of simplicity. That's already enough to make the algorithm converge in all cases I have tested. I have used this to test for convergence for many polynomials of order 2 and 4 and coefficients of different magnitudes:
```cpp
TEST(Core_SolvePoly, large_test)
{
cv::Mat_<float> coefs3(1,3);
cv::Mat_<float> coefs5(1,5);
cv::Mat r;
double prec;
for (int c0 = -20; c0 <= 20; c0++)
{
coefs3.at<float>(0) = c0;
for (int c1 = -20; c1 <= 20; c1++)
{
coefs3.at<float>(1) = c1;
for (int c2 = -20; c2 <= 20; c2++)
{
coefs3.at<float>(2) = c2;
prec = cv::solvePoly(coefs3, r);
EXPECT_LE(prec, 1e-6);
}
}
}
for (int c0 = -10; c0 <= 10; c0++)
{
coefs5.at<float>(0) = c0;
for (int c1 = -10; c1 <= 10; c1++)
{
coefs5.at<float>(1) = c1;
for (int c2 = -10; c2 <= 10; c2++)
{
coefs5.at<float>(2) = c2;
for (int c3 = -10; c3 <= 10; c3++)
{
coefs5.at<float>(3) = c3;
for (int c4 = -10; c4 <= 10; c4++)
{
coefs5.at<float>(4) = c4;
prec = cv::solvePoly(coefs5, r);
EXPECT_LE(prec, 1e-2);
}
}
}
}
}
for (int i = -10; i < 10; i++)
{
coefs3.at<float>(0) = pow(2, i);
for (int j = -10; j < 10; j++)
{
coefs3.at<float>(1) = pow(2, j);
for (int k = -10; k < 10; k++)
{
coefs3.at<float>(2) = pow(2, k);
prec = cv::solvePoly(coefs3, r);
EXPECT_LE(prec, 1e-6);
}
}
}
}
```
This test passes, but I have not committed it because it runs for a couple of seconds.
This fixes#23644 and replaces #29055. I have checked #29055 and it does not pass the test above. It seems to be optimized to the precise polynomial of #23644.
### 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.
- [x] The feature is well documented and sample code can be built with the project CMake
videoio(mjpeg): fix heap-buffer-overflow in put_bits off-by-one resize guard #29113
### Summary
Fix a heap-buffer-overflow (WRITE of size 4) in the built-in MJPEG encoder detected by AddressSanitizer during fuzzing.
Fixes#29112
### Root Cause
`mjpeg_buffer::put_bits` in `modules/videoio/src/cap_mjpeg_encoder.cpp` guards buffer resize with:
```cpp
if ((m_pos == (data.size() - 1) && len > bits_free) || m_pos == data.size())
resize(int(2 * data.size()));
```
When `len == bits_free` the guard is **false** (strict `>`), so no resize happens. The subsequent code then:
1. Subtracts `len` from `bits_free`, making it exactly 0.
2. Enters the `bits_free <= 0` branch and executes `++m_pos`.
3. Writes `data[m_pos]` — now equal to `data[data.size()]` — **out of bounds**.
### Fix
Change `len > bits_free` to `len >= bits_free` so the buffer is grown whenever the current slot will be exactly or more than consumed.
```diff
-if ((m_pos == (data.size() - 1) && len > bits_free) || m_pos == data.size())
+if ((m_pos == (data.size() - 1) && len >= bits_free) || m_pos == data.size())
```
### Verification
Reproducer (1×1 grayscale frame, `CAP_OPENCV_MJPEG`):
```cpp
uint8_t pixel = 0xff;
cv::Mat frame(1, 1, CV_8UC1, &pixel);
int fourcc = cv::VideoWriter::fourcc('M', 'J', 'P', 'G');
cv::VideoWriter writer;
writer.open("/tmp/poc.avi", cv::CAP_OPENCV_MJPEG, fourcc, 25.0, cv::Size(1,1), false);
writer.write(frame);
```
Ran under `-fsanitize=address,undefined`; exits cleanly with no error after this fix.
### Regression Test
`TEST(Videoio_MJPEG, put_bits_no_heap_overflow)` added to `modules/videoio/test/test_video_io.cpp` — opens a `CAP_OPENCV_MJPEG` VideoWriter for a 1×1 grayscale file and writes one frame; asserts `EXPECT_NO_THROW`.
core(rvv): fix v_matmul/v_matmuladd scalable semantics and expand lane-group test coverage #29080
### 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.
- [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. -->
## Platform
SpacemiT X60 (K1), 8-core RISC-V RVV 1.0, VLEN=256, 16GB RAM, OS: Bianbu Linux (kernel 6.6.63), GCC 13.2.0, Build: OpenCV 4.14.0-pre, Release, HAL: YES (RVV HAL 0.0.1)
## Motivation
OpenCV's Universal Intrinsics `v_matmul` and `v_matmuladd` have a semantic bug in the RVV scalable backend (`modules/core/include/opencv2/core/hal/intrin_rvv_scalable.hpp`).
The current implementation uses `v_extract_n(v, 0/1/2/3)` with hardcoded indices, assuming the vector holds exactly 4 float lanes (128-bit fixed). On hardware with VLEN=256 (e.g. SpacemiT K1 / BPI-F3), `v_float32` with LMUL=2 holds 16 lanes. As a result, lanes 4–15 silently reuse the inputs from lanes 0–3, producing wrong results.
OpenCV itself acknowledges this in `modules/core/src/matmul.simd.hpp`:
// v_matmuladd for RVV is 128-bit only but not scalable,
// this will fail the test Core_Transform.accuracy
The RVV scalable `transform_32f` path has been disabled because of this bug. However, the existing `TheTest<R>::test_matmul()` only checked the first 4-lane group (the outer loop was effectively hardcoded to `int i = 0`), so the bug was never caught by CI even on wide-vector backends.
## Modification
**Test fix** (`modules/core/test/test_intrin_utils.hpp`): Expanded `test_matmul()` to iterate over all 4-lane groups:
// Before (only checked lane group i=0)
int i = 0;
for (int j = i; j < i + 4; ++j) { ... }
// After (checks all lane groups)
for (int i = 0; i < VTraits<R>::vlanes(); i += 4)
{
for (int j = i; j < i + 4; ++j) { ... }
}
**Kernel fix** (`modules/core/include/opencv2/core/hal/intrin_rvv_scalable.hpp`): Rewrote `v_matmul` and `v_matmuladd` to process all 4-lane groups correctly. Each group of 4 lanes now independently computes the full matrix multiply using its own `v[i], v[i+1], v[i+2], v[i+3]` inputs. The `transform_32f` RVV path in `matmul.simd.hpp` remains disabled as the autovectorized path shows better performance on current hardware.
## Experiment 1: Bug reproduced on SpacemiT K1 (VLEN=256)
./opencv_test_core --gtest_filter="*intrin*"
Result: `hal_intrin128.float32x4_BASELINE` FAILED with 24 failures, all from lane groups i=4, i=8, i=12 (lanes 4–15).
Representative failures from `v_matmul` (line 1526):
i=4 j=4: actual=158 expected=56
i=4 j=5: actual=166.39999 expected=59.200001
i=8 j=8: actual=314.39999 expected=68.800003
i=12 j=12: actual=512.40002 expected=81.599998
Representative failures from `v_matmuladd` (line 1540):
i=4 j=4: actual=147.5 expected=51.5
i=8 j=8: actual=284.70001 expected=60.700001
i=12 j=12: actual=453.89999 expected=69.900002
Lane group i=0 (j=0..3) passed correctly — confirming the bug only affects lanes beyond the first 4, exactly as expected from the hardcoded `v_extract_n(v, 0/1/2/3)` implementation.
## Experiment 2: Both tests pass after fixing the kernel
./opencv_test_core --gtest_filter='hal_intrin128.float32x4_BASELINE'
[ OK ] hal_intrin128.float32x4_BASELINE (1859 ms)
[ PASSED ] 1 test.
./opencv_test_core --gtest_filter='Core_Transform.accuracy'
[ OK ] Core_Transform.accuracy (819 ms)
[ PASSED ] 1 test.
## Experiment 3: RVV transform path remains disabled (performance regression)
After re-enabling the RVV scalable `transform_32f` path experimentally, benchmarks showed a significant regression vs the compiler-autovectorized scalar path (CV_32FC3):
Size RVV path Scalar path Ratio
640x480 7.83 ms 1.48 ms 5.3x slower
1280x720 23.96 ms 5.17 ms 4.6x slower
1920x1080 53.76 ms 10.12 ms 5.3x slower
The compiler-autovectorized path outperforms the hand-written RVV kernel for this workload, consistent with the original comment in `matmul.simd.hpp`. The `transform_32f` RVV path is therefore kept disabled in this PR. The kernel fix to `v_matmul`/`v_matmuladd` remains necessary for correctness on wide-vector hardware, and the expanded test ensures the bug cannot regress silently in future.
KleidiCV update to verison 26.03 #28744
KleidiCV release: https://gitlab.arm.com/kleidi/kleidicv/-/releases/26.03
Tuned DNN test threshold as resize linear produces slightly different result with the new KleidiCV version.
### 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
randomnormallike_layer.cpp registered itself via CV_DNN_REGISTER_LAYER_CLASS_STATIC at file scope. Nothing else in the translation unit was referenced from elsewhere, so when OpenCV is built statically (BUILD_SHARED_LIBS=OFF, as in the reporter's MSVC build) the linker drops the object file and the static-init registration never runs. The ONNX importer then sets layerParams.type = "RandomNormalLike" but getLayerInstance has no factory for that type, and parsing fails with "Can't create layer of type RandomNormalLike".
Switch to the standard pattern used by every other layer in the module: declare RandomNormalLikeLayer in all_layers.hpp, expose a static create() factory from the .cpp, and register it explicitly from initializeLayerFactory in init.cpp. Because init.cpp is referenced by the DNN module init path, this pulls in the layer .cpp regardless of build mode and the registration always runs.
The failure was incorrectly attributed to MSVC in the bug report. The bug is build-mode sensitive (static vs shared), not platform sensitive.
Verified locally on linux/gcc-13 by building modules/dnn and
opencv_test_dnn against the patched tree, then running opencv_test_dnn --gtest_filter='Test_ONNX_layers.RandomNormalLike_basic/0:Test_ONNX_layers.RandomNormalLike_complex/0'
Both tests pass; without the patch the same binary reproduces the
"Can't create layer of type RandomNormalLike" error from the report.
Update ArUco doc #28824
See https://github.com/opencv/opencv/pull/28823
Update of the ArUco doc but targeted for OpenCV 4.
### 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.
- [x] The feature is well documented and sample code can be built with the project CMake
imgproc: add kernel size validation in boxFilter #29040
Check that ksize dimensions are strictly positive in boxFilter(), returning StsBadSize error instead of producing undefined behavior.
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
RISC-V: add RVV convertScale paths for selected depth conversions #29058
### Summary
This PR extends the RISC-V RVV HAL `convertScale` implementation with optimized paths for selected `convertTo()` depth conversions:
- `CV_32F -> CV_8U`
- `CV_16U -> CV_32F`
- `CV_16S -> CV_32F`
The change is confined to `hal/riscv-rvv/src/core/convert_scale.cpp`. It does not modify the generic `convertTo()` implementation or affect dispatch for non-RISC-V targets.
### Rationale
`Mat::convertTo()` reaches architecture-specific implementations through the HAL `convertScale` interface. Adding these paths in the RVV HAL keeps the optimization in the existing backend layer and avoids introducing RISC-V-specific branches into common OpenCV code.
The selected conversions were chosen based on measured benefit and practical relevance. `CV_32F -> CV_8U` provides the largest speedup, while `CV_16U -> CV_32F` and `CV_16S -> CV_32F` provide consistent improvements for common image-processing data paths.
### Benchmark
Tested on Banana Pi BPI-F3, an 8-core RISC-V board with RVV 1.0 support.
Build and test configuration:
- OpenCV `4.14.0-pre`
- Release build
- RVV HAL enabled
- Compiler: `riscv64-unknown-linux-gnu-g++ 14.2.1`
- Test binary: `opencv_perf_core`
- Test filter: `*convertTo*`
- Samples: `--perf_force_samples=20 --perf_min_samples=20`
Benchmark command:
```bash
./opencv_perf_core \
--gtest_filter=*convertTo* \
--perf_force_samples=20 \
--perf_min_samples=20
```
Each benchmark case was measured with 20 forced samples. The baseline/after comparison was repeated to check run-to-run stability. The optimized conversion pairs showed consistent improvements.
Second-run comparison for the optimized pairs:
```text
OPTIMIZED_PAIRS: 24 cases, gmean 2.6009x
CV_32F -> CV_8U: 16.0718x
CV_16U -> CV_32F: 1.2334x
CV_16S -> CV_32F: 1.1376x
```
`CV_32F -> CV_8U` showed the largest improvement, with speedups in the `14.5x` to `18.8x` range across the tested image sizes, channel counts, and alpha values.
### Notes on Measurement
The initial benchmark run showed noise in conversion pairs not touched by this PR, likely due to board-level variance such as frequency scaling, thermal state, or background scheduling.
A second run showed untouched pairs close to neutral:
```text
UNTOUCHED_OTHER: gmean 0.9941x
```
The optimized conversion pairs remained consistently faster across both runs, with no observed regression in the added RVV paths.
### 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
Rvv core norm #29057Fixesopencv/opencv#29052
### Problem
`Core_Norm/ElemWiseTest.accuracy/0` failed on RISC-V with RVV enabled when computing norm for `CV_16S` data.
The reported failing case was:
```text
src[0] ~ 16sC4 3-dim (1 x 116 x 40)
```
The expected norm result was a large positive `double`, but the RVV path returned an incorrect value:
```text
expected: 3370900308417
actual: -173296
```
This indicates that the problem was not in the public `cv::norm()` API, but in the RVV HAL implementation used for the `CV_16S` L2/L2SQR accumulation path.
### Root Cause
The RVV HAL has a specialized implementation for `CV_16S` L2 norm:
```cpp
NormL2_RVV<short, double>
```
The implementation widens `int16` values, squares them, converts the widened products to `float64`, accumulates them in an `f64m8` vector, and finally reduces the vector to a scalar `double`:
```cpp
auto s = __riscv_vfmv_v_f_f64m8(0, vlmax);
...
auto v_mul = __riscv_vwmul(v, v, vl);
s = __riscv_vfadd_tu(s, s, __riscv_vfwcvt_f(v_mul, vl), vl);
...
return __riscv_vfmv_f(__riscv_vfredosum(...));
```
The bug was in the scalar initializer passed to `__riscv_vfredosum`.
Before this patch, the code created an `f64m1` scalar vector but used the maximum vector length for `e32m1`:
```cpp
__riscv_vfmv_s_f_f64m1(0, __riscv_vsetvlmax_e32m1())
```
This is inconsistent: the vector type is `f64m1`, so the VL used to initialize it must correspond to `e64m1`, not `e32m1`.
objdetect(aruco): fix maxCorrectionBits in predefined dictionaries #29034
This PR fixes the bugs in the creation of some dictionaries and standarizes its construction.
## Bugs
1. **DICT_ARUCO_MIP_36h12_DATA** was incorrectly assigned `maxCorrectionBits=12`, which is the intermarker distance. This was causing a high rate of false positives during detection, which is a significant problem.
2. **APRILTAG** dictionaries were incorrectly created with `maxCorrectionBits=0`, making it impossible to do error correction.
## Solution
Given a intermarker distance X, the correct `maxCorrectionBits = X/2 - 1`. Thus, standardize the construction of Dictionaries as such.
libpng upgrade to 1.6.57 #29051
### 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
Python: add context manager compatibility for VideoCapture and VideoWriter #28967
### Description
This PR implements the context manager protocol (`with` statement support) for `cv2.VideoCapture` and `cv2.VideoWriter` objects in Python.
### Problem
Currently, these classes do not support the context manager protocol, leading to a `TypeError: ... object does not support the context manager protocol` when used with a `with` block. As reported in issue #28956, if an exception occurs before an explicit `.release()` call, the video resource or file remains locked in the system[cite: 298, 309].
### Identification & Motivation
By analyzing the issue and the Python binding structure of OpenCV, I identified that while the core logic resides in C++, the Pythonic behavior can be enhanced by injecting `__enter__` and `__exit__` methods during the module initialization. This ensures that resources are automatically and safely released even if the program execution is interrupted by an error[cite: 298, 325].
### Solution
I have modified `modules/python/package/cv2/__init__.py` to dynamically inject the necessary methods:
1. Defined `_video_enter` to return the object itself (standard context manager behavior).
2. Defined `_video_exit` to trigger the `.release()` method automatically.
3. Injected these methods into `VideoCapture` and `VideoWriter` classes immediately after the `bootstrap()` function to ensure the native C++ classes are correctly loaded into the global namespace.
Fixes#28956
## Summary
Replace the existing RVV HAL FAST-16 implementation (`hal/riscv-rvv/src/features2d/fast.cpp`) with a score-first approach, achieving **2-4x speedup** over the previous HAL implementation on RISC-V hardware.
## Approach
The previous HAL implementation used a count-based approach (XOR trick + per-pixel bitmask scanning + separate cornerScore computation). This PR replaces it with a **score-first** approach that processes multiple horizontal pixels in parallel using RVV vectors.
Key optimizations:
1. **Score-first approach**: Directly compute corner scores via min/max reduction over all 9-arc windows, then threshold on score. This eliminates the arc-counting pass and the separate `cornerScore` function.
2. **u8 to i16 zero-extension**: Zero-extend pixel values to int16 for natural signed comparison, eliminating the XOR-delta trick and preventing score overflow.
3. **vcompress batch output**: Extract all corner indices in one vector operation instead of per-lane bitmask scanning.
4. **vlen-adaptive**: Uses `vsetvl_e16m1` for dynamic vector length — works on any RVV 1.0 implementation regardless of VLEN (128, 256, 512, etc.) without code changes.
## Performance
Benchmarked by maintainer on **Muse Pi v3.0** (GCC, SpacemiT toolchain v1.0.4):
| Test | Previous HAL (ms) | This PR (ms) | Speedup |
|------|-------------------|--------------|---------|
| FAST-20 NMS=true | 23.06 | 7.99 | **2.89x** |
| FAST-20 NMS=true (orig) | 7.31 | 1.80 | **4.06x** |
| FAST-30 NMS=false | 20.10 | 7.75 | **2.59x** |
| FAST_DEFAULT s2.jpg | 76.94 | 19.06 | **4.04x** |
| ORB_DEFAULT chess9 | 64.46 | 25.43 | **2.53x** |
Both NMS=true and NMS=false cases are supported.
## Files Changed
- **`hal/riscv-rvv/src/features2d/fast.cpp`**: Replaced count-based implementation with score-first approach
- No changes to `modules/features2d/src/fast.cpp` or any other files
## Test Plan
- [x] Built with RISC-V cross-compilation toolchain (GCC 14.2, RVV 1.0)
- [x] Tested on QEMU (rv64, v=true, vlen=256) — correct results for both NMS modes
- [x] Maintainer tested on Muse Pi v3.0 hardware — 2-4x speedup confirmed
- [ ] CI passes on all platforms
Fix CMake crash when CUDA arch autodetection comes up empty #28954
With CUDA 13 and a system gcc that the toolkit does not support, every NVCC probe inside ocv_filter_available_architecture fails and the result list ends up empty. The next line then calls list(GET ... -1) on that empty list, so CMake dies with the unhelpful message about list GET given empty list and the user has no obvious next step. This change replaces that path with a fatal error that points at the three real fixes, namely setting CUDA_ARCH_BIN, setting CUDA_HOST_COMPILER, or enabling OPENCV_CMAKE_CUDA_DEBUG to see what NVCC actually printed. It also forwards CMAKE_CUDA_HOST_COMPILER into CUDA_HOST_COMPILER since the issue reporter passed the standard CMake variable and it was being silently ignored.
Fixes#28952
imgproc: add findTRUContours - lock-free parallel contour extraction #28773
Integrates the TRUCO algorithm (Threaded Raster Unrestricted Contour Ownership, @cite TRUCO2026) as a transparent fast path inside `cv::findContours`. No API change is required: existing code automatically benefits when `mode=RETR_LIST` and no hierarchy output is requested.
### How it works
When `mode=RETR_LIST` and the caller does not request hierarchy, `findContours` delegates to the TRUCO parallel engine instead of Suzuki-Abe. All ContourApproximationModes are supported; approximation is applied in parallel after extraction. In all other cases the original Suzuki-Abe path is used unchanged.
### Key design ideas
- Row-strip domain decomposition parallelised via `cv::parallel_for_`
- Start-point ownership rule + speculative downward tracing eliminate tile stitching and synchronisation primitives (lock-free)
- 8-bit state space instead of the 32-bit integer labeling required by Suzuki-Abe, giving higher SIMD throughput and lower memory-bandwidth pressure
- Paged contour buffer (`TRUCOPagedContour`) avoids heap reallocation on the hot tracing path
- SIMD-accelerated row scanning via `cv::v_uint8` intrinsics
- Thread count controlled globally via `cv::setNumThreads()`, consistent with OpenCV conventions
### Output correctness
Significant effort has gone into ensuring the output is identical to the original `findContours` in every respect: same contour set, same ordering, and same approximation results for all methods. A dedicated test suite (`test_contours_truco.cpp`) verifies exact match against Suzuki-Abe across all four `ContourApproximationModes` and thread counts from 1 to 39, using noise images, circles, nested rectangles, and mixed scenes.
### Performance vs. Suzuki-Abe (from submitted paper)
- single-thread: ~1.8–1.9× faster (8-bit SIMD advantage)
- 20 threads: ~14–20× faster on i7-13700H (6P+8E, 20T)
- 20 threads: ~10–12× faster on Xeon Silver 4510 (12C/24T)
### 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.
- [x] The feature is well documented and sample code can be built with the project CMake
Use Xcode DocC tool for buiding Apple platform docs + add quick-start tutorial #28704
### 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
- [x] There is a reference to the original bug report and related work
This PR resolves https://github.com/opencv/opencv/issues/28702 and https://github.com/opencv/opencv/issues/28703
Additionally it resolves build issues on Apple platforms by making build scripts run with Python 3
Add ARMPL support for DFT Function #28664
- This PR introduces hal/armpl/ with implementation of 1D, 2D DFT and DCT routines using ARM Performance Libraries as a custom HAL replacement for OpenCV's DFT & DCT Function.
- ArmPL MSI package is automatically downloaded and extracted via CMake when building on Windows ARM64, with a WITH_ARMPL option that defaults to ON for that platform.
- Forward and inverse real DFT calls in dxt.cpp are routed through ArmPL when available, with scaling applied only when needed.
- Test error thresholds in test_dxt.cpp are relaxed (from 1e-5 to 2e-4 for float ) to account for numerical differences between ArmPL and OpenCV's reference DFT results.
**Performance Benchmarks :**
<img width="993" height="835" alt="image" src="https://github.com/user-attachments/assets/76def647-6d20-4bce-8bc9-7363e723669f" />
- [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
- Implement inrange_simd() covering uchar/ushort/short, chan=1/2/3/4
- Replace legacy CV_SIMD128 run_inrange3 with modern CV_SIMD API
- Extend perf tests to cover all added type/channel combinations
- Resolves TODO introduced in #12608 (2018)
fix: Guard ndsrvp filter center copy when source span is empty #28915
## Summary
This adds a defensive guard around the centre-region `memcpy` in the ndsrvp HAL filter padding path.
**Description**: Multiple memcpy calls in the ndsrvp HAL filter, bilateral filter, and median blur routines use computed sizes (e.g., cnes * (rborder - j), cn * (rborder - j), src_step * height) without validating that the computed byte count fits within the destination buffer. An attacker supplying a crafted image with manipulated dimensions, channel counts, or border parameters can cause the computed copy size to exceed the allocated destination buffer, resulting in a heap buffer overflow that corrupts adjacent memory.
## Changes
- `hal/ndsrvp/src/filter.cpp`
## Verification
- [x] Build passes
- [x] Scanner re-scan confirms fix
- [x] LLM code review passed
---
*Automated security fix by [OrbisAI Security](https://orbisappsec.com)*
cmake: fix PNG status display when BUILD_PNG=ON #28995
### Description
Fixes#28657.
On macOS (and other Apple platforms), `BUILD_PNG=ON` is the default. The build system correctly clears `PNG_FOUND` in `OpenCVFindLibsGrfmt.cmake` and builds libpng from the bundled source. However, during the subsequent module processing phase, a downstream `find_package(PNG)` call — triggered transitively via `include()` in the **same scope** — overwrites not only `PNG_FOUND`, but also `PNG_INCLUDE_DIR`, `PNG_LIBRARIES`, and `PNG_VERSION_STRING`.
#### Root Cause: FindPNG.cmake Has Asymmetric Guards
Reading CMake 4.3's `FindPNG.cmake` (`/opt/homebrew/share/cmake/Modules/FindPNG.cmake`) reveals:
| Variable | Guard? | Fate |
|---|---|---|
| `PNG_LIBRARY` | `if(NOT PNG_LIBRARY)` at line 138 — **guarded** | Preserved |
| `PNG_PNG_INCLUDE_DIR` | `find_path(...)` at line 115 — **no guard** | **Overwritten** |
| `PNG_INCLUDE_DIR` | Derived from `PNG_PNG_INCLUDE_DIR` | **Chain-overwritten** |
| `PNG_LIBRARIES` | Derived from `PNG_LIBRARY` + `ZLIB_LIBRARY` | **Partly overwritten** |
| `PNG_VERSION_STRING` | Parsed from `PNG_PNG_INCLUDE_DIR/png.h` | **Overwritten** |
`PNG_LIBRARY` survives because FindPNG itself checks `if(NOT PNG_LIBRARY)`. But `find_path(PNG_PNG_INCLUDE_DIR)` runs unconditionally — re-searching and overwriting the bundled path with the system one.
#### Fix: Three Coordinated Changes
**Part A — Status guard** (`CMakeLists.txt`): When `BUILD_PNG=ON`, pass `FALSE` as the condition to always show `"build"` regardless of `PNG_FOUND`.
**Part B — Variable lock** (`cmake/OpenCVFindLibsGrfmt.cmake`): After building from bundled source, lock `PNG_PNG_INCLUDE_DIR` as `CACHE INTERNAL`. CMake's `find_path()` checks the cache first — if the variable exists with a valid path, it skips re-searching. The system path is never found.
**Part C — Cache cleanup** (`cmake/OpenCVFindLibsGrfmt.cmake`): Add `PNG_PNG_INCLUDE_DIR` to the `ocv_clear_internal_cache_vars()` call in the `else` branch. When a user switches `BUILD_PNG=OFF`, the cached variable is cleared, allowing `find_path` to search for the system libpng normally. Prevents stale cache leakage across configuration changes.
#### Verification (macOS 26, CMake 4.3, Homebrew libpng 1.6.58)
```
BEFORE downstream find_package(PNG):
PNG_LIBRARY = libpng
PNG_INCLUDE_DIR = .../3rdparty/libpng
PNG_VERSION_STRING = 1.6.37
AFTER downstream find_package(PNG) [with fix]:
PNG_LIBRARY = libpng ← preserved (FindPNG guard)
PNG_INCLUDE_DIR starts with .../3rdparty/libpng ← locked (Part B)
PNG_VERSION_STRING = 1.6.53 ← from bundled png.h
Status display: build (ver 1.6.53) ← correct (Part A)
```
The full reproduction and analysis are in the attached `bugReview/` directory.
### Checklist
- [x] There is a reference to the original bug report and related work
- [x] The test case is in `bugReview/` directory
- [x] Tested on macOS 26 (arm64) with CMake 4.3 + Homebrew libpng 1.6.58
- [x] Cache hygiene verified for BUILD_PNG ON→OFF→ON transitions
flann: fix Index::radiusSearch output size mismatch #28990
## Problem
`Index::radiusSearch` returns `nn` — the number of neighbors found within the radius — but the output arrays `_indices` and `_dists` are always allocated with `maxResults` columns regardless of how many neighbors were actually found. This creates two inconsistencies:
1. When `nn < maxResults`, the output arrays contain stale entries beyond position `nn`, so `nn != indices.cols` and callers cannot rely on the output size to know how many results are valid.
2. When `nn > maxResults`, the return value exceeds the capacity of the output arrays, which have only `maxResults` columns. The extra neighbors were never stored, so the return value is misleading.
The following snippet reproduces both cases:
```cpp
int testFLANN(){
std::vector<cv::Point2f> corners={{3679.83,1857.22},{3324.43,1850.67},{3278.83,1502.32},{3621.32,1508.69},{3662.26,1837.97},{3336.06,1839.28},{3291.74,1516.03},{3608.94,1518.72},{2980.66,1843.22},{2628.11,1837.14},{2607.73,1491.57},{2948.22,1496.76},{2289.31,1830.19},{1943.99,1824.17},{1945.51,1482.34},{2280.68,1487.39},{1607.47,1819.11},{1260.04,1813.26},{1283.94,1470.34},{1620.03,1475.85},{923.063,1808.08},{576.193,1802.4},{624.713,1459.78},{959.715,1464.93},{3270.25,1494.98},{2952.95,1492.19},{2922.75,1190.02},{3231.05,1194.81},{3284.82,1507.62},{2942.74,1502.59},{2912.32,1178.33},{3242.98,1183.19},{2612.82,1496.37},{2276.44,1491.63},{2267.61,1170.13},{2593.64,1174.43},{1949.73,1486.61},{1614.92,1480.64},{1626.77,1160.34},{1952,1165.51},{1289.38,1476.21},{953.709,1470.21},{986.779,1148.92},{1311.98,1154.89},{3567.28,1195.1},{3237.51,1189.03},{3197.63,884.15},{3518.61,888.76},{2918.31,1183.62},{2588.69,1179.37},{2570.64,875.672},{2889.87,878.902},{2271.97,1174.25},{1947.62,1169.61},{1948.56,868.197},{2263.8,872.533},{1630.99,1164.6},{1306.74,1159.52},{1327.81,858.358},{1642.69,862.765},{992.896,1155.52},{666.107,1149.96},{705.246,845.776},{1023.25,851.582},{3204.48,889.981},{2883.49,885.252},{2859.31,593.752},{3175.43,594.736},{2575.86,880.331},{2259.44,876.647},{2252.33,589.235},{2560.47,592.332},{1954.36,873.708},{1636.7,868.068},{1646.93,580.76},{1956.14,584.797},{1332.02,862.624},{1017.11,856.71},{1045.32,572.178},{1350.95,577.635},{3481.36,605.324},{3169.05,601.083},{3138.84,324.116},{3446.12,325.545},{2866.14,599.61},{2555.38,597.142},{2541.51,320.931},{2845.5,322.419},{2256.79,593.253},{1950.17,590.12},{1951.8,317.445},{2250.88,319.418},{1654.16,587.663},{1344.83,582.787},{1362.8,309.253},{1663.89,313.056},{1050.94,577.867},{741.476,571.648},{776.433,300.444},{1076.97,304.56},{3327.05,1847.65},{2977.74,1840.48},{2945.48,1499.68},{3281.82,1504.97},{2630.85,1834.22},{2287.2,1828.06},{2278.56,1489.51},{2610.64,1494.31},{1946.11,1822.05},{1604.75,1816.18},{1617.11,1478.59},{1947.62,1484.48},{1262.96,1810.53},{920.46,1805.05},{956.712,1467.57},{1286.66,1473.27},{3618.7,1511.71},{3281.82,1504.97},{3240.24,1186.11},{3564.22,1192.53},{2945.48,1499.68},{2610.64,1494.31},{2591.52,1176.55},{2915.32,1180.97},{2278.56,1489.51},{1947.62,1484.48},{1949.81,1167.56},{2269.79,1172.18},{1617.11,1478.59},{1286.66,1473.27},{1308.98,1157.53},{1628.88,1162.47},{956.712,1467.57},{627.315,1462.81},{669.943,1146.75},{989.494,1151.86},{3240.25,1186.11},{2915.32,1180.98},{2887.03,881.727},{3200.69,886.725},{2591.52,1176.55},{2269.79,1172.19},{2261.62,874.587},{2573.63,878.324},{1949.81,1167.55},{1628.88,1162.47},{1640.44,864.751},{1950.74,870.259},{1308.98,1157.53},{989.494,1151.86},{1019.41,854.787},{1329.92,860.49},{3515.88,891.68},{3200.69,886.725},{3171.89,598.263},{3478.26,602.785},{2887.04,881.725},{2573.63,878.324},{2558.28,594.392},{2863.1,597.005},{2261.62,874.587},{1950.74,870.259},{1952.4,588.114},{2254.56,591.241},{1640.44,864.751},{1329.92,860.49},{1348.65,579.559},{1650.55,584.209},{1019.41,854.787},{708.649,849.44},{745.388,568.534},{1047.42,574.313},{3171.89,598.263},{2863.1,597.005},{2842.6,325.169},{3141.93,326.654},{2558.28,594.392},{2254.56,591.241},{2248.65,321.425},{2544.55,323.537},{1952.4,588.113},{1650.55,584.209},{1660.07,316.284},{1954.02,319.457},{1348.65,579.559},{1047.43,574.312},{1073.06,307.674},{1366.42,312.707}};
cv::flann::KDTreeIndexParams indexParams(1);
cv::Mat data = cv::Mat(corners).reshape(1, static_cast<int>(corners.size()));
auto index = std::make_shared<cv::flann::Index>(data, indexParams);
int maxResults = 4;
int nTimesError1 = 0; // nn != indices.size()
int nTimesError2 = 0; // nn > maxResults
for (size_t i = 0; i < corners.size(); i++) {
std::vector<int> indices(4);
std::vector<float> dists(4);
int nn = index->radiusSearch(data.row(static_cast<int>(i)), indices, dists, 100, maxResults);
if (nn != (int)indices.size()) { nTimesError1++; }
if (nn > maxResults) { nTimesError2++; }
}
std::cout << "nTimesError1: " << nTimesError1 << std::endl; // > 0 before fix
std::cout << "nTimesError2: " << nTimesError2 << std::endl; // > 0 before fix
return 1;
}
```
## Fix
- Capture the search result in `rsearch_ret` instead of returning early from each `switch` case (this also required adding the missing `break` statements that would otherwise have caused fall-through between type-incompatible distance specialisations).
- Cap `rsearch_ret` at `maxResults` so the return value never exceeds the capacity of the output arrays.
- When `rsearch_ret < maxResults`, trim `_indices` and `_dists` to `query.rows × rsearch_ret` via `colRange(0, rsearch_ret).copyTo(...)` so the output dimensions always match the returned count.