Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/modules/dnn/src/layers/slice_layer.cpp
16337 views
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 "../op_inf_engine.hpp"
45
#include "layers_common.hpp"
46
#include <opencv2/dnn/shape_utils.hpp>
47
48
#ifdef HAVE_OPENCL
49
#include "opencl_kernels_dnn.hpp"
50
#endif
51
52
namespace cv
53
{
54
namespace dnn
55
{
56
57
class SliceLayerImpl CV_FINAL : public SliceLayer
58
{
59
public:
60
SliceLayerImpl(const LayerParams& params)
61
{
62
setParamsFrom(params);
63
axis = params.get<int>("axis", 1);
64
if (params.has("slice_point"))
65
{
66
CV_Assert(!params.has("begin") && !params.has("size") && !params.has("end"));
67
const DictValue &indicesValue = params.get("slice_point");
68
sliceRanges.resize(indicesValue.size() + 1,
69
std::vector<Range>(axis + 1, Range::all()));
70
int prevSlice = 0;
71
for (int i = 0; i < indicesValue.size(); ++i)
72
{
73
sliceRanges[i][axis].start = prevSlice;
74
sliceRanges[i][axis].end = indicesValue.get<int>(i);
75
prevSlice = sliceRanges[i][axis].end;
76
}
77
sliceRanges.back()[axis].start = prevSlice;
78
}
79
else if (params.has("begin"))
80
{
81
CV_Assert(params.has("size") ^ params.has("end"));
82
const DictValue &begins = params.get("begin");
83
const DictValue &sizesOrEnds = params.has("size") ? params.get("size") : params.get("end");
84
CV_Assert(begins.size() == sizesOrEnds.size());
85
86
sliceRanges.resize(1);
87
sliceRanges[0].resize(begins.size(), Range::all());
88
for (int i = 0; i < begins.size(); ++i)
89
{
90
int start = begins.get<int>(i);
91
int sizeOrEnd = sizesOrEnds.get<int>(i); // It may be negative to reverse indexation.
92
CV_Assert(start >= 0);
93
94
sliceRanges[0][i].start = start;
95
if (params.has("size"))
96
{
97
int size = sizeOrEnd;
98
CV_Assert(size == -1 || size > 0); // -1 value means range [start, axis_size).
99
sliceRanges[0][i].end = size > 0 ? (start + size) : -1; // We'll finalize a negative value later.
100
}
101
else
102
{
103
int end = sizeOrEnd;
104
CV_Assert(end < 0 || end > start); // End index is excluded.
105
sliceRanges[0][i].end = end; // We'll finalize a negative value later.
106
}
107
}
108
}
109
}
110
111
virtual bool supportBackend(int backendId) CV_OVERRIDE
112
{
113
return backendId == DNN_BACKEND_OPENCV ||
114
backendId == DNN_BACKEND_INFERENCE_ENGINE && sliceRanges.size() == 1 && sliceRanges[0].size() == 4;
115
}
116
117
bool getMemoryShapes(const std::vector<MatShape> &inputs,
118
const int requiredOutputs,
119
std::vector<MatShape> &outputs,
120
std::vector<MatShape> &internals) const CV_OVERRIDE
121
{
122
CV_Assert(inputs.size() == 1);
123
MatShape inpShape = inputs[0];
124
125
if (!sliceRanges.empty())
126
{
127
outputs.resize(sliceRanges.size(), inpShape);
128
for (int i = 0; i < outputs.size(); ++i)
129
{
130
CV_Assert(sliceRanges[i].size() <= inpShape.size());
131
for (int j = 0; j < sliceRanges[i].size(); ++j)
132
{
133
outputs[i][j] = clamp(sliceRanges[i][j], inpShape[j]).size();
134
}
135
}
136
}
137
else // Divide input blob on equal parts by axis.
138
{
139
CV_Assert(0 <= axis && axis < inpShape.size());
140
CV_Assert(requiredOutputs > 0 && inpShape[axis] % requiredOutputs == 0);
141
inpShape[axis] /= requiredOutputs;
142
outputs.resize(requiredOutputs, inpShape);
143
}
144
return false;
145
}
146
147
void finalize(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr) CV_OVERRIDE
148
{
149
std::vector<Mat> inputs, outputs;
150
inputs_arr.getMatVector(inputs);
151
outputs_arr.getMatVector(outputs);
152
153
CV_Assert(inputs.size() == 1);
154
const MatSize& inpShape = inputs[0].size;
155
156
if (sliceRanges.empty())
157
{
158
// Divide input blob on equal parts by axis.
159
int outAxisSize = inpShape[axis] / outputs.size();
160
sliceRanges.resize(outputs.size(),
161
std::vector<Range>(axis + 1, Range::all()));
162
int prevSlice = 0;
163
for (int i = 0; i < outputs.size(); ++i)
164
{
165
sliceRanges[i][axis].start = prevSlice;
166
sliceRanges[i][axis].end = sliceRanges[i][axis].start + outAxisSize;
167
prevSlice = sliceRanges[i][axis].end;
168
}
169
}
170
else
171
CV_Assert(outputs.size() == sliceRanges.size());
172
173
for (int i = 0; i < outputs.size(); ++i)
174
{
175
CV_Assert(sliceRanges[i].size() <= inpShape.dims());
176
// Clamp.
177
for (int j = 0; j < sliceRanges[i].size(); ++j)
178
{
179
sliceRanges[i][j] = clamp(sliceRanges[i][j], inpShape[j]);
180
}
181
// Fill the rest of ranges.
182
for (int j = sliceRanges[i].size(); j < inpShape.dims(); ++j)
183
{
184
sliceRanges[i].push_back(Range::all());
185
}
186
}
187
}
188
189
#ifdef HAVE_OPENCL
190
bool forward_ocl(InputArrayOfArrays inputs_, OutputArrayOfArrays outputs_, OutputArrayOfArrays internals_)
191
{
192
std::vector<UMat> inputs;
193
std::vector<UMat> outputs;
194
195
bool use_half = (inputs_.depth() == CV_16S);
196
inputs_.getUMatVector(inputs);
197
outputs_.getUMatVector(outputs);
198
199
if (inputs[0].dims < 4 || (total(shape(outputs[0]), 0, 2) % 4 != 0) ||
200
(total(shape(outputs[0]), 2) % 4 != 0))
201
return false;
202
203
String opts;
204
if (use_half)
205
opts = "-DDtype=half -DDtype4=half4 -DDtype8=half8";
206
else
207
opts = "-DDtype=float -DDtype4=float4 -DDtype8=float8";
208
const UMat& inpMat = inputs[0];
209
for (size_t i = 0; i < outputs.size(); i++)
210
{
211
int groups = outputs[i].size[0];
212
int channels = outputs[i].size[1];
213
int rows = outputs[i].size[2];
214
int cols = outputs[i].size[3];
215
216
ocl::Kernel kernel("slice", ocl::dnn::slice_oclsrc, opts);
217
size_t local[] = { 128 };
218
size_t global[] = { (size_t)groups * channels / 4 * local[0] };
219
int idx = 0;
220
kernel.set(idx++, ocl::KernelArg::PtrReadOnly(inpMat));
221
kernel.set(idx++, (int)(inpMat.size[2] * inpMat.size[3]));
222
kernel.set(idx++, (int)(rows * cols));
223
kernel.set(idx++, (int)inpMat.size[3]);
224
kernel.set(idx++, (int)cols);
225
kernel.set(idx++, (int)sliceRanges[i][2].start);
226
kernel.set(idx++, (int)sliceRanges[i][3].start);
227
kernel.set(idx++, ocl::KernelArg::PtrWriteOnly(outputs[i]));
228
bool ret = kernel.run(1, global, local, false);
229
if (!ret)
230
return false;
231
}
232
233
return true;
234
}
235
#endif
236
237
void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE
238
{
239
CV_TRACE_FUNCTION();
240
CV_TRACE_ARG_VALUE(name, "name", name.c_str());
241
242
CV_OCL_RUN(IS_DNN_OPENCL_TARGET(preferableTarget),
243
forward_ocl(inputs_arr, outputs_arr, internals_arr))
244
245
std::vector<Mat> inputs, outputs;
246
inputs_arr.getMatVector(inputs);
247
outputs_arr.getMatVector(outputs);
248
249
const Mat& inpMat = inputs[0];
250
CV_Assert(outputs.size() == sliceRanges.size());
251
for (size_t i = 0; i < outputs.size(); i++)
252
{
253
inpMat(sliceRanges[i]).copyTo(outputs[i]);
254
}
255
}
256
257
virtual Ptr<BackendNode> initInfEngine(const std::vector<Ptr<BackendWrapper> >& inputs) CV_OVERRIDE
258
{
259
#ifdef HAVE_INF_ENGINE
260
InferenceEngine::DataPtr input = infEngineDataNode(inputs[0]);
261
InferenceEngine::LayerParams lp;
262
lp.name = name;
263
lp.type = "Crop";
264
lp.precision = InferenceEngine::Precision::FP32;
265
std::shared_ptr<InferenceEngine::CropLayer> ieLayer(new InferenceEngine::CropLayer(lp));
266
267
CV_Assert(sliceRanges.size() == 1);
268
269
int from, to, step;
270
if (preferableTarget == DNN_TARGET_MYRIAD)
271
{
272
from = 1;
273
to = sliceRanges[0].size() + 1;
274
step = 1;
275
}
276
else
277
{
278
from = sliceRanges[0].size() - 1;
279
to = -1;
280
step = -1;
281
}
282
for (int i = from; i != to; i += step)
283
{
284
ieLayer->axis.push_back(i);
285
ieLayer->offset.push_back(sliceRanges[0][i].start);
286
ieLayer->dim.push_back(sliceRanges[0][i].end - sliceRanges[0][i].start);
287
}
288
return Ptr<BackendNode>(new InfEngineBackendNode(ieLayer));
289
290
#endif // HAVE_INF_ENGINE
291
return Ptr<BackendNode>();
292
}
293
};
294
295
Ptr<SliceLayer> SliceLayer::create(const LayerParams& params)
296
{
297
return Ptr<SliceLayer>(new SliceLayerImpl(params));
298
}
299
300
}
301
}
302
303