From 9940db5599e687a81ae67ef10d5b53c95985929b Mon Sep 17 00:00:00 2001 From: Sridhar Date: Thu, 10 Sep 2026 13:01:04 +0530 Subject: [PATCH] Merge pull request #29911 from sridhar-git05:fix-broadcast-zero-dimension-5x core: handle zero-sized broadcast dimensions - #29911 ### 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 Port the fix from #29878 to the 5.x branch. This adds a guard for zero-sized destination matrices in cv::broadcast() and a regression test covering broadcasting from {1, 0} to {3, 0}. The relevant BroadcastTo.* tests pass locally. Related: #29878 --- 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 21dffcad7b..082626b0ad 100644 --- a/modules/core/src/matrix_transform.cpp +++ b/modules/core/src/matrix_transform.cpp @@ -1320,6 +1320,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 ca06c21133..0373866e43 100644 --- a/modules/core/test/test_arithm.cpp +++ b/modules/core/test/test_arithm.cpp @@ -2829,6 +2829,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(BroadcastTo, regression_dst_dp_zero_when_last_dim_is_one)