1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
5 // By downloading, copying, installing or using the software you agree to this license.
6 // If you do not agree to this license, do not download, install,
7 // copy or use the software.
11 // For Open Source Computer Vision Library
13 // Copyright (C) 2013, OpenCV Foundation, all rights reserved.
14 // Copyright (C) 2017, Intel Corporation, all rights reserved.
15 // Third party copyrights are property of their respective owners.
17 // Redistribution and use in source and binary forms, with or without modification,
18 // are permitted provided that the following conditions are met:
20 // * Redistribution's of source code must retain the above copyright notice,
21 // this list of conditions and the following disclaimer.
23 // * Redistribution's in binary form must reproduce the above copyright notice,
24 // this list of conditions and the following disclaimer in the documentation
25 // and/or other materials provided with the distribution.
27 // * The name of the copyright holders may not be used to endorse or promote products
28 // derived from this software without specific prior written permission.
30 // This software is provided by the copyright holders and contributors "as is" and
31 // any express or implied warranties, including, but not limited to, the implied
32 // warranties of merchantability and fitness for a particular purpose are disclaimed.
33 // In no event shall the Intel Corporation or contributors be liable for any direct,
34 // indirect, incidental, special, exemplary, or consequential damages
35 // (including, but not limited to, procurement of substitute goods or services;
36 // loss of use, data, or profits; or business interruption) however caused
37 // and on any theory of liability, whether in contract, strict liability,
38 // or tort (including negligence or otherwise) arising in any way out of
39 // the use of this software, even if advised of the possibility of such damage.
43 #include "../precomp.hpp"
44 #include "layers_common.hpp"
45 #include "../op_inf_engine.hpp"
46 #include <opencv2/dnn/shape_utils.hpp>
53 static void computeShapeByReshapeMask(const MatShape &srcShape,
54 const MatShape &maskShape,
55 Range srcRange /*= Range::all()*/,
58 int srcShapeSize = (int)srcShape.size();
59 int maskShapeSize = (int)maskShape.size();
61 if (srcRange == Range::all())
62 srcRange = Range(0, srcShapeSize);
65 int sz = srcRange.size();
66 srcRange.start = clamp(srcRange.start, srcShapeSize);
67 srcRange.end = srcRange.end == INT_MAX ? srcShapeSize : srcRange.start + sz;
70 bool explicitMask = !maskShape.empty(); // All mask values are positive.
71 for (int i = 0, n = maskShape.size(); i < n && explicitMask; ++i)
73 explicitMask = maskShape[i] > 0;
75 // Working range of source shape is a range where area(src) == area(mask).
78 int maskTotal = total(maskShape);
79 // Go from the end of mask until we collect required total.
81 for (int i = srcRange.end - 1; i >= srcRange.start; --i)
85 if (total(srcShape, i, srcRange.end) != maskTotal)
87 srcRange.start = i + 1;
98 matched = total(srcShape, i, srcRange.end) == maskTotal;
101 while (total(srcShape, srcRange.start, srcRange.end) != maskTotal && srcRange.start > 0)
105 CV_Assert(total(srcShape, srcRange.start, srcRange.end) == maskTotal);
108 CV_Assert(0 <= srcRange.start && srcRange.start <= srcRange.end && srcRange.end <= srcShapeSize);
109 int dstShapeSize = srcShapeSize - srcRange.size() + maskShapeSize;
110 dstShape.resize(dstShapeSize);
112 std::copy(srcShape.begin(), srcShape.begin() + srcRange.start, dstShape.begin());
113 std::copy(srcShape.begin() + srcRange.end, srcShape.begin() + srcShapeSize, dstShape.begin() + srcRange.start + maskShapeSize);
116 for (int i = 0; i < maskShapeSize; i++)
118 if (maskShape[i] > 0)
120 dstShape[srcRange.start + i] = maskShape[i];
122 else if (maskShape[i] == 0)
124 if (srcRange.start + i >= srcShapeSize)
125 CV_Error(Error::StsBadArg, format("Copy dim[%d] (which has zero size) is out of the source shape bounds", srcRange.start + i));
126 dstShape[srcRange.start + i] = srcShape[srcRange.start + i];
128 else if (maskShape[i] == -1)
131 CV_Error(Error::StsAssert, "Duplicate of inferred dim (which is denoted by -1)");
132 inferDim = srcRange.start + i;
133 dstShape[inferDim] = 1;
136 CV_Error(Error::StsBadArg, "maskShape[i] >= -1");
139 size_t srcTotal = total(srcShape);
140 size_t dstTotal = total(dstShape);
141 CV_Assert(dstTotal != 0);
145 if (srcTotal % dstTotal != 0)
146 CV_Error(Error::StsBackTrace, "Can't infer a dim denoted by -1");
148 dstShape[inferDim] = (int)(srcTotal / dstTotal);
152 CV_Assert(srcTotal == dstTotal);
157 class ReshapeLayerImpl CV_FINAL : public ReshapeLayer
160 ReshapeLayerImpl(const LayerParams& params)
162 setParamsFrom(params);
163 int axis = params.get<int>("axis", 0);
164 int numAxes = params.get<int>("num_axes", -1);
165 CV_Assert(numAxes >= -1);
166 newShapeRange = (numAxes == -1) ? Range(axis, INT_MAX) : Range(axis, axis + numAxes);
168 newShapeDesc.clear();
169 if (params.has("dim"))
171 const DictValue ¶mShape = params.get("dim");
172 int i, dims = paramShape.size();
173 newShapeDesc.resize(dims);
174 for (i = 0; i < dims; i++)
175 newShapeDesc[i] = paramShape.get<int>(i);
179 virtual bool supportBackend(int backendId) CV_OVERRIDE
181 return backendId == DNN_BACKEND_OPENCV ||
182 (backendId == DNN_BACKEND_INFERENCE_ENGINE && haveInfEngine());
185 bool getMemoryShapes(const std::vector<MatShape> &inputs,
186 const int requiredOutputs,
187 std::vector<MatShape> &outputs,
188 std::vector<MatShape> &internals) const CV_OVERRIDE
190 if (inputs.size() == 1 || inputs.size() == requiredOutputs)
193 for (size_t i = 0; i < inputs.size(); i++)
195 outputs.push_back(MatShape());
196 computeShapeByReshapeMask(inputs[i], newShapeDesc, newShapeRange, outputs.back());
201 CV_Assert_N(inputs.size() == 2, total(inputs[0]) == total(inputs[1]));
202 outputs.assign(1, inputs[1]);
207 void finalize(InputArrayOfArrays, OutputArrayOfArrays outputs_arr) CV_OVERRIDE
209 std::vector<Mat> outputs;
210 outputs_arr.getMatVector(outputs);
212 CV_Assert(!outputs.empty());
213 outShapes.resize(outputs.size());
214 for (int i = 0; i < outputs.size(); ++i)
215 outShapes[i] = shape(outputs[i]);
218 bool forward_ocl(InputArrayOfArrays inps, OutputArrayOfArrays outs, OutputArrayOfArrays internals)
220 std::vector<UMat> inputs;
221 std::vector<UMat> outputs;
223 inps.getUMatVector(inputs);
224 outs.getUMatVector(outputs);
226 for (size_t i = 0; i < outputs.size(); i++)
228 UMat srcBlob = inputs[i];
229 void *src_handle = inputs[i].handle(ACCESS_READ);
230 void *dst_handle = outputs[i].handle(ACCESS_WRITE);
231 if (src_handle != dst_handle)
233 UMat umat = srcBlob.reshape(1, (int)outShapes[i].size(), &outShapes[i][0]);
234 umat.copyTo(outputs[i]);
237 outs.assign(outputs);
242 void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE
245 CV_TRACE_ARG_VALUE(name, "name", name.c_str());
247 CV_OCL_RUN(IS_DNN_OPENCL_TARGET(preferableTarget),
248 forward_ocl(inputs_arr, outputs_arr, internals_arr))
250 std::vector<Mat> inputs, outputs;
251 inputs_arr.getMatVector(inputs);
252 outputs_arr.getMatVector(outputs);
253 for (size_t i = 0; i < outputs.size(); i++)
255 Mat srcBlob = inputs[i];
256 if (outputs[i].data != srcBlob.data)
257 srcBlob.reshape(1, shape(outputs[i])).copyTo(outputs[i]);
261 #ifdef HAVE_INF_ENGINE
262 virtual Ptr<BackendNode> initInfEngine(const std::vector<Ptr<BackendWrapper> >& inputs) CV_OVERRIDE
264 InferenceEngine::Builder::ReshapeLayer ieLayer(name);
265 CV_Assert(outShapes.size() == 1);
266 ieLayer.setDims(outShapes[0]);
267 return Ptr<BackendNode>(new InfEngineBackendNode(ieLayer));
269 #endif // HAVE_INF_ENGINE
272 std::vector<MatShape> outShapes;
275 Ptr<ReshapeLayer> ReshapeLayer::create(const LayerParams& params)
277 return Ptr<ReshapeLayer>(new ReshapeLayerImpl(params));