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_cuda.hpp"
46 #include "../op_inf_engine.hpp"
47 #include <opencv2/dnn/shape_utils.hpp>
50 #include "../cuda4dnn/primitives/reshape.hpp"
51 using namespace cv::dnn::cuda4dnn;
59 static void computeShapeByReshapeMask(const MatShape &srcShape,
60 const MatShape &maskShape,
61 Range srcRange /*= Range::all()*/,
64 int srcShapeSize = (int)srcShape.size();
65 int maskShapeSize = (int)maskShape.size();
67 if (srcRange == Range::all())
68 srcRange = Range(0, srcShapeSize);
71 int sz = srcRange.size();
72 srcRange.start = clamp(srcRange.start, srcShapeSize);
73 srcRange.end = srcRange.end == INT_MAX ? srcShapeSize : srcRange.start + sz;
76 bool explicitMask = !maskShape.empty(); // All mask values are positive.
77 for (int i = 0, n = maskShape.size(); i < n && explicitMask; ++i)
79 explicitMask = maskShape[i] > 0;
81 // Working range of source shape is a range where area(src) == area(mask).
84 int maskTotal = total(maskShape);
85 // Go from the end of mask until we collect required total.
87 for (int i = srcRange.end - 1; i >= srcRange.start; --i)
91 if (total(srcShape, i, srcRange.end) != maskTotal)
93 srcRange.start = i + 1;
104 matched = total(srcShape, i, srcRange.end) == maskTotal;
107 while (total(srcShape, srcRange.start, srcRange.end) != maskTotal && srcRange.start > 0)
111 CV_Assert(total(srcShape, srcRange.start, srcRange.end) == maskTotal);
114 CV_Assert(0 <= srcRange.start && srcRange.start <= srcRange.end && srcRange.end <= srcShapeSize);
115 int dstShapeSize = srcShapeSize - srcRange.size() + maskShapeSize;
116 dstShape.resize(dstShapeSize);
118 std::copy(srcShape.begin(), srcShape.begin() + srcRange.start, dstShape.begin());
119 std::copy(srcShape.begin() + srcRange.end, srcShape.begin() + srcShapeSize, dstShape.begin() + srcRange.start + maskShapeSize);
122 for (int i = 0; i < maskShapeSize; i++)
124 if (maskShape[i] > 0)
126 dstShape[srcRange.start + i] = maskShape[i];
128 else if (maskShape[i] == 0)
130 if (srcRange.start + i >= srcShapeSize)
131 CV_Error(Error::StsBadArg, format("Copy dim[%d] (which has zero size) is out of the source shape bounds", srcRange.start + i));
132 dstShape[srcRange.start + i] = srcShape[srcRange.start + i];
134 else if (maskShape[i] == -1)
137 CV_Error(Error::StsAssert, "Duplicate of inferred dim (which is denoted by -1)");
138 inferDim = srcRange.start + i;
139 dstShape[inferDim] = 1;
142 CV_Error(Error::StsBadArg, "maskShape[i] >= -1");
145 size_t srcTotal = total(srcShape);
146 size_t dstTotal = total(dstShape);
147 CV_Assert(dstTotal != 0);
151 if (srcTotal % dstTotal != 0)
152 CV_Error(Error::StsBackTrace, "Can't infer a dim denoted by -1");
154 dstShape[inferDim] = (int)(srcTotal / dstTotal);
158 CV_Assert(srcTotal == dstTotal);
163 class ReshapeLayerImpl CV_FINAL : public ReshapeLayer
166 ReshapeLayerImpl(const LayerParams& params)
168 setParamsFrom(params);
169 int axis = params.get<int>("axis", 0);
170 int numAxes = params.get<int>("num_axes", -1);
171 CV_Assert(numAxes >= -1);
172 newShapeRange = (numAxes == -1) ? Range(axis, INT_MAX) : Range(axis, axis + numAxes);
174 newShapeDesc.clear();
175 if (params.has("dim"))
177 const DictValue ¶mShape = params.get("dim");
178 int i, dims = paramShape.size();
179 newShapeDesc.resize(dims);
180 for (i = 0; i < dims; i++)
181 newShapeDesc[i] = paramShape.get<int>(i);
185 virtual bool supportBackend(int backendId) CV_OVERRIDE
187 return backendId == DNN_BACKEND_OPENCV ||
188 backendId == DNN_BACKEND_CUDA ||
189 (backendId == DNN_BACKEND_INFERENCE_ENGINE && haveInfEngine());
192 bool getMemoryShapes(const std::vector<MatShape> &inputs,
193 const int requiredOutputs,
194 std::vector<MatShape> &outputs,
195 std::vector<MatShape> &internals) const CV_OVERRIDE
197 if (inputs.size() == 1 || inputs.size() == requiredOutputs)
200 for (size_t i = 0; i < inputs.size(); i++)
202 outputs.push_back(MatShape());
203 computeShapeByReshapeMask(inputs[i], newShapeDesc, newShapeRange, outputs.back());
208 CV_Assert_N(inputs.size() == 2, total(inputs[0]) == total(inputs[1]));
209 outputs.assign(1, inputs[1]);
214 void finalize(InputArrayOfArrays, OutputArrayOfArrays outputs_arr) CV_OVERRIDE
216 std::vector<Mat> outputs;
217 outputs_arr.getMatVector(outputs);
219 CV_Assert(!outputs.empty());
220 outShapes.resize(outputs.size());
221 for (int i = 0; i < outputs.size(); ++i)
222 outShapes[i] = shape(outputs[i]);
225 bool forward_ocl(InputArrayOfArrays inps, OutputArrayOfArrays outs, OutputArrayOfArrays internals)
227 std::vector<UMat> inputs;
228 std::vector<UMat> outputs;
230 inps.getUMatVector(inputs);
231 outs.getUMatVector(outputs);
233 for (size_t i = 0; i < outputs.size(); i++)
235 UMat srcBlob = inputs[i];
236 void *src_handle = inputs[i].handle(ACCESS_READ);
237 void *dst_handle = outputs[i].handle(ACCESS_WRITE);
238 if (src_handle != dst_handle)
240 UMat umat = srcBlob.reshape(1, (int)outShapes[i].size(), &outShapes[i][0]);
241 umat.copyTo(outputs[i]);
244 outs.assign(outputs);
249 void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE
252 CV_TRACE_ARG_VALUE(name, "name", name.c_str());
254 CV_OCL_RUN(IS_DNN_OPENCL_TARGET(preferableTarget),
255 forward_ocl(inputs_arr, outputs_arr, internals_arr))
257 std::vector<Mat> inputs, outputs;
258 inputs_arr.getMatVector(inputs);
259 outputs_arr.getMatVector(outputs);
260 for (size_t i = 0; i < outputs.size(); i++)
262 Mat srcBlob = inputs[i];
263 if (outputs[i].data != srcBlob.data)
264 srcBlob.reshape(1, shape(outputs[i])).copyTo(outputs[i]);
269 Ptr<BackendNode> initCUDA(
271 const std::vector<Ptr<BackendWrapper>>& inputs,
272 const std::vector<Ptr<BackendWrapper>>& outputs
275 auto context = reinterpret_cast<csl::CSLContext*>(context_);
276 return make_cuda_node<cuda4dnn::ReshapeOp>(preferableTarget, std::move(context->stream));
280 #ifdef HAVE_INF_ENGINE
281 virtual Ptr<BackendNode> initInfEngine(const std::vector<Ptr<BackendWrapper> >& inputs) CV_OVERRIDE
283 InferenceEngine::Builder::ReshapeLayer ieLayer(name);
284 CV_Assert(outShapes.size() == 1);
285 ieLayer.setDims(outShapes[0]);
286 return Ptr<BackendNode>(new InfEngineBackendNode(ieLayer));
288 #endif // HAVE_INF_ENGINE
291 std::vector<MatShape> outShapes;
294 Ptr<ReshapeLayer> ReshapeLayer::create(const LayerParams& params)
296 return Ptr<ReshapeLayer>(new ReshapeLayerImpl(params));