From 9548c94917a2e6cdb5619e582137da0e926972da Mon Sep 17 00:00:00 2001 From: Vincent Rabaud Date: Sat, 10 Oct 2026 13:13:33 +0200 Subject: [PATCH] check element count in isScalarLikeMat for 1x1 multi-channel Mats isScalarLikeMat(sc, cn) previously returned true whenever rows == 1 and cols == 1 (as long as nval <= 4), without checking whether nval matches 1 or the other operand's channel count cn. As a result, a 1x1 multi-channel Mat (e.g. 1x1 CV_32FC3, nval == 3) was mistakenly treated as a scalar for a different channel count (e.g. cn == 1 when multiplied by a cv::Scalar converted to a 4x1 CV_64FC1 Mat in Mat::mul). In arithm_op, this caused s1 and s2 to both be true, demoting the actual scalar operand s2 to false and broadcasting the operands into a 4x1 CV_32FC3 result instead of a 1x1 CV_32FC3 result. Require nval == 1 || nval == cn in isScalarLikeMat so that a 1x1 Mat is only treated as scalar-like when its total element count is compatible with the target channel count. --- modules/core/src/precomp.hpp | 2 +- modules/core/test/test_mat.cpp | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/modules/core/src/precomp.hpp b/modules/core/src/precomp.hpp index 5a77b6783a..a3281ecd5c 100644 --- a/modules/core/src/precomp.hpp +++ b/modules/core/src/precomp.hpp @@ -413,7 +413,7 @@ inline bool isScalarLikeMat(const _InputArray& sc, int cn) } else return false; - if (!continuous || nval > 4) + if (!continuous || nval > 4 || (nval != 1 && nval != cn)) return false; return (rows == 1 && cols == 1) || (rows == cn && cols == 1) || (rows == 1 && cols == cn); } diff --git a/modules/core/test/test_mat.cpp b/modules/core/test/test_mat.cpp index 3ac5464433..7c6731a265 100644 --- a/modules/core/test/test_mat.cpp +++ b/modules/core/test/test_mat.cpp @@ -3262,4 +3262,13 @@ TEST(Core_Mat, fitSameSize_keeps_layout) } } +TEST(Mat, ScalarMul) { + cv::Mat cv_mat_1x1_c3(1, 1, CV_32FC3, cv::Scalar(1, 2, 3)); + cv::Mat cv_mat_mul = cv_mat_1x1_c3.mul(cv::Scalar(2, 3, 4)); + ASSERT_EQ(cv_mat_mul.rows, 1); + ASSERT_EQ(cv_mat_mul.cols, 1); + ASSERT_EQ(cv_mat_mul.type(), CV_32FC3); + ASSERT_EQ(cv_mat_mul.at(0, 0), cv::Vec3f(2, 6, 12)); +} + }} // namespace