f1250e7e3e0a69b5c75266db0c7560f2aaa5ad67
[platform/upstream/opencv.git] / modules / dnn / src / layers / flatten_layer.cpp
1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
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.
8 //
9 //
10 //                           License Agreement
11 //                For Open Source Computer Vision Library
12 //
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.
16 //
17 // Redistribution and use in source and binary forms, with or without modification,
18 // are permitted provided that the following conditions are met:
19 //
20 //   * Redistribution's of source code must retain the above copyright notice,
21 //     this list of conditions and the following disclaimer.
22 //
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.
26 //
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.
29 //
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.
40 //
41 //M*/
42
43 #include "../precomp.hpp"
44 #include "layers_common.hpp"
45 #include "../op_inf_engine.hpp"
46 #include <float.h>
47 #include <algorithm>
48 #include <opencv2/dnn/shape_utils.hpp>
49
50 namespace cv
51 {
52 namespace dnn
53 {
54
55 class FlattenLayerImpl CV_FINAL : public FlattenLayer
56 {
57 public:
58     FlattenLayerImpl(const LayerParams &params)
59     {
60         _startAxis = params.get<int>("axis", 1);
61         _endAxis = params.get<int>("end_axis", -1);
62         setParamsFrom(params);
63     }
64
65     virtual bool supportBackend(int backendId) CV_OVERRIDE
66     {
67         return backendId == DNN_BACKEND_OPENCV ||
68                (backendId == DNN_BACKEND_INFERENCE_ENGINE && haveInfEngine());
69     }
70
71     bool getMemoryShapes(const std::vector<MatShape> &inputs,
72                          const int requiredOutputs,
73                          std::vector<MatShape> &outputs,
74                          std::vector<MatShape> &internals) const CV_OVERRIDE
75     {
76         CV_Assert(inputs.size() > 0);
77         for (size_t i = 1; i < inputs.size(); i++)
78         {
79             CV_Assert(inputs[i] == inputs[0]);
80         }
81
82         int numAxes = inputs[0].size();
83         int startAxis = clamp(_startAxis, numAxes);
84         int endAxis = clamp(_endAxis, numAxes);
85
86         CV_Assert(startAxis >= 0);
87         CV_Assert(endAxis >= startAxis && endAxis < (int)numAxes);
88
89         size_t flattenedDimensionSize = total(inputs[0], startAxis, endAxis + 1);
90
91         MatShape outputShapeVec;
92         for (int i = 0; i < startAxis; i++)
93         {
94             outputShapeVec.push_back(inputs[0][i]);
95         }
96         outputShapeVec.push_back(flattenedDimensionSize);
97         for (size_t i = endAxis + 1; i < numAxes; i++)
98         {
99             outputShapeVec.push_back(inputs[0][i]);
100         }
101         CV_Assert(outputShapeVec.size() <= 4);
102
103         outputs.resize(inputs.size(), outputShapeVec);
104
105         return true;
106     }
107
108     void finalize(InputArrayOfArrays inputs_arr, OutputArrayOfArrays) CV_OVERRIDE
109     {
110         std::vector<Mat> inputs;
111         inputs_arr.getMatVector(inputs);
112
113         int numAxes = inputs[0].dims;
114         _startAxis = clamp(_startAxis, numAxes);
115         _endAxis = clamp(_endAxis, numAxes);
116     }
117
118 #ifdef HAVE_OPENCL
119     bool forward_ocl(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr)
120     {
121         std::vector<UMat> inpvec;
122         std::vector<UMat> outputs;
123
124         inputs_arr.getUMatVector(inpvec);
125         outputs_arr.getUMatVector(outputs);
126
127         std::vector<UMat*> inputs(inpvec.size());
128         for (int i = 0; i < inpvec.size(); i++)
129             inputs[i] = &inpvec[i];
130
131         for (size_t i = 0; i < inputs.size(); i++)
132         {
133             MatShape outShape = shape(outputs[i]);
134             UMat& output = outputs_arr.getUMatRef(i);
135             output = inputs[i]->reshape(1, (int)outShape.size(), &outShape[0]);
136         }
137
138         return true;
139     }
140 #endif
141
142     void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE
143     {
144         CV_TRACE_FUNCTION();
145         CV_TRACE_ARG_VALUE(name, "name", name.c_str());
146
147         CV_OCL_RUN(IS_DNN_OPENCL_TARGET(preferableTarget) &&
148                    outputs_arr.isUMatVector(),
149                    forward_ocl(inputs_arr, outputs_arr, internals_arr))
150
151         std::vector<Mat> inputs, outputs;
152         inputs_arr.getMatVector(inputs);
153         outputs_arr.getMatVector(outputs);
154
155         for (size_t i = 0; i < inputs.size(); i++)
156         {
157             MatShape outShape = shape(outputs[i]);
158             if (inputs[i].data != outputs[i].data)
159             {
160                 inputs[i].reshape(1, (int)outShape.size(), &outShape[0]).copyTo(outputs[i]);
161             }
162         }
163     }
164
165 #ifdef HAVE_INF_ENGINE
166     virtual Ptr<BackendNode> initInfEngine(const std::vector<Ptr<BackendWrapper> >& inputs) CV_OVERRIDE
167     {
168         InferenceEngine::Builder::Layer ieLayer(name);
169         ieLayer.setName(name);
170         ieLayer.setType("Flatten");
171         ieLayer.getParameters()["axis"] = (size_t)_startAxis;
172         ieLayer.getParameters()["end_axis"] = _endAxis;  // Do not cast to size_t because it might be negative.
173         ieLayer.setInputPorts(std::vector<InferenceEngine::Port>(1));
174         ieLayer.setOutputPorts(std::vector<InferenceEngine::Port>(1));
175         return Ptr<BackendNode>(new InfEngineBackendNode(ieLayer));
176     }
177 #endif  // HAVE_INF_ENGINE
178
179     int _startAxis;
180     int _endAxis;
181 };
182
183 Ptr<FlattenLayer> FlattenLayer::create(const LayerParams& params)
184 {
185     return Ptr<FlattenLayer>(new FlattenLayerImpl(params));
186 }
187
188 }
189 }