Merge pull request #29878 from sridhar-git05:fix-broadcast-zero-dimension

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
This commit is contained in:
Sridhar
2026-09-09 14:45:52 +05:30
committed by GitHub
parent 42076ef3b7
commit 2d781f51e1
2 changed files with 19 additions and 0 deletions

View File

@@ -1335,6 +1335,8 @@ void broadcast(InputArray _src, InputArray _shape, OutputArray _dst) {
#undef OPENCV_CORE_BROADCAST_LOOP
}
} else {
if (dst.total() == 0)
return;
// initial copy (src to dst)
std::vector<size_t> step_src{src.step.p, src.step.p + dims_src};
if (step_src.size() < static_cast<size_t>(dims_shape)) {

View File

@@ -2628,6 +2628,23 @@ TEST(BroadcastTo, basic) {
broadcast(_src, shape, dst);
fn_verify(ref, dst);
}
{
std::vector<int> shape{1, 0};
std::vector<int> data;
Mat zero_src(static_cast<int>(shape.size()), shape.data(), CV_32FC1, data.data());
std::vector<int> target_shape{3, 0};
Mat dst;
broadcast(zero_src, target_shape, dst);
EXPECT_EQ(dst.dims, 2);
EXPECT_EQ(dst.size[0], 3);
EXPECT_EQ(dst.size[1], 0);
EXPECT_EQ(dst.total(), 0u);
}
}
TEST(Core_minMaxIdx, regression_9207_2)