Files
opencv-MIRROR/modules/core/perf/perf_stat.cpp
pranayr710 2aaffd248d Merge pull request #30003 from pranayr710:fix/sum-32bit-accumulator
core: stop cv::sum() wrapping at 32 bits for CV_32U and CV_32S - #30003

Fixes #30002

### Problem

`cv::sum()` returns doubles, but for single-channel `CV_32S` and `CV_32U` it accumulates part of
the total in 32 bits, so a sum beyond the 32-bit range wraps. For `CV_32S` that is signed integer
overflow.

```
Mat m(1, 8, CV_32S, Scalar(INT_MAX));
cv::sum(m)[0];        // -8            expected 17179869176

Mat u(1, 8, CV_32U, Scalar(UINT_MAX));
cv::sum(u)[0];        // 8589934584    expected 34359738360
```

`sum_()`'s unrolled single-channel step adds four elements **to each other** in `WT` before the
result reaches the `ST` accumulator, and `WT` defaults to the source type:

```cpp
s0 += (WT)src[0] + (WT)src[cn] + (WT)src[cn*2] + (WT)src[cn*3];
```

For `CV_8U`/`CV_16U`/`CV_16S` that is harmless — integer promotion widens the operands to `int`
first. For the 32-bit depths the additions happen in 32 bits.

The vectorized specialization only runs from `len >= 6 * vector_width`, so shorter arrays take the
scalar route entirely and longer ones still leave a wrapping tail; and `DEFINE_SUM_SIMD_32` is
instantiated only for `int` and `float`, so `CV_32U` has no vectorized path at all. Multi-channel
inputs are unaffected: those branches add each element straight into its own `double` accumulator.

### Fix

Pass an explicit 64-bit integer `WT` for the two entry points. Widening to 64-bit integers rather
than to `double` keeps the step in integer arithmetic, and four 32-bit values cannot come near the
64-bit range. The 16-bit float entry points already pass an explicit `WT` for the same reason.

### Performance

1920x1080, best of 5 runs of 50 iterations:

| depth | before (wrong) | this patch (int64 WT) | double WT, for comparison |
| --- | --- | --- | --- |
| `CV_32U` | 0.430 ms | 0.407 ms | 0.729 ms |
| `CV_32S` | 0.235 ms | 0.258 ms | 0.268 ms |
| `CV_16U` (not touched) | 0.111 ms | 0.095 ms | |
| `CV_32F` (not touched) | 0.244 ms | 0.254 ms | |

Accumulating in `double` would also fix the wrap but costs about 70% on `CV_32U`, which has no
vectorized path and therefore runs this step for every element. The integer widening has no
measurable cost; run-to-run noise on this machine is around 10%.

### Tests

