From 2d781f51e1fe5e9c7f465d774098fe57796b54a3 Mon Sep 17 00:00:00 2001 From: Sridhar Date: Wed, 9 Sep 2026 14:45:52 +0530 Subject: [PATCH] Merge pull request #29878 from sridhar-git05:fix-broadcast-zero-dimension MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 ### 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 --- modules/core/src/matrix_transform.cpp | 2 ++ modules/core/test/test_arithm.cpp | 17 +++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/modules/core/src/matrix_transform.cpp b/modules/core/src/matrix_transform.cpp index fd9485d271..309d8d7ec2 100644 --- a/modules/core/src/matrix_transform.cpp +++ b/modules/core/src/matrix_transform.cpp @@ -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 step_src{src.step.p, src.step.p + dims_src}; if (step_src.size() < static_cast(dims_shape)) { diff --git a/modules/core/test/test_arithm.cpp b/modules/core/test/test_arithm.cpp index 7eb642b51d..ffe6ead18e 100644 --- a/modules/core/test/test_arithm.cpp +++ b/modules/core/test/test_arithm.cpp @@ -2628,6 +2628,23 @@ TEST(BroadcastTo, basic) { broadcast(_src, shape, dst); fn_verify(ref, dst); } + + { + std::vector shape{1, 0}; + std::vector data; + Mat zero_src(static_cast(shape.size()), shape.data(), CV_32FC1, data.data()); + + std::vector 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)