1
0
mirror of https://github.com/opencv/opencv.git synced 2026-07-25 21:33:04 +04:00

3355 Commits

Author SHA1 Message Date
Alexander Smorkalov a68b702ed5 Disable norm loop unroll for RISC-V RVV case. 2026-06-04 11:27:48 +03:00
Zixi Wang 2405556989 Merge pull request #29140 from Tiansuanyu:fix-gcc13-vblas-fma
core: fix numerical instability and UB in VBLAS SIMD helpers #29140

### Description

**Fixes #28845**

**Root cause identified by:** stubbing out `VBLAS<double>::givens()` to return 0 immediately — both tests pass, confirming the divergence originates in the double-precision Givens SIMD rotation.

**Main fix:** Use FMA form in `VBLAS::{float,double}::givens()` to keep JacobiSVD vector rotation numerically stable on SIMD/FMA builds.
This fixes the fisheye homography initialization divergence (`RMS 36.2553` vs `1`) seen in `RegisterCamerasTest.hetero1/2` under GCC 13. 

**Additional fix:** Replace fixed-size temporary storage `sbuf[2]` in `VBLAS<double>::dot()` with `v_reduce_sum()` to avoid out-of-bounds stores on wide SIMD backends (e.g., AVX2 `v_float64` requires 4 lanes, causing UB).

**Verification:**
Passed full `opencv_test_core` and `opencv_test_calib` locally under Ubuntu 24.04 (GCC 13) with AVX2.