`Core_SumWide.no_32bit_wraparound` is a `TEST_P` over depth, channel count and length (4, 8, 23,
24, 64, 127 — around the vectorized path's 6-vector-width threshold), asserting the exact total.
It fails on unpatched 5.x:

```text
[  FAILED  ] Core_SumWide.no_32bit_wraparound/0, where GetParam() = (12, 1, 4)
    Which is: 17179869180
    Which is: 4294967292
```

and passes with the patch. Full `opencv_test_core`: 16897 of 16904. The 7 failures
(`Core_InputOutput.filestorage_base64_*`, `Core_globbing.accuracy`) reproduce identically on
unmodified 5.x in this environment and are unrelated.

### 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-09-29 12:07:34 +03:00

140 lines
3.1 KiB
C++

#include "perf_precomp.hpp"
namespace opencv_test
{
using namespace perf;
// The 32-bit integer depths are not in TYPICAL_MAT_TYPES, so they were not measured; they are the
// ones whose scalar accumulation step this touches.
PERF_TEST_P(Size_MatType, sum_wide,
testing::Combine(testing::Values(TYPICAL_MAT_SIZES),
testing::Values(CV_32SC1, CV_32UC1, CV_32SC3)))
{
Size sz = get<0>(GetParam());
int type = get<1>(GetParam());
Mat arr(sz, type);
Scalar s;
declare.in(arr, WARMUP_RNG).out(s);
TEST_CYCLE() s = sum(arr);
SANITY_CHECK_NOTHING();
}
PERF_TEST_P(Size_MatType, sum, TYPICAL_MATS)
{
Size sz = get<0>(GetParam());
int type = get<1>(GetParam());
Mat arr(sz, type);
Scalar s;
declare.in(arr, WARMUP_RNG).out(s);
TEST_CYCLE() s = sum(arr);
SANITY_CHECK(s, 1e-6, ERROR_RELATIVE);
}
PERF_TEST_P(Size_MatType, mean, TYPICAL_MATS)
{
Size sz = get<0>(GetParam());
int type = get<1>(GetParam());
Mat src(sz, type);
Scalar s;
declare.in(src, WARMUP_RNG).out(s);
TEST_CYCLE() s = cv::mean(src);
SANITY_CHECK(s, 1e-5);
}
PERF_TEST_P(Size_MatType, mean_mask, TYPICAL_MATS)
{
Size sz = get<0>(GetParam());
int type = get<1>(GetParam());
Mat src(sz, type);
Mat mask = Mat::ones(src.size(), CV_8U);
Scalar s;
declare.in(src, WARMUP_RNG).in(mask).out(s);
TEST_CYCLE() s = cv::mean(src, mask);
SANITY_CHECK(s, 5e-5);
}
PERF_TEST_P(Size_MatType, meanStdDev, TYPICAL_MATS)
{
Size sz = get<0>(GetParam());
int matType = get<1>(GetParam());
Mat src(sz, matType);
Scalar mean;
Scalar dev;
declare.in(src, WARMUP_RNG).out(mean, dev);
TEST_CYCLE() meanStdDev(src, mean, dev);
SANITY_CHECK(mean, 1e-5, ERROR_RELATIVE);
SANITY_CHECK(dev, 1e-5, ERROR_RELATIVE);
}
PERF_TEST_P(Size_MatType, meanStdDev_mask, TYPICAL_MATS)
{
Size sz = get<0>(GetParam());
int matType = get<1>(GetParam());
Mat src(sz, matType);
Mat mask = Mat::ones(sz, CV_8U);
Scalar mean;
Scalar dev;
declare.in(src, WARMUP_RNG).in(mask).out(mean, dev);
TEST_CYCLE() meanStdDev(src, mean, dev, mask);
SANITY_CHECK(mean, 1e-5);
SANITY_CHECK(dev, 1e-5);
}
PERF_TEST_P(Size_MatType, countNonZero, testing::Combine( testing::Values( TYPICAL_MAT_SIZES ), testing::Values( CV_8UC1, CV_8SC1, CV_16UC1, CV_16SC1, CV_32SC1, CV_32FC1, CV_64FC1 ) ))
{
Size sz = get<0>(GetParam());
int matType = get<1>(GetParam());
Mat src(sz, matType);
int cnt = 0;
declare.in(src, WARMUP_RNG);
int runs = (sz.width <= 640) ? 8 : 1;
TEST_CYCLE_MULTIRUN(runs) cnt = countNonZero(src);
SANITY_CHECK(cnt);
}
PERF_TEST_P(Size_MatType, hasNonZero, testing::Combine( testing::Values( TYPICAL_MAT_SIZES ), testing::Values( CV_8UC1, CV_8SC1, CV_16UC1, CV_16SC1, CV_32SC1, CV_32FC1, CV_64FC1 ) ))
{
Size sz = get<0>(GetParam());
int matType = get<1>(GetParam());
Mat src(sz, matType);
/*bool hnz = false;*/
declare.in(src, WARMUP_RNG);
int runs = (sz.width <= 640) ? 8 : 1;
TEST_CYCLE_MULTIRUN(runs) /*hnz =*/ hasNonZero(src);
SANITY_CHECK_NOTHING();
}
} // namespace