After the first document, YAMLParser::parse() expects the next one to
start with '---'. A line that starts with an alphanumeric character is
rejected with "The YAML streams must start with '---', except the first
one", but a line that starts with '-' and is not '---' is neither
consumed nor rejected, so the loop that looks for the next document
never advances and FileStorage::open() does not return.
Report the same parse error for such a line.
* core: do not pass empty input to HAL minMaxIdx
cv::minMaxLoc and cv::minMaxIdx on an empty CV_8U Mat crashed with
SIGSEGV on ARM64 builds that use KleidiCV: the HAL min/max location
wrapper reads src_data[offset] when a min or max value is requested, and
src_data is NULL for an empty Mat. The generic code already returns zero
values and -1 indices for empty input, so skip the HAL calls then.
* core: fix comment on empty input in minMaxIdx
* core: return early for empty input in minMaxIdx
Check the input for emptiness at the top of cv::minMaxIdx and return zero
values and -1 indices, instead of skipping only the HAL calls. This also
covers a default constructed Mat (dims == 0) and empty UMat. Add a test
for cv::Mat().
core: vectorize masked mean for 8-bit inputs.
The cv::mean() function is currently implemented with scalar loops for 8-bit masked inputs on the CPU fallback path.
This PR provides a Universal Intrinsics reduction-based implementation for 1-4 channel inputs.
The sample allocated C as (|A.rows - B.rows| + 1) x (|A.cols - B.cols| + 1) and copied the top-left corner of the inverse DFT into it. That is neither the full nor the valid convolution. Allocate C with the full convolution size (A.rows + B.rows - 1) x (A.cols + B.cols - 1), which matches the DFT size used below.
Fixes#4558
* core: fix solveLP floating-point drift producing infeasible solutions
* core(lpsolver): tighten pivot-eps comment per review (drop issue ref, note cost)
* core(lpsolver): snap cancellation noise relative to the operands
Replace the fixed 1e-12 cutoff on the whole tableau with a relative test on
the subtraction that updates it. A fixed cutoff turns legitimate small data
into zeros (right-hand sides around 1e-14 were returned as z = 0), while the
relative test removes only results that are within rounding noise of the
values being subtracted.
Add small_magnitude_data, which fails with the fixed cutoff.
* core(lpsolver): snap cancellation noise when restoring objective after Phase I
When any constraint has a negative right-hand side, initialize_simplex() runs Phase I and then rebuilds the original objective from old_c and the Phase I tableau before entering Phase II inner_simplex(). Snap cancellation noise in those updates consistently with pivot() so that exact-zero checks in Phase II are not distorted by residual rounding error.
Add negative_rhs_restore_cancellation regression test.
* core(lpsolver): compare the regression tests with their exact optima
issue_12343 has the unique optimum z = (16, 15, 0, 24)/37, objective
189/37. Compare z with it through cvtest::norm, as regression_basic does.
Checking only the status and the constraints passes for any feasible
point reported as SOLVELP_SINGLE.
Compare small_magnitude_data with its exact solution as well, and check
that the point returned by negative_rhs_restore_cancellation lies on its
optimal segment. Assert the status first in all three tests.
Inline add_snap_zero, which had one caller, and drop an example noise
magnitude from the sub_snap_zero comment that does not hold in general.
* core(lpsolver): pivot the Phase I auxiliary variable out on a nonzero entry
When Phase I ends with the auxiliary variable x0 basic at value 0,
initialize_simplex() makes it nonbasic by one degenerate pivot. It always
pivoted on the first column of x0's row, but that entry can be 0. With
cancellation noise snapped to exact zeros this happens often: the pivot
divides by 0 and solveLP returns SOLVELP_UNBOUNDED for bounded problems.
Pivot on the entry of largest magnitude instead.
Add phase1_auxiliary_basic_at_zero, which returned SOLVELP_UNBOUNDED.
* core(lpsolver): guard zero Phase I pivot row and snap v updates
* core(lpsolver): snap each restored objective coefficient once
After Phase I, each coefficient of the original objective is rebuilt as a
sum of terms. Add up each column and the absolute values of its terms, and
set the coefficient to 0 once, when it is at most 1e-12 times that
absolute sum, instead of snapping after every term.
The objective value v is never compared or returned, so its updates go
back to plain additions. The doc comment of initialize_simplex() now
lists SOLVELP_LOST.
Port of #30003 (5.x) to 4.x. The scalar step of sum_() added four elements to each other in the source type before the double accumulator, so 32-bit values overflowed.
core: fix in-place cartToPolar when only the magnitude overwrites an input - #30646Fixes#30645
### Problem
`cv::cartToPolar` gives wrong results on `CV_32F` when only the magnitude output is the same `Mat` as `x` or `y`. The SIMD loop handles the leftover elements by repeating the last full block. In-place calls must skip this, but `cartToPolar32f_` only checked the angle, so the repeated block read magnitudes as inputs.
### Fix
Added `mag == X || mag == Y` to the check, so these calls handle the leftover elements with the scalar code. `polarToCart` and `magnitude` already check all their outputs.
### Tests
New `Core_CartToPolar_inplace_mag.accuracy` for `CV_32F` with lengths 1 to 39: the magnitude overwrites `x`, then `y`, and the results are compared with a call using separate outputs. The existing `Core_CartToPolar_inplace` test overwrites both inputs, so it never reached this case. `CV_64F` is not tested, because it works on separate float buffers and can't hit this bug.
On Apple M1 Pro, 28 of the 39 cases fail without the fix. All pass with the fix, along with the related `cartToPolar`, `polarToCart`, `magnitude` and `phase` tests, with OpenCL on and off.
### 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
core: throw an error instead of crashing in inRange on CV_16F #30668Fixes#30667
### Problem
`cv::inRange` crashed with a segmentation fault on `CV_16F` input. `inRangeTab` has `0` for `CV_16F`, and the code called the returned function without checking it.
### Fix
If no function is found, `cv::inRange` now raises `CV_Error` with `StsNotImplemented` and a message saying that `CV_16F` is not supported, like 5.x does for its unsupported depths.
### Tests
New `Core_InRange.unsupported_depth_throws` checks scalar and array bounds on `CV_16F`. Without the fix, the test program crashes. With the fix, it passes, and all `opencv_test_core` tests pass on Apple M1 Pro.
`inRange` supports `CV_16F` on 5.x, so this test does not throw there. It needs to be removed or changed when 4.x is merged into 5.x.
### 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
`u->mapcount` was incremented before `clEnqueueMapBuffer()`.
If mapping failed, the counter remained incremented even though no
mapping was established, leaving `UMatData` in an inconsistent state
and potentially triggering later assertions such as:
(-215:Assertion failed) u->mapcount == 0 in function 'deallocate'
Update the logic to increment `mapcount` only after a successful
`clEnqueueMapBuffer()` call.
The issue was observed while running:
OCL_PyrDownFixture_PyrDown.PyrDown/6 from opencv_perf_imgproc.
Assisted-by: LLM
Signed-off-by: jiajia Qian <jiajia.qian@nxp.com>
Each key block must have the form "{names | default | help}". The
constructor read the second and third fields without checking that they
exist, so a block such as "{help h}" or "{help h|}" read past the end
of a vector and crashed. Throw a parse error instead, as is already done
for other malformed key strings.
The non-integer power paths of cv::pow (sqrt for +-0.5, log/exp otherwise)
only distinguish CV_32F from everything else, so every other depth was
processed as CV_64F: an 8U/8S/16U/16S/16F/32S buffer was read and written
as doubles, past the end of both src and dst.
Compute those depths in CV_32F (CV_64F for CV_32S, so every value stays
exact) and convert the result back to the source type.
FileStorage::Impl::~Impl() calls release(), and release() can throw: for
example workaround() reports an empty key of a delayed Base64 sequence.
WriteStructContext::~WriteStructContext() calls endWriteStruct(), which
throws when the structure was already closed by hand or never opened. A
destructor is noexcept, so either exception ended the process.
Catch it in both destructors and log a warning instead, as other
destructors in OpenCV do. When release() throws in ~Impl(), call it a
second time, as FileStorage::open() does when opening fails: the first
call has already dropped the delayed structure that made it throw, so
the second one writes the rest of the file. ~Impl() then closes the
file in case both calls threw.
elf_aux_info() returns non-zero on failure and leaves the output
buffer untouched. The ppc64 CPU feature detection reused one variable
for both AT_HWCAP and AT_HWCAP2, so if the AT_HWCAP2 lookup failed the
AT_HWCAP value was tested against the PPC_FEATURE2_* bits. Use a
separate variable for AT_HWCAP2 and treat a failed lookup as no
features available.
Impl::release() skipped the delayed struct (a sequence still waiting for
its first write in Base64 mode) when only the root was on the stack, so
its key leaked and the sequence was missing from the output. Resolve it
first. Reset the public FileStorage::state in release(),
releaseAndGetString() and a failed open(). An unbalanced endWriteStruct()
or closing bracket now throws and keeps the root on the stack; popping
the root made the next flush() read past the empty stack.
startNextStream() now resets the root in place instead of popping it.
A keyless writeRaw() of data into a map now throws in Base64 mode, as
it does without Base64. At the top level it opened a Base64 writer that
was never freed, and in a nested map after a closed structure it wrote
output that could not be read back.
Fixes#30338
core: fix wasm SIMD float rounding - #30213
Summary
- Fix rounding in the WebAssembly SIMD implementation of `v_round(const v_float32x4&)`.
- Add regression tests for positive and negative halfway values.
Motivation
The previous implementation added `0.5` before truncating, which caused incorrect results for some negative values and halfway cases.
This change uses `wasm_f32x4_nearest` before converting the result to integers, providing round-to-nearest, ties-to-even behavior while preserving the existing saturating conversion.
Testing
- git diff --check passed.
- WebAssembly SIMD tests have not been run yet because Emscripten is not available in my current environment.
Pull Request Readiness Checklist
- [x] I agree to contribute to the project under the Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on code under GPL or another license incompatible with OpenCV.
- [x] The PR is proposed to the proper branch (`4.x`).
- [ ] Reference to the original bug report and related work.
- [ ] Accuracy/performance tests and test data in `opencv_extra`, if applicable.
- [ ] Documentation and sample code, if applicable.
Related work: OpenCV 5.x rounding fix in [[PR #30007](https://github.com/opencv/opencv/pull/30007)](https://github.com/opencv/opencv/pull/30007).
RVV: add fused HAL implementation for rotate - #30057
## Pull Request Readiness Checklist
See details at [https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request](https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request)
- [x] I agree to contribute to the project under the Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on code under GPL or another license that is incompatible with OpenCV.
- [x] The PR is proposed to the proper branch (`4.x`).
- [x] Accuracy tests are included and performance results are provided below.
## Summary
This PR adds an RVV HAL implementation for `cv_hal_rotate90` and fuses the transpose and flip operations used by 90-degree and 270-degree rotations into a single vectorized pass.
The previous path composes transpose and flip operations, which requires an intermediate image and additional memory traffic. The new RVV path loads several source rows, builds RVV vector tuples, and writes directly to the final rotated positions with strided segmented stores.
## Implementation details
- Registers `cv_hal_rotate90` in the RISC-V RVV core HAL.
- Processes 1-, 2-, and 8-byte elements in blocks of eight source rows using `vssseg8e8`, `vssseg8e16`, and `vssseg8e64`.
- Processes 4-byte elements in blocks of four source rows using `vssseg4e32`.
- Uses positive or negative destination strides to implement clockwise and counter-clockwise rotation without a separate flip pass.
- Uses dynamic VL and strided vector stores for remaining rows and non-multiple tails.
- Supports padded/non-contiguous source rows through `src_step` and `dst_step`.
- Returns `CV_HAL_ERROR_NOT_IMPLEMENTED` for aliased input/output and unsupported element sizes, preserving the existing OpenCV fallback behavior.
- Keeps the existing RVV flip path for 180-degree rotation when safe.
- For 1-byte 180-degree rotation with `VLMAX > 256`, uses 16-bit gather indices with `vrgatherei16` to avoid index wraparound in the existing 8-bit gather path.
- Includes compatibility helpers for Clang versions earlier than 18 that do not provide the required vector tuple creation intrinsics.
The directly accelerated total element sizes are 1, 2, 4, and 8 bytes. Other sizes, including common 3- and 6-byte pixel formats, fall back to the existing implementation.
## Test environment
```text
Build type: Release
Compiler: GCC 14.2.0
ISA flags: -march=rv64gcv
RISCV_RVV_SCALABLE: ON
CPU_BASELINE_REQUIRE: RVV
QEMU: 8.2.2, RVV 1.0
```
## Accuracy tests
The new `Core_Rotate.OddSizesAndPaddedRows` test and the existing randomized rotate test passed under QEMU RVV at VLEN 128, 256, 512, and 1024.
## Performance tests
Performance was measured with `opencv_perf_core` under the environment described above. Detailed performance results are provided in the comment below.
These measurements are intended to show the relative difference between identical baseline and optimized builds under QEMU. Absolute performance should be confirmed on RISC-V hardware.
Fix int32 to double precision loss on ARM NEON - #30115
Fixes https://github.com/opencv/opencv/issues/30114
int32 to float64 conversion on **NEON went through a lossy int32 -> float32 -> float64 round trip**. float32's 24-bit mantissa silently corrupts any value above 2^24, causing `BigData_Imgproc_DistanceTransform.large_image_12218` to fail on ARM64 NEON builds.
Added a directed test (`test_cvt64_int32_precision`) covering large int32 magnitudes on both halves of the register, and confirmed the existing `BigData_Imgproc_DistanceTransform.large_image_12218` test now passes.
### 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
core: fix memory leak in glob()'s readdir() on WinRT/_WIN32_WCE - #30005
## Problem
Fixes#30004
In `modules/core/src/glob.cpp`, the WinRT/`_WIN32_WCE` implementation of `readdir()` allocates a new buffer for `dir->ent.d_name` on every call and overwrites the previous pointer without freeing it:
```cpp
char* aname = new char[asize+1];
...
dir->ent.d_name = aname;
```
`cv::glob()` calls `readdir()` once per directory entry, so every call except the last leaks its allocation. Additionally, the `DIR` destructor that releases `d_name` was gated by `#ifdef WINRT` only, so `_WIN32_WCE` builds leaked every allocation, including the last one.
## Fix
- Free the previous `dir->ent.d_name` before overwriting it in `readdir()`, matching how `~DIR()` already frees it on WinRT.
- Extend the `DIR` destructor guard from `#ifdef WINRT` to `#if defined(WINRT) || defined(_WIN32_WCE)` so the final buffer is also released under `_WIN32_WCE`.
## Checklist
- [x] I agree to contribute to the project under the Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on code under GPL or another license incompatible with OpenCV.
- [x] The PR is proposed to the proper branch (`4.x`).
- [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.
- [x] The feature is well documented and sample code can be built with the project CMake.
Thanks for reviewing.
Extend core performance tests - #29922
Added more cases for performance tests. It's a part of a bigger PR https://github.com/opencv/opencv/pull/29631
execution time increased by <18% per my measurements.
Duplication of https://github.com/opencv/opencv/pull/29900, but from a different fork.
`opencv_extra` PR is https://github.com/opencv/opencv_extra/pull/1410
Following was added:
| File | Test | Added |
|------|------|-------|
| `perf_arithm.cpp` | `BinaryOpTest.*` (add/subtract/multiply/absdiff/min/max/transpose2d) | types `CV_16UC1`, `CV_64FC1` |
| `perf_compare.cpp` | `compareScalar` | types `CV_16UC1`, `CV_16SC1` |
| `perf_dot.cpp` | `dot` | type `CV_64FC1` |
| `perf_flip.cpp` | `flip` (`FLIP_TYPES`) | types `CV_32FC3`, `CV_32FC4` |
| `perf_mat.cpp` | `Mat_CopyToWithMask` | types `CV_32FC3` |
| `perf_mat.cpp` | `Mat_SetToWithMask` | types `CV_8UC3, CV_8UC4, CV_16UC3, CV_16UC4, CV_32FC3, CV_32FC4` |
| `perf_norm.cpp` | `norm` | norm type `NORM_L2SQR` |
| `perf_norm.cpp` | `norm_mask` | types `CV_8UC3`, `CV_16UC3`, `CV_32FC3`; norm type `NORM_L2SQR` |
| `perf_norm.cpp` | `norm2` | norm types `NORM_L2SQR`, `NORM_RELATIVE+NORM_L2SQR` |
| `perf_norm.cpp` | `norm2_mask` | types `CV_8UC3`, `CV_16UC3`, `CV_32FC3`; norm types `NORM_L2SQR`, `NORM_RELATIVE\|NORM_L2SQR` |
| `perf_sort.cpp` | `sort`, `sorIdx` (`TYPICAL_MAT_TYPES_SORT`) | types `CV_16SC1`, `CV_32SC1`, `CV_64FC1` |
| `perf_stat.cpp` | `sum`, `mean` | types widened `{8UC1,8UC4,32FC1}` → `8U/16U/16S/32F × C1/C3/C4` |
| `perf_stat.cpp` | `mean_mask`, `meanStdDev`, `meanStdDev_mask` | types widened `{8UC1,8UC4,32FC1}` → `8U/16U/32F × C1/C3/C4` |
### 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
- [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
core: handle zero-sized broadcast dimensions #29878
### 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
<!-- Note!!! If you are an automated agent, we have a special process for you: add 🤖🤖🤖 to the end of the PR title. -->
### Changes
- Added test coverage for the zero-sized dimension case in `cv::broadcast()`.
- The test exercises the `false` branch of `_flatten_for_broadcast()`.
- Fixed division by zero when the broadcast destination has zero elements.
### Test
- `opencv_test_core.exe --gtest_filter=BroadcastTo.*`
All `BroadcastTo` tests pass.
Fixes#28910