From 33d76d5adedf1b384d2f2a5c2299154e8fc7606f Mon Sep 17 00:00:00 2001 From: Abhishek Gola Date: Tue, 6 Oct 2026 15:14:51 +0530 Subject: [PATCH] Merge pull request #30091 from abhishek-gola:core-shape-einsum Add squeeze/unsqueeze/flatten/reshape for N-D arrays - #30091 ### 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 - [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable Patch to opencv_extra has the same branch name. - [x] The feature is well documented and sample code can be built with the project CMake --- modules/core/include/opencv2/core.hpp | 46 +++++++ modules/core/include/opencv2/core/mat.hpp | 13 ++ modules/core/src/matrix.cpp | 149 +++++++++++++++++++++ modules/core/src/shape_ops.cpp | 65 +++++++++ modules/core/test/test_shape_ops.cpp | 149 +++++++++++++++++++++ modules/dnn/src/layers/flatten_layer.cpp | 14 +- modules/dnn/src/layers/reshape2_layer.cpp | 47 ++----- modules/dnn/src/layers/squeeze_layer.cpp | 30 +---- modules/dnn/src/layers/unsqueeze_layer.cpp | 27 +--- modules/dnn/test/test_layers.cpp | 24 ++++ 10 files changed, 461 insertions(+), 103 deletions(-) create mode 100644 modules/core/src/shape_ops.cpp create mode 100644 modules/core/test/test_shape_ops.cpp diff --git a/modules/core/include/opencv2/core.hpp b/modules/core/include/opencv2/core.hpp index f39cc2e115..b8efd1c5ba 100644 --- a/modules/core/include/opencv2/core.hpp +++ b/modules/core/include/opencv2/core.hpp @@ -1092,6 +1092,52 @@ CV_EXPORTS_W void flip(InputArray src, OutputArray dst, int flipCode); */ CV_EXPORTS_W void flipND(InputArray src, OutputArray dst, int axis); +/** @brief Removes axes of size 1 from an n-dimensional array. + * + * The elements are not changed. When called in place (dst is src) on a continuous array, only the + * header changes; otherwise the elements are copied into dst (Mat::reshape gives a view without + * copying). The channels of the elements are kept, the axes are the array dimensions. The same holds + * for unsqueeze, flatten and reshape. + * @param src input array + * @param dst output array + * @param axes axes to remove, each of size 1; negative values count from the end. + * When empty, all the axes of size 1 are removed. + * @sa unsqueeze, MatShape::squeeze + */ +CV_EXPORTS_W void squeeze(InputArray src, OutputArray dst, const std::vector& axes = std::vector()); + +/** @brief Inserts axes of size 1 into an n-dimensional array. + * @param src input array + * @param dst output array with src.dims + axes.size() dimensions + * @param axes positions of the new axes in dst; negative values count from the end of dst. + * @sa squeeze, MatShape::unsqueeze + */ +CV_EXPORTS_W void unsqueeze(InputArray src, OutputArray dst, const std::vector& axes); + +/** @brief Merges consecutive axes of an n-dimensional array into one. + * + * With the default arguments the result is 1-dimensional. + * @param src input array + * @param dst output array + * @param startAxis first axis to merge; negative values count from the end. + * @param endAxis last axis to merge (inclusive); negative values count from the end. + * @sa MatShape::flatten + */ +CV_EXPORTS_W void flatten(InputArray src, OutputArray dst, int startAxis = 0, int endAxis = -1); + +/** @brief Changes the shape of an n-dimensional array. + * + * One element of newShape may be -1, it is then inferred from the number of elements. An element + * equal to 0 copies the corresponding axis of src, unless allowZero is set, in which case it is a + * zero-size axis (the ONNX Reshape convention). + * @param src input array + * @param dst output array + * @param newShape the new shape + * @param allowZero treat 0 in newShape as a size instead of "same as src" + * @sa MatShape::reshape, Mat::reshape + */ +CV_EXPORTS_W void reshape(InputArray src, OutputArray dst, const std::vector& newShape, bool allowZero = false); + /** @brief Concatenates n-dimensional arrays along the given axis. * * All the arrays must have the same type and number of dimensions, and the same size along every diff --git a/modules/core/include/opencv2/core/mat.hpp b/modules/core/include/opencv2/core/mat.hpp index 8a75fee675..51895aa035 100644 --- a/modules/core/include/opencv2/core/mat.hpp +++ b/modules/core/include/opencv2/core/mat.hpp @@ -160,6 +160,19 @@ struct CV_EXPORTS_W_SIMPLE MatShape // compute shape of the result with possible broadcasting CV_WRAP MatShape expand(const MatShape& another) const; + // The operations below drop the layout, except for a block one: it is applied to the + // semantic NCHW form and blocked again, which only works while N and C stay unchanged. + + // removes the given axes of size 1; all the axes of size 1 when axes is empty + CV_WRAP MatShape squeeze(const std::vector& axes = std::vector()) const; + // inserts axes of size 1; axes are positions in the result + CV_WRAP MatShape unsqueeze(const std::vector& axes) const; + // merges the axes from startAxis to endAxis (inclusive) into one + CV_WRAP MatShape flatten(int startAxis = 0, int endAxis = -1) const; + // the shape of the same number of elements given by newShape, where -1 is inferred + // and 0 copies the corresponding axis of this shape (unless allowZero is set) + CV_WRAP MatShape reshape(const MatShape& newShape, bool allowZero = false) const; + // convert shape between layouts CV_WRAP MatShape toLayout(DataLayout newLayout, int C0=0) const; diff --git a/modules/core/src/matrix.cpp b/modules/core/src/matrix.cpp index be8b6c8782..7757bdf3f6 100644 --- a/modules/core/src/matrix.cpp +++ b/modules/core/src/matrix.cpp @@ -396,6 +396,155 @@ MatShape MatShape::toLayout(DataLayout newLayout, int C0) const return newsize; } +static int normalizeShapeAxis(int axis, int dims) +{ + CV_CheckGE(axis, -dims, "axis is out of range"); + CV_CheckLT(axis, dims, "axis is out of range"); + return axis < 0 ? axis + dims : axis; +} + +// The semantic NCHW form {N, C, spatial...} of a block ('NC1HWC0') shape, so that axes and +// element counts are the logical ones rather than the C0-padded ones. +static MatShape toSemantic(const MatShape& shape) +{ + CV_CheckGE(shape.dims, 3, "a block shape is {N, C1, spatial..., C0}"); + return shape.toLayout(DATA_LAYOUT_NCHW); +} + +// Blocks such a result again. Once N or C changes, elements cross the padded C0 lanes and +// the data needs a repack, which a shape operation cannot express. +static MatShape toBlockOf(MatShape result, const MatShape& src, const char* op) +{ + if (result.dims < 2 || result.p[0] != src.p[0] || result.p[1] != src.C) + CV_Error_(Error::StsNotImplemented, + ("%s: the block layout is kept only when the batch and the channel axes stay " + "unchanged; convert the shape with toLayout() first", op)); + CV_CheckLE(result.dims + 1, (int)MatShape::MAX_DIMS, "too many dimensions"); + result.layout = DATA_LAYOUT_NCHW; + return result.toLayout(DATA_LAYOUT_BLOCK, src.p[src.dims-1]); +} + +MatShape MatShape::squeeze(const std::vector& axes) const +{ + CV_Assert(dims >= 0); + if (layout == DATA_LAYOUT_BLOCK) + return toBlockOf(toSemantic(*this).squeeze(axes), *this, "squeeze"); + bool remove[MAX_DIMS] = {false}; + if (axes.empty()) + { + for (int i = 0; i < dims; i++) + remove[i] = p[i] == 1; + } + for (int a : axes) + { + int i = normalizeShapeAxis(a, dims); + CV_Check(a, !remove[i], "squeeze: duplicate axis"); + CV_Check(p[i], p[i] == 1, "squeeze: the size of a squeezed axis must be 1"); + remove[i] = true; + } + // a new number of axes: the layout of this shape does not apply + MatShape result; + result.dims = 0; + for (int i = 0; i < dims; i++) + if (!remove[i]) + result.p[result.dims++] = p[i]; + return result; +} + +MatShape MatShape::unsqueeze(const std::vector& axes) const +{ + CV_Assert(dims >= 0); + if (layout == DATA_LAYOUT_BLOCK) + return toBlockOf(toSemantic(*this).unsqueeze(axes), *this, "unsqueeze"); + const int outDims = dims + (int)axes.size(); + CV_CheckLE(outDims, (int)MAX_DIMS, "unsqueeze: too many dimensions"); + bool insert[MAX_DIMS] = {false}; + for (int a : axes) + { + int i = normalizeShapeAxis(a, outDims); + CV_Check(a, !insert[i], "unsqueeze: duplicate axis"); + insert[i] = true; + } + // a new number of axes: the layout of this shape does not apply + MatShape result; + result.dims = outDims; + for (int i = 0, j = 0; i < outDims; i++) + result.p[i] = insert[i] ? 1 : p[j++]; + return result; +} + +MatShape MatShape::flatten(int startAxis, int endAxis) const +{ + CV_Assert(dims >= 0); + if (layout == DATA_LAYOUT_BLOCK) + return toBlockOf(toSemantic(*this).flatten(startAxis, endAxis), *this, "flatten"); + if (dims == 0) + { + CV_Check(startAxis, startAxis == 0 || startAxis == -1, "flatten: axis is out of range"); + CV_Check(endAxis, endAxis == 0 || endAxis == -1, "flatten: axis is out of range"); + return MatShape({1}); + } + int start = normalizeShapeAxis(startAxis, dims), end = normalizeShapeAxis(endAxis, dims); + CV_CheckLE(start, end, "flatten: startAxis must not follow endAxis"); + int64 merged = 1; + for (int i = start; i <= end; i++) + merged *= p[i]; + CV_CheckLE((double)merged, (double)INT_MAX, "flatten: the result is too big"); + // a new number of axes: the layout of this shape does not apply + MatShape result; + result.dims = 0; + for (int i = 0; i < dims; i++) + { + if (i == start) + result.p[result.dims++] = (int)merged; + else if (i < start || i > end) + result.p[result.dims++] = p[i]; + } + return result; +} + +MatShape MatShape::reshape(const MatShape& newShape, bool allowZero) const +{ + CV_Assert(dims >= 0 && newShape.dims >= 0); + if (layout == DATA_LAYOUT_BLOCK) + return toBlockOf(toSemantic(*this).reshape(newShape, allowZero), *this, "reshape"); + // a new number of axes: neither the layout of this shape nor the one of the spec applies + MatShape result; + result.dims = newShape.dims; + std::copy(newShape.p, newShape.p + newShape.dims, result.p); + int inferred = -1; + int64 known = 1; + for (int i = 0; i < result.dims; i++) + { + int& sz = result.p[i]; + if (sz == -1) + { + CV_Check(i, inferred < 0, "reshape: at most one axis may be -1"); + inferred = i; + continue; + } + CV_Check(sz, sz >= 0, "reshape: sizes must be -1 or non-negative"); + if (sz == 0 && !allowZero) + { + CV_Check(i, i < dims, "reshape: 0 refers to an axis the source does not have"); + sz = p[i]; + } + known *= sz; + } + const int64 total_ = (int64)total(); + if (inferred >= 0) + { + CV_Check((double)known, known != 0, "reshape: cannot infer the -1 axis next to a zero-size axis"); + CV_Check((double)total_, total_ % known == 0, "reshape: the number of elements does not match"); + CV_CheckLE((double)(total_/known), (double)INT_MAX, "reshape: the result is too big"); + result.p[inferred] = (int)(total_/known); + } + else if (known != total_) + CV_Error_(Error::StsBadArg, ("reshape: the number of elements does not match: %lld vs %lld", + (long long)known, (long long)total_)); + return result; +} + MatShape MatShape::expand(const MatShape& another) const { if (dims == 0) diff --git a/modules/core/src/shape_ops.cpp b/modules/core/src/shape_ops.cpp new file mode 100644 index 0000000000..a82f681100 --- /dev/null +++ b/modules/core/src/shape_ops.cpp @@ -0,0 +1,65 @@ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// Copyright (C) 2026, BigVision LLC, all rights reserved. +// Third party copyrights are property of their respective owners. + +#include "precomp.hpp" + +namespace cv { + +// In place (dst shares the data of a continuous src) only the header changes; otherwise the +// elements are copied into dst. +static void reshapeTo(InputArray _src, OutputArray _dst, const MatShape& shape) +{ + Mat src = _src.getMat(); + CV_Assert(shape.total() == src.total()); + if (_dst.kind() == _InputArray::MAT && src.isContinuous()) + { + Mat& dst = _dst.getMatRef(); + if (dst.data && dst.data == src.data) + { + dst = src.reshape(0, shape); + return; + } + } + _dst.create(shape, src.type()); + Mat dst = _dst.getMat(); + if (dst.data == src.data) + return; + if (dst.isContinuous()) + { + src.copyTo(Mat(src.dims, src.size.p, src.type(), dst.data)); + return; + } + // create() keeps a preallocated destination of the right shape even when it is strided + Mat tmp; + src.copyTo(tmp); + Mat(shape.dims, shape.p, src.type(), tmp.data).copyTo(dst); +} + +void squeeze(InputArray src, OutputArray dst, const std::vector& axes) +{ + CV_INSTRUMENT_REGION(); + reshapeTo(src, dst, src.shape().squeeze(axes)); +} + +void unsqueeze(InputArray src, OutputArray dst, const std::vector& axes) +{ + CV_INSTRUMENT_REGION(); + reshapeTo(src, dst, src.shape().unsqueeze(axes)); +} + +void flatten(InputArray src, OutputArray dst, int startAxis, int endAxis) +{ + CV_INSTRUMENT_REGION(); + reshapeTo(src, dst, src.shape().flatten(startAxis, endAxis)); +} + +void reshape(InputArray src, OutputArray dst, const std::vector& newShape, bool allowZero) +{ + CV_INSTRUMENT_REGION(); + reshapeTo(src, dst, src.shape().reshape(MatShape(newShape), allowZero)); +} + +} // namespace cv diff --git a/modules/core/test/test_shape_ops.cpp b/modules/core/test/test_shape_ops.cpp new file mode 100644 index 0000000000..a6aae4d478 --- /dev/null +++ b/modules/core/test/test_shape_ops.cpp @@ -0,0 +1,149 @@ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// Copyright (C) 2026, BigVision LLC, all rights reserved. +// Third party copyrights are property of their respective owners. + +#include "test_precomp.hpp" + +namespace opencv_test { namespace { + +static std::vector shapeOf(const Mat& m) { return std::vector(m.size.p, m.size.p + m.dims); } + +TEST(Core_MatShape, shape_ops) +{ + MatShape s({2, 1, 3, 1}); + EXPECT_EQ(MatShape({2, 3}), s.squeeze()); + EXPECT_EQ(MatShape({2, 3, 1}), s.squeeze({1})); + EXPECT_EQ(MatShape({2, 1, 3}), s.squeeze({-1})); + EXPECT_ANY_THROW(s.squeeze({0})); + EXPECT_ANY_THROW(s.squeeze({1, -3})); + EXPECT_EQ(MatShape::scalar(), MatShape({1, 1}).squeeze()); + + MatShape t({2, 3}); + EXPECT_EQ(MatShape({1, 2, 3}), t.unsqueeze({0})); + EXPECT_EQ(MatShape({2, 3, 1}), t.unsqueeze({-1})); + EXPECT_EQ(MatShape({1, 2, 1, 3}), t.unsqueeze({0, 2})); + EXPECT_ANY_THROW(t.unsqueeze({0, 0})); + EXPECT_EQ(MatShape({1}), MatShape::scalar().unsqueeze({0})); + + MatShape u({2, 3, 4, 5}); + EXPECT_EQ(MatShape({120}), u.flatten()); + EXPECT_EQ(MatShape({2, 60}), u.flatten(1)); + EXPECT_EQ(MatShape({2, 12, 5}), u.flatten(1, 2)); + EXPECT_EQ(MatShape({2, 3, 4, 5}), u.flatten(2, 2)); + EXPECT_ANY_THROW(u.flatten(2, 1)); + EXPECT_EQ(MatShape({1}), MatShape::scalar().flatten()); + EXPECT_ANY_THROW(MatShape::scalar().flatten(1)); + + EXPECT_EQ(MatShape({6, 20}), u.reshape(MatShape({6, -1}))); + EXPECT_EQ(MatShape({2, 3, 20}), u.reshape(MatShape({0, 0, -1}))); + EXPECT_ANY_THROW(MatShape({0, 4}).reshape(MatShape({0, -1}))); // -1 next to a zero-size axis is ambiguous + EXPECT_EQ(MatShape({0, 7}), MatShape({0, 4}).reshape(MatShape({0, 7}), true)); + EXPECT_ANY_THROW(u.reshape(MatShape({7, -1}))); + EXPECT_ANY_THROW(u.reshape(MatShape({-1, -1}))); + EXPECT_ANY_THROW(u.reshape(MatShape({121}))); +} + +// A block ('NC1HWC0') shape survives these operations as long as N and C are untouched. +TEST(Core_MatShape, shape_ops_block_layout) +{ + const MatShape nchw({2, 12, 5, 5}, DATA_LAYOUT_NCHW); + const MatShape blk = nchw.toLayout(DATA_LAYOUT_BLOCK, 8); + ASSERT_EQ(MatShape({2, 2, 5, 5, 8}, DATA_LAYOUT_BLOCK, 12), blk); + ASSERT_EQ((size_t)800, blk.total()); // padded: C 12 rounds up to 2*8 + + // the spatial axes may move + const MatShape flat = blk.flatten(2); + EXPECT_EQ(MatShape({2, 2, 25, 8}, DATA_LAYOUT_BLOCK, 12), flat); + EXPECT_EQ(DATA_LAYOUT_BLOCK, flat.layout); + EXPECT_EQ(12, flat.C); + EXPECT_EQ(blk.total(), flat.total()); + EXPECT_EQ(nchw.flatten(2), flat.toLayout(DATA_LAYOUT_NCHW)); + + EXPECT_EQ(MatShape({2, 2, 1, 5, 5, 8}, DATA_LAYOUT_BLOCK, 12), blk.unsqueeze({2})); + EXPECT_EQ(MatShape({2, 2, 25, 8}, DATA_LAYOUT_BLOCK, 12), blk.reshape(MatShape({0, 0, -1}))); + EXPECT_EQ(MatShape({2, 2, 5, 5, 8}, DATA_LAYOUT_BLOCK, 12), blk.squeeze()); + + const MatShape blk1 = MatShape({2, 12, 1, 5}, DATA_LAYOUT_NCHW).toLayout(DATA_LAYOUT_BLOCK, 8); + EXPECT_EQ(MatShape({2, 2, 5, 8}, DATA_LAYOUT_BLOCK, 12), blk1.squeeze()); + + // moving N or C would repack the padded C0 lanes + EXPECT_ANY_THROW(blk.flatten()); + EXPECT_ANY_THROW(blk.flatten(0, 1)); + EXPECT_ANY_THROW(blk.unsqueeze({0})); + EXPECT_ANY_THROW(blk.reshape(MatShape({2, 6, 50}))); + EXPECT_ANY_THROW(blk.reshape(MatShape({4, 12, 25}))); + EXPECT_ANY_THROW(blk.reshape(MatShape({-1}))); + + const MatShape blkN1 = MatShape({1, 12, 5, 5}, DATA_LAYOUT_NCHW).toLayout(DATA_LAYOUT_BLOCK, 8); + EXPECT_ANY_THROW(blkN1.squeeze({0})); + + // the counts a caller addresses are logical: C == 12, not the padded C1 * C0 == 16 + EXPECT_EQ(MatShape({2, 12, 25}, DATA_LAYOUT_NCHW), blk.toLayout(DATA_LAYOUT_NCHW).flatten(2)); + EXPECT_ANY_THROW(blk.reshape(MatShape({2, 16, 25}))); +} + +TEST(Core_ShapeOps, views_and_copies) +{ + RNG& rng = theRNG(); + Mat a({2, 1, 3, 4}, CV_32FC2); + rng.fill(a, RNG::UNIFORM, -1, 1); + + Mat s; + cv::squeeze(a, s); + EXPECT_EQ(std::vector({2, 3, 4}), shapeOf(s)); + EXPECT_NE(a.data, s.data); // the output does not alias the input + EXPECT_EQ(CV_32FC2, s.type()); + EXPECT_EQ(0, cvtest::norm(Mat(1, 48, CV_32FC1, a.data), Mat(1, 48, CV_32FC1, s.data), NORM_INF)); + + Mat u, f, r; + cv::unsqueeze(a, u, {0, -1}); + EXPECT_EQ(std::vector({1, 2, 1, 3, 4, 1}), shapeOf(u)); + cv::flatten(a, f, 1); + EXPECT_EQ(std::vector({2, 12}), shapeOf(f)); + cv::reshape(a, r, {-1, 6}); + EXPECT_EQ(std::vector({4, 6}), shapeOf(r)); + EXPECT_EQ(0, cvtest::norm(Mat(1, 48, CV_32FC1, a.data), Mat(1, 48, CV_32FC1, r.data), NORM_INF)); + + // a preallocated destination of the new shape gets a copy + Mat pre({2, 3, 4}, CV_32FC2, Scalar::all(0)); + uchar* p0 = pre.data; + cv::squeeze(a, pre); + EXPECT_EQ(p0, pre.data); + EXPECT_EQ(0, cvtest::norm(Mat(1, 48, CV_32FC1, a.data), Mat(1, 48, CV_32FC1, pre.data), NORM_INF)); + + // a non-continuous source is copied + Mat big({4, 6}, CV_8U), roi = big(Rect(1, 1, 4, 2)), fr; + rng.fill(big, RNG::UNIFORM, 0, 256); + cv::flatten(roi, fr); + ASSERT_EQ(std::vector({8}), shapeOf(fr)); + for (int i = 0; i < 8; i++) + EXPECT_EQ(roi.at(i/4, i%4), fr.at(i)); + + // in place: only the header changes + Mat b({1, 5}, CV_16S, Scalar(3)); + const uchar* bdata = b.data; + cv::squeeze(b, b); + EXPECT_EQ(std::vector({5}), shapeOf(b)); + EXPECT_EQ(bdata, b.data); + + // a preallocated strided destination of the target shape gets a copy, not an assert + Mat canvas(10, 10, CV_8U, Scalar(0)), view = canvas(Rect(0, 0, 4, 5)); + Mat src5x4({1, 5, 4}, CV_8U); + rng.fill(src5x4, RNG::UNIFORM, 0, 256); + cv::squeeze(src5x4, view); + ASSERT_EQ(std::vector({5, 4}), shapeOf(view)); + EXPECT_FALSE(view.isContinuous()); + for (int i = 0; i < 5; i++) + for (int j = 0; j < 4; j++) + EXPECT_EQ(src5x4.at(0, i, j), view.at(i, j)); + + // to and from 0-d + Mat one({1, 1}, CV_32F, Scalar(2)), sc; + cv::squeeze(one, sc); + EXPECT_EQ(0, sc.dims); + EXPECT_EQ(2.f, sc.at(0)); +} + +}} // namespace diff --git a/modules/dnn/src/layers/flatten_layer.cpp b/modules/dnn/src/layers/flatten_layer.cpp index 7d29408f0c..9dab1b9bcb 100644 --- a/modules/dnn/src/layers/flatten_layer.cpp +++ b/modules/dnn/src/layers/flatten_layer.cpp @@ -136,19 +136,7 @@ public: outputShapeVec.push_back((int)inner); } else { - CV_Assert(endAxis >= startAxis && endAxis <= numAxes); - - size_t flattenedDimensionSize = total(inputs[0], startAxis, endAxis + 1); - - for (int i = 0; i < startAxis; i++) - { - outputShapeVec.push_back(inputs[0][i]); - } - outputShapeVec.push_back(flattenedDimensionSize); - for (size_t i = endAxis + 1; i < numAxes; i++) - { - outputShapeVec.push_back(inputs[0][i]); - } + outputShapeVec = inputs[0].flatten(startAxis, endAxis); } outputs.resize(inputs.size(), outputShapeVec); diff --git a/modules/dnn/src/layers/reshape2_layer.cpp b/modules/dnn/src/layers/reshape2_layer.cpp index 8667d2dd8c..db6be73b51 100644 --- a/modules/dnn/src/layers/reshape2_layer.cpp +++ b/modules/dnn/src/layers/reshape2_layer.cpp @@ -143,43 +143,20 @@ public: MatShape getOutShape(const MatShape& inpShape, const MatShape& shapeSpec) const { - MatShape outShape = shapeSpec; - int m1idx = -1; - int i, ndims = outShape.dims; - int64_t outTotal = 1; - for (i = 0; i < ndims; i++) { - if (outShape[i] < 0) { - CV_Assert(outShape[i] == -1); - if (m1idx >= 0) { - CV_Error(Error::StsBadArg, "invalid shape spec, there must be at most one '-1'"); - } - m1idx = i; - } - else { - if (outShape[i] == 0) { - if (i >= inpShape.dims) { - CV_Error(Error::StsBadArg, "cannot copy dimension from the input tensor"); - } - outShape[i] = inpShape[i]; - } - outTotal *= outShape[i]; + // legacy models: (1, k) with the wrong k means (1, total); 0 is resolved first so + // that the (0, k) spelling is recognized too + if (shapeSpec.dims == 2) + { + int d0 = shapeSpec[0] == 0 && inpShape.dims > 0 ? inpShape[0] : shapeSpec[0]; + int d1 = shapeSpec[1] == 0 && inpShape.dims > 1 ? inpShape[1] : shapeSpec[1]; + const int64_t inpTotal = (int64_t)inpShape.total(); + if (d0 == 1 && d1 > 0 && (int64_t)d1 != inpTotal) + { + CV_CheckLE((double)inpTotal, (double)INT_MAX, "reshape: the result is too big"); + return MatShape({1, (int)inpTotal}); } } - - int64_t inpTotal = (int64_t)inpShape.total(); - if (m1idx >= 0) { - int64_t autoSize = inpTotal/outTotal; - CV_Assert(autoSize <= INT_MAX && autoSize*outTotal == inpTotal); - outShape[m1idx] = (int)autoSize; - } - else if (outTotal != inpTotal && ndims == 2 && outShape[0] == 1 && outShape[1] > 0) { - outShape[1] = (int)(inpTotal / outShape[0]); - } - else { - CV_Assert(outTotal == inpTotal); - } - - return outShape; + return inpShape.reshape(shapeSpec); } bool getMemoryShapes(const std::vector &inputs, diff --git a/modules/dnn/src/layers/squeeze_layer.cpp b/modules/dnn/src/layers/squeeze_layer.cpp index 2f8191ea62..18b3f47895 100644 --- a/modules/dnn/src/layers/squeeze_layer.cpp +++ b/modules/dnn/src/layers/squeeze_layer.cpp @@ -52,35 +52,7 @@ public: MatShape getOutShape(const MatShape& inpShape, const std::vector& axes_) const { - bool squeezeMask[MatShape::MAX_DIMS]; - - if (axes_.empty()) { - // remove all 1's - for (int i = 0; i < inpShape.dims; i++) - squeezeMask[i] = inpShape[i] == 1; - } else { - for (int i = 0; i < inpShape.dims; i++) - squeezeMask[i] = false; - for (int a: axes_) { - int a_ = normalize_axis(a, inpShape.dims); - if (squeezeMask[a_]) { - CV_Error_(Error::StsBadArg, ("duplicate squeezed axis #%d", a)); - } - if (inpShape[a_] != 1) { - CV_Error_(Error::StsBadArg, ("squeezed axis #%d (== %d) != 1", a, inpShape[a_])); - } - squeezeMask[a_] = true; - } - } - - MatShape outShape(inpShape.dims); - int j = 0; - for (int i = 0; i < inpShape.dims; i++) { - if (!squeezeMask[i]) - outShape[j++] = inpShape[i]; - } - outShape.dims = j; - return outShape; + return inpShape.squeeze(axes_); } bool isDataShuffling() const CV_OVERRIDE { return true; } diff --git a/modules/dnn/src/layers/unsqueeze_layer.cpp b/modules/dnn/src/layers/unsqueeze_layer.cpp index 80e8283416..bad8b528a2 100644 --- a/modules/dnn/src/layers/unsqueeze_layer.cpp +++ b/modules/dnn/src/layers/unsqueeze_layer.cpp @@ -52,32 +52,7 @@ public: MatShape getOutShape(const MatShape& inpShape, const std::vector& axes_) const { - bool unsqueezeMask[MatShape::MAX_DIMS]; - - int outDims = inpShape.dims + (int)axes_.size(); - CV_Assert(0 <= outDims && outDims <= MatShape::MAX_DIMS); - - for (int i = 0; i < outDims; i++) - unsqueezeMask[i] = false; - for (int a: axes_) { - int a_ = normalize_axis(a, outDims); - if (unsqueezeMask[a_]) { - CV_Error_(Error::StsBadArg, ("duplicate unsqueezed axis #%d", a)); - } - unsqueezeMask[a_] = true; - } - - MatShape outShape(outDims); - int j = 0; - for (int i = 0; i < outDims; i++) { - if (unsqueezeMask[i]) - outShape[i] = 1; - else { - CV_Assert(j < inpShape.dims); - outShape[i] = inpShape[j++]; - } - } - return outShape; + return inpShape.unsqueeze(axes_); } bool isDataShuffling() const CV_OVERRIDE { return true; } diff --git a/modules/dnn/test/test_layers.cpp b/modules/dnn/test/test_layers.cpp index f68ef8bccc..431bce6ed8 100644 --- a/modules/dnn/test/test_layers.cpp +++ b/modules/dnn/test/test_layers.cpp @@ -110,6 +110,30 @@ TEST(Layer_Test_Reshape, Accuracy) } } +// Legacy models spell a flatten-to-(1, total) as a 2D shape whose second element is wrong. +static MatShape reshape2OutShape(const MatShape& inpShape, const std::vector& spec) +{ + LayerParams params; + params.set("shape", DictValue::arrayInt(spec.data(), spec.size())); + Ptr layer = LayerFactory::createLayerInstance("Reshape2", params); + + std::vector outputs, internals; + layer->getMemoryShapes(std::vector(1, inpShape), 1, outputs, internals); + return outputs[0]; +} + +TEST(Layer_Test_Reshape2, legacy_shape_spec) +{ + EXPECT_EQ(MatShape({1, 7}), reshape2OutShape(MatShape({1, 7}), {1, 5})); + EXPECT_EQ(MatShape({1, 7}), reshape2OutShape(MatShape({1, 7}), {0, 5})); + EXPECT_EQ(MatShape({1, 24}), reshape2OutShape(MatShape({1, 2, 3, 4}), {0, 5})); + + // a spec that already matches is not the legacy case + EXPECT_EQ(MatShape({1, 7}), reshape2OutShape(MatShape({7}), {1, 7})); + EXPECT_EQ(MatShape({1, 24}), reshape2OutShape(MatShape({1, 2, 3, 4}), {0, -1})); + EXPECT_EQ(MatShape({2, 12}), reshape2OutShape(MatShape({2, 3, 4}), {0, -1})); +} + class Layer_LSTM_Test : public ::testing::Test { public: