diff --git a/modules/dnn/src/layers/hardmax.cpp b/modules/dnn/src/layers/hardmax.cpp index 68d5a83ebc..d5cc58add2 100644 --- a/modules/dnn/src/layers/hardmax.cpp +++ b/modules/dnn/src/layers/hardmax.cpp @@ -68,7 +68,7 @@ public: Mat src = inputs[0]; Mat dst = outputs[0]; - axis = normalize_axis(axis, src.dims); + const int normAxis = normalize_axis(axis, src.dims); MatShape shape(src.size.p, src.size.p + src.dims); // Prepare output @@ -76,15 +76,15 @@ public: switch (src.depth()) { - case CV_8U: hardmaxApply(src, dst, axis); break; - case CV_8S: hardmaxApply(src, dst, axis); break; - case CV_16U: hardmaxApply(src, dst, axis); break; - case CV_16S: hardmaxApply(src, dst, axis); break; - case CV_32S: hardmaxApply(src, dst, axis); break; - case CV_64S: hardmaxApply(src, dst, axis); break; - case CV_Bool: hardmaxApply(src, dst, axis); break; - case CV_32F: hardmaxApply(src, dst, axis); break; - case CV_64F: hardmaxApply(src, dst, axis); break; + case CV_8U: hardmaxApply(src, dst, normAxis); break; + case CV_8S: hardmaxApply(src, dst, normAxis); break; + case CV_16U: hardmaxApply(src, dst, normAxis); break; + case CV_16S: hardmaxApply(src, dst, normAxis); break; + case CV_32S: hardmaxApply(src, dst, normAxis); break; + case CV_64S: hardmaxApply(src, dst, normAxis); break; + case CV_Bool: hardmaxApply(src, dst, normAxis); break; + case CV_32F: hardmaxApply(src, dst, normAxis); break; + case CV_64F: hardmaxApply(src, dst, normAxis); break; default: CV_Error(Error::StsUnsupportedFormat, "Unsupported input data type"); } diff --git a/modules/dnn/test/test_layers.cpp b/modules/dnn/test/test_layers.cpp index 18a4f19fc5..6b138f722c 100644 --- a/modules/dnn/test/test_layers.cpp +++ b/modules/dnn/test/test_layers.cpp @@ -6617,4 +6617,34 @@ TEST(Test_TensorScatter, InplaceNewEngineGraph) EXPECT_EQ(pastBuf, outBuf); } +TEST(Layer_Test_Hardmax_Axis, keepsNegativeAxisAcrossRanks) +{ + LayerParams lp; + lp.type = "Hardmax"; + lp.name = "test_hardmax"; + lp.set("axis", -1); + + Ptr layer = LayerFactory::createLayerInstance(lp.type, lp); + ASSERT_TRUE(layer); + + // The largest value in each group of 3 is at index 1 and index 0 + float data[] = {0, 5, 1, + 9, 0, 0}; + float expected[] = {0, 1, 0, + 1, 0, 0}; + + // First run: 2D input [2, 3], so axis -1 is index 1 + std::vector inputs{Mat(2, 3, CV_32F, data).clone()}, outputs; + runLayer(layer, inputs, outputs); + ASSERT_EQ(outputs.size(), (size_t)1); + EXPECT_EQ(0, cvtest::norm(outputs[0], Mat(2, 3, CV_32F, expected), NORM_INF)); + + // Second run on the same layer: 3D input [1, 2, 3], so axis -1 must now be index 2 + int sz[] = {1, 2, 3}; + inputs = {Mat(3, sz, CV_32F, data).clone()}; + runLayer(layer, inputs, outputs); + ASSERT_EQ(outputs.size(), (size_t)1); + EXPECT_EQ(0, cvtest::norm(outputs[0], Mat(3, sz, CV_32F, expected), NORM_INF)); +} + }} // namespace