### 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 (`next`)
- [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 (Passed existing `opencv_test_core` and `opencv_test_calib` tests)
- [ ] The feature is well documented and sample code can be built with the project CMake (N/A - Bug fix)
2026-05-26 18:01:06 +03:00
Alexander Smorkalov d8263a9899 Merge branch 4.x 2026-05-25 17:49:25 +03:00
Alexander Smorkalov 1c44eaf8bd Move divSpectrums to core module. 2026-05-24 17:28:53 +03:00
Alexander Smorkalov 00d19e1c63 Merge pull request #29114 from akretz:fix-masked-norm
Fix MaskedNormInf_SIMD<float, float>
2026-05-24 12:31:30 +03:00
Adrian Kretz dd214962a5 Merge pull request #29109 from akretz:fix-issue-23644
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
2026-05-24 10:53:48 +03:00
Adrian Kretz 3157f3e3ed Expand char to 32 bit of float 2026-05-23 10:17:16 +02:00
Abhishek Gola 0a8603b3ac Merge pull request #28889 from abhishek-gola:simd_kernel_speedup
SIMD Kernel speedup for DNN layers #28889

This PR add following speedups for Grounding Dino tiny model.

For Device:  Intel(R) Core(TM) i9-14900KS, x86, 32 Cores, ubuntu 24.04,
| Model | `ENGINE_NEW (Before)` | `ENGINE_NEW (After)` | `ENGINE_ORT` |
| :--- | :--- | :--- | :--- | 
| **Grounding Dino Tiny** | 3130 ms | 1872.06 ms| 1800.18 ms|

### 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
2026-05-21 15:53:15 +03:00
Alexander Smorkalov 1d54398f07 Merge pull request #29076 from abhishek-gola:core_cuda_changes
Added GPU fit and other GPU core module changes
2026-05-21 15:27:52 +03:00
Alexander Smorkalov 2d528c49d2 Merge pull request #29078 from omrope79:dep_convertFp16
Deprecate CUDA's convertFp16() in favor of convertTo() with CV_16F
2026-05-21 15:26:54 +03:00
kevinylin88 01b23a0de5 Merge pull request #29080 from kevinylin88:project4_kevinlin
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.
2026-05-21 14:29:55 +03:00
Alexander Smorkalov b745bbf539 Merge pull request #29082 from vpisarev:fix_input_array_std_vector_5x
fix vector<T> and vector<vector<T>> handling via InputArray/OutputArray
2026-05-21 14:22:00 +03:00
Alexander Smorkalov 657496cab4 Merge pull request #29088 from asmorkalov:as/5.x_bool_io
Fixed bool type IO in FileStorage.
2026-05-21 13:29:59 +03:00
Alexander Smorkalov 7a23e57680 Fixed bool type IO in FileStorage. 2026-05-21 11:48:33 +03:00
Vadim Pisarevsky 996713974c ported patch to fix vector<T> and vector<vector<T>> handling via InputArray/OutputArray proxy types, regardless of the underlying std::vector implementation. This is a port of https://github.com/opencv/opencv/pull/28862 to 5.x 2026-05-20 22:07:05 +03:00
Alexander Smorkalov c9070f9f35 Merge branch 4.x 2026-05-20 17:57:51 +03:00
Om Navin Rope 1e731a2e2a Changes for fp16 conversion 2026-05-20 17:30:37 +05:30
Abhishek Gola 2f89729f2d core cuda changes 2026-05-20 17:29:34 +05:30
satyam yadav cc8f683b6a Merge pull request #28482 from satyam102006:core/yaml-1-2-support
core: add YAML 1.2 support for FileStorage #28482

Fixes: #26363
CI Update: https://github.com/opencv/ci-gha-workflow/pull/306

Summary: 
- Bool true/false literals support
- Header-less YAMLs support for Python YAML module compatibility. Header-less files are parsed as YAMLs by default
- Added FORMAT_YAML_1_0 flag to FileStorage for fallback.
- New YAML1.2 header

Testing: 
- Added Core_InputOutput.YAML_1_2_Compatibility test case in test_io.cpp.
- Added YAML interop test in Python
2026-05-19 13:44:50 +03:00
Alexander Smorkalov bd0bc5af59 Fixed data overflow issue when int64 value is interpreted as float/double. 2026-05-18 13:35:38 +03:00
Alexander Smorkalov 6018b0cf82 Merge pull request #28897 from Lurie97:fix_diag
core: implement OpenCL kernel for UMat::diag to avoid aliasing races
2026-05-15 13:31:12 +03:00
Alexander Smorkalov fb3054d814 Suppressed UB warning in cubeRoot function. 2026-05-14 11:26:40 +03:00
Abhishek Gola 8cc3f68cd4 Merge pull request #28964 from abhishek-gola:extend_primitive_core_ops
Extended primitive core operations to support new types #28964

The support was already there, this PR tests them on edge cases and patch the fix.

closes: https://github.com/opencv/opencv/issues/24580
### 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
2026-05-08 17:32:56 +03:00
Pratham Kumar 9929b5ceb9 Merge pull request #28610 from pratham-mcw:core-norm_mask-opt
core : add NEON intrinsics support for norm_mask function #28610

- This PR adds NEON intrinsics-based implementations for masked norm operations in norm.simd.hpp for ARM64 architecture.
- The optimized implementation uses ARM NEON intrinsics to accelerate masked norm computations (Infinity norm, L1 norm, and L2 norm) used by the norm function when a mask is provided.
- In the x64 architecture, masked norm operations benefit from IPP-based optimized implementations. However, on ARM64, the execution falls back to scalar implementations, which results in lower performance.
- To achieve performance parity with x64, NEON-based SIMD implementations have been added for ARM64.
- Additionally, scalar loop unrolling optimizations have been added for non-masked norm operations.
- After introducing these changes, masked norm operations showed significant performance improvements on ARM64 platforms, particularly for single-channel (cn=1) operations where NEON intrinsics provide the greatest benefit.
<img width="952" height="822" alt="image" src="https://github.com/user-attachments/assets/12d35f93-a316-4520-9d9c-12ce6b371ddb" />

- [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
2026-05-08 09:57:09 +03:00
jiajia Qian 60858fce9e core: implement OpenCL kernel for UMat::diag to avoid aliasing races
The previous OpenCL implementation of UMat::diag() relied on a sequence of
operations involving buffer initialization followed by copy/transpose on
an aliased diag() view. Although these operations were enqueued on an
in-order command queue, this implicitly assumed memory visibility between
kernels operating on aliased regions of the same buffer.

According to the OpenCL specification, in-order command queues only guarantee
command scheduling order, while memory visibility between commands is only
established through explicit command-level synchronization points (e.g.
events, barriers, or clFinish).Under OpenCL’s relaxed memory model, such
assumptions are not guaranteed without an explicit command-level synchronization
point, and can lead to data races and incorrect results, especially for very
small matrices (e.g. 1x1). The issue is more likely to be exposed on Mesa-based drivers
when the GPU is running at lower frequencies (e.g. 500 MHz).

This change introduces a dedicated OpenCL kernel to construct the diagonal
matrix in a single kernel invocation, avoiding intermediate aliasing and
eliminating the need for implicit ordering assumptions. If the OpenCL path
is unavailable or unsupported, the implementation transparently falls back
to the CPU path.

Signed-off-by: jiajia Qian <jiajia.qian@nxp.com>
2026-05-07 09:18:29 +08:00
Samaresh Kumar Singh dbf872ac1b Fix indirect call type mismatch in minMaxIdx dispatch table
The minMaxIdx dispatch table in modules/core/src/minmax.cpp stored
seven differently typed functions through C-style casts to a single
MinMaxIdxFunc pointer type, which is undefined behaviour and trips
UBSan's -fsanitize=function for any CV_32F or CV_64F input. This
change switches the typedef and every depth-specific helper to take
void pointers for src, minval and maxval, with the original typed
pointer recovered at function entry. The dispatch table no longer
needs C-style casts and the int pointer punning at the call site
goes away. Fixes #28928.
2026-05-05 22:39:59 -05:00
Kumataro 8449b9e468 core: safe handling of compressed file level extension (.gz[0-9])
- Replace unsafe pointer arithmetic and direct buffer modification with std::string methods.
- Update documentation to clarify that the last digit is used as compression level and truncated from the actual filename.
- Add test cases for .gz and .gz0-9
2026-05-05 07:41:59 +09:00
Kumataro 28b1f54468 core,objdetects,dnn,features2d: fix build warnings with GCC 16 2026-05-02 10:41:24 +09:00
Varun Jaiswal faf34f95af Merge pull request #28837 from varun-jaiswal17:gemma3-tokenizer
Add Gemma3 tokenizer support for dnn #28837

- Adds Gemma3 tokenizer support
- Implements character-level BPE
- Adds 6 tests covering English, phrase, mixed case, numbers, special tokens, and encode/decode
- add gemma3_inference.py

Merge with: 
- **Companion PR**  : https://github.com/opencv/opencv_extra/pull/1346
- forward pass bug in gemma3_inference.py : https://github.com/opencv/opencv/pull/28836

### 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
2026-04-29 10:00:27 +03:00
Alexander Smorkalov 7bde3f9ae9 Merge branch 4.x 2026-04-24 11:11:26 +03:00
kjg0724 5d88781f74 Merge pull request #28782 from kjg0724:reduce-simd-optimization
core: add platform-specific SIMD for cv::reduce REDUCE_SUM

### Pull Request

Rewrite `cv::reduce` SIMD optimization using platform-specific instructions as discussed in #28763.

#### Changes

**Col reduce (dim=1) — horizontal sum per row:**
- ARM DOTPROD: `vdotq_u32()` — single-instruction byte sum, no intermediate flush needed
- ARM AArch64 fallback: `vpaddlq` chain (u8→u16→u32)
- Intel AVX2: `_mm256_sad_epu8()` — 32 bytes → 4×u64 partial sums per cycle
- Intel SSSE3: `_mm_shuffle_epi8` + `_mm_sad_epu8` for cn=4 channel separation
- Intel SSE2: `_mm_sad_epu8` for cn=1
- cn=4: hardware deinterleave (`vld4q_u8` on ARM, shuffle+SAD on Intel)

**Row reduce (dim=0) — vertical accumulation across rows:**
- u16 intermediate accumulator with 256-row flush (halves memory bandwidth vs direct u32)
- ARM AArch64: `vaddw_u8` widening add (single instruction vs expand+add)
- Intel: unpack + add with u16 buffer

**Coverage:** All REDUCE_SUM type combinations — 8U→32S, 8U→32F, 16U→32F, 16S→32F, 32F→32F, 32F→64F, 64F→64F. Non-8U types use universal intrinsics where platform-specific gain is minimal (widening is single-stage, FP has limited alternatives). `REDUCE_AVG` benefits automatically (uses SUM internally).

**Dispatch:** `CV_CPU_DISPATCH` with SSE2/AVX2/NEON_DOTPROD/LASX. Fallback hierarchy: DOTPROD → AArch64 NEON → Universal Intrinsics → scalar.

#### Benchmark (Apple M3 Pro, MacBook Pro 16-inch 2023)

| Path | Type | Speedup vs scalar |
|------|------|-------------------|
| Col reduce (dim=1) | 8UC1 | **3.0–4.5x** |
| Col reduce (dim=1) | 8UC4 | **2.7–5.0x** |
| Col reduce (dim=1) | 32FC1 | 1.7–2.3x |
| Row reduce (dim=0) | 8UC1 | 1.1–1.5x |

Row reduce gains are modest due to memory-bandwidth bound (as expected for vertical accumulation). No regressions on non-target paths (MAX, MIN, SUM2).

#### Testing

- `opencv_test_core --gtest_filter="*Reduce*:*reduce*"` — 483 tests PASSED
- Edge cases: non-aligned dimensions (127×61), cn=2/3 scalar fallback, REDUCE_SUM2 unmodified

#### Files changed

- `modules/core/src/reduce.simd.hpp` — new, platform-dispatched SIMD implementation
- `modules/core/src/reduce.dispatch.cpp` — new, CV_CPU_DISPATCH wrapper
- `modules/core/CMakeLists.txt` — add `NEON_DOTPROD` to dispatch list
- `modules/core/src/matrix_operations.cpp` — wire dispatch functions into ReduceC/R_Invoker
2026-04-21 12:24:38 +03:00
jiajia Qian ba879cd60f core/ocl: fix incorrect results for in-place flip on strict OpenCL implementations
Previously, OpenCL in-place flip kernels (rows/cols/both) could produce
incorrect results compared to the CPU implementation on strict OpenCL
drivers such as Mesa. The kernels relied on implicit load–load–store–store
(LLSS) ordering when src and dst alias, which is not guaranteed by the
OpenCL memory model and may be reordered.

Some vendor drivers happened to preserve the expected ordering, masking
the issue, but Mesa correctly exposes the undefined behavior.

This change introduces dedicated in-place flip kernels that:
- Explicitly detect in-place execution (src == dst)
- Stage data through local memory tiles
- Enforce correct ordering with work-group barriers
- Avoid global memory read/write aliasing hazards

The non in-place path is unchanged.

With this fix, OpenCL in-place flip produces correct and consistent results
across drivers, matches CPU behavior, and complies with the OpenCL memory
model.

Signed-off-by: jiajia Qian <jiajia.qian@nxp.com>
2026-04-21 08:54:52 +08:00
Abhishek Gola de851d24a5 Merge pull request #28121 from abhishek-gola:loop_layer_add
Add Loop layer to new DNN engine #28121

Addition of loop layer in 5.x for issue: https://github.com/opencv/opencv/issues/26179 and https://github.com/opencv/opencv/issues/26141 and https://github.com/opencv/opencv/issues/25200

OpenCV Extra: https://github.com/opencv/opencv_extra/pull/1335

### 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
2026-04-14 09:15:46 +03:00
Alexander Smorkalov 1a6f669763 Merge branch 4.x 2026-04-09 18:44:48 +03:00
Jorge Velez a49a293d3c Merge pull request #27534 from JorgeV92:gsoc2025-tokenizer
GSoC 2025: Add Tokenizer Support to DNN Module #27534

merge with https://github.com/opencv/opencv_extra/pull/1276

### Summary
This pull request introduces initial support for a tokenizer module under `modules/dnn/src/tokenizer` as part of Google Summer of Code 2025 (Project: Tokenization for OpenCV DNN).

### Status
- [x] Project structure in place
- [x] Initial BPE tokenizer loading
- [x] Regex splitting (in progress)
- [x] Encoding logic for GPT-2 tokenizer (in progress)
- [ ] Documentation (to be improved)

### Goals
The goal is to support Hugging Face-compatible tokenization (e.g., GPT-2) natively in C++ to be integrated with DNN inference pipelines. 

The core pipeline lives in `dnn/src/tokenizer/core_bpe.hpp` and `dnn/src/tokenizer/encoding.hpp`. For Unicode handling I’m using `dnn/src/tokenizer/unicode.hpp`, which is adapted from llama.cpp.


### Feedback
Please share early feedback on:
- General design structure
- Integration strategy with `dnn`
- Code organization or naming conventions

### Reference
Project: https://summerofcode.withgoogle.com/programs/2025/projects/79SW6eNK
2026-04-06 10:46:13 +03:00
Lurie97 a3e129aad8 Merge pull request #28686 from Lurie97:fix_inplace
core(opencl): fix inplace transpose race by enforcing LLSS ordering via local barrier #28686

The former inplace transpose implementation allowed a reordering of global-memory operations across work-items. Specifically, the intended LLSS (Load–Load–Store–Store) access pattern could be reordered by the GPU into LSLS (Load–Store–Load–Store), causing partially written tiles to be observed by other work-items and producing incorrect output.

This patch introduces a tiled LDS-based algorithm and adds an explicit:

    barrier(CLK_LOCAL_MEM_FENCE);

between the load and store phases.

### 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
2026-04-03 15:50:11 +03:00
Prasad Ayush Kumar 47ac80995f Merge pull request #28749 from Prasadayus:NMS-empty-detection-fix
Nms empty detection fix #28749

Requires opencv_extra: https://github.com/opencv/opencv_extra/pull/1330

### 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
2026-04-02 18:37:23 +03:00
pratham-mcw 3cf98c51c8 Merge pull request #28609 from pratham-mcw:core-rotate-neon-optimization
core: add NEON implementation for rotate function #28609

- This PR adds a NEON intrinsics-based implementation for the rotate function in matrix_transform.cpp for Windows-ARM64.
- The optimized implementation uses  ARM NEON intrinsics to accelerate the internal transpose step used by the rotate function.
- In the x64 architecture, the rotate operation benefits from IPP-based optimized implementations. However, on ARM64, the execution falls back to the scalar implementation, which results in lower performance.
- To achieve performance parity with x64, a NEON-based SIMD implementation has been added for ARM64. 
- After introducing these changes, the rotate function showed noticeable performance improvements on ARM64 platforms.
<img width="1009" height="817" alt="image" src="https://github.com/user-attachments/assets/8bec0041-b19c-4fc8-9103-532746224515" />

 
- [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
2026-03-31 16:52:04 +03:00
Alexander Smorkalov 92c43f80fc Merge pull request #28739 from pratham-mcw:core/fix-MeanStdDeviation-accuracytest
core: fix meanStdDev bug by using separate variables v2, v3 in sumsqr_
2026-03-31 15:39:16 +03:00
pratham-mcw c5d747f75c core: fix meanStdDev bug by using separate variables v2, v3 in sumsqr_ 2026-03-31 11:29:34 +05:30
Vincent Rabaud 5c91261ca0 Force step to be ptrdiff_t in resize
Otherwise, ASAN could return an error:
"runtime error: addition of unsigned offset"
2026-03-30 10:48:00 +02:00
Yang Guanyuhan 2d15169ab5 Merge pull request #28692 from YangGuanyuhan:fix-lightglue-assertion-fail
dnn: fix dst_dp assertion in broadcast for size-1 dims causing crash in lightglue.onnx model #28692

The original assertion CV_Assert(dst_dp == 1) does not handle valid cases where the innermost dimension size is 1 like [10, 5, 1], resulting in dst_dp == 0.

This occurs during broadcasting in LightGlue ONNX model and leads to assertion failure.

Allow dst_dp == 0 for size-1 dimensions to handle this edge case correctly.

### 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
2026-03-23 11:27:37 +03:00
Abhishek Gola ff2e6358fd added AVXX VNNI support 2026-03-20 13:20:31 +05:30
Alexander Smorkalov f6aceee13b Merge pull request #28655 from usernotfound-101:cvmixchannels-warning-fix
Add static integer casting for cvMixChannels, safer
2026-03-20 10:25:38 +03:00
Varun Jaiswal df7d437b86 Merge pull request #28663 from varun-jaiswal17:added-inRange-64double-SIMD
Added SIMD support for 64 bit float and fallback for 64 bit int#28663

Merged with : https://github.com/opencv/ci-gha-workflow/pull/299

### 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
2026-03-20 08:42:56 +03:00
Alexander Smorkalov b5a7e0c662 Merge branch 4.x 2026-03-19 11:29:57 +03:00
Abhishek Gola 2dec80044b moved AVXVNNI function to core 2026-03-17 18:58:03 +05:30
usernotfound-101 3470f5b35b Add static integer casting to get rid of the warning, safer 2026-03-13 22:25:08 +05:30
Vadim Pisarevsky 1b483ffea6 Merge pull request #28585 from vpisarev:dnn_block_layout_v5
Block layout-based convolution in DNN #28585

merge together with https://github.com/opencv/opencv_extra/pull/1321

Some core parts of the new engine in DNN module have been revised substantially:

1. all tests seem to pass, except for `Test_Graph_Simplifier.ResizeSubgraph`, which has been disabled because it does not take the newly added `TransformLayoutLayer` into account. The test should be reworked perhaps.
1. convolution and related operations (maxpool/avgpool) now use so-called block layout (`DATA_LAYOUT_BLOCK`), where `NxCxHxW` tensors are represented  as `NxC1xHxWxC0`, where `C1=(C + C0-1)/C0` and `C0` is a power-of-two (usually 4, 8, 16 or 32).
1. graph is now pre-processed and `TransformLayoutLayer` is inserted to convert data from NCHW or NHWC layout to the block layout or vice versa. The transformations are done in a lazy way only when they are really needed. For example, in the whole Resnet only 2 transformations are performed.
1. transformer-based models and other models that do not use convolutions will run as usual, without going to block layout.
1. there is yet another graph preprocessing stage added that embeds constant weights/scale and bias into convolution and batch norm layers.
1. 'batchnorm', 'activation' and 'adding a residual' are now fused with convolution, just like in the old engine. That brings some noticeable acceleration.
1. optimized convolution kernels have been added.
     * depthwise convolution, as well as maxpool and avgpool support C0=4, 8, 16 etc. _as long as_  C0 is divisible by the number of fp32 lanes in a SIMD register of the target platform (e.g. on ARM with NEON there must be `C0 % 4 == 0`, on x64 with AVX2 `C0 % 8 == 0`).
     * non-depthwise convolution only supports C0=8 for now. C0=8 seems to be a sweetspot for ARM with NEON, x64 with AVX2 or RISC-V with RVV (with 128- or 256-bit registers). For some platforms with dedicated matrix accelerators C0=16 or even C0=32 might be more efficient, but we could add the respective kernels later.
     * only fp32 kernels have been added. fp16/bf16 kernels might be added a little later.

### 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
- [x] Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake
2026-03-13 17:09:27 +03:00
Madan mohan Manokar 18c7c9bcb9 Merge pull request #28614 from amd:fast_flipHoriz
Optimized flip Horizontal #28614

- Refactor flipHoriz implementation.
- Optimizations for horizontal image flipping 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
- [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
2026-03-13 11:11:20 +03:00