Path: blob/master/modules/dnn/src/layers/slice_layer.cpp
16337 views
/*M///////////////////////////////////////////////////////////////////////////////////////1//2// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.3//4// By downloading, copying, installing or using the software you agree to this license.5// If you do not agree to this license, do not download, install,6// copy or use the software.7//8//9// License Agreement10// For Open Source Computer Vision Library11//12// Copyright (C) 2013, OpenCV Foundation, all rights reserved.13// Copyright (C) 2017, Intel Corporation, all rights reserved.14// Third party copyrights are property of their respective owners.15//16// Redistribution and use in source and binary forms, with or without modification,17// are permitted provided that the following conditions are met:18//19// * Redistribution's of source code must retain the above copyright notice,20// this list of conditions and the following disclaimer.21//22// * Redistribution's in binary form must reproduce the above copyright notice,23// this list of conditions and the following disclaimer in the documentation24// and/or other materials provided with the distribution.25//26// * The name of the copyright holders may not be used to endorse or promote products27// derived from this software without specific prior written permission.28//29// This software is provided by the copyright holders and contributors "as is" and30// any express or implied warranties, including, but not limited to, the implied31// warranties of merchantability and fitness for a particular purpose are disclaimed.32// In no event shall the Intel Corporation or contributors be liable for any direct,33// indirect, incidental, special, exemplary, or consequential damages34// (including, but not limited to, procurement of substitute goods or services;35// loss of use, data, or profits; or business interruption) however caused36// and on any theory of liability, whether in contract, strict liability,37// or tort (including negligence or otherwise) arising in any way out of38// the use of this software, even if advised of the possibility of such damage.39//40//M*/4142#include "../precomp.hpp"43#include "../op_inf_engine.hpp"44#include "layers_common.hpp"45#include <opencv2/dnn/shape_utils.hpp>4647#ifdef HAVE_OPENCL48#include "opencl_kernels_dnn.hpp"49#endif5051namespace cv52{53namespace dnn54{5556class SliceLayerImpl CV_FINAL : public SliceLayer57{58public:59SliceLayerImpl(const LayerParams& params)60{61setParamsFrom(params);62axis = params.get<int>("axis", 1);63if (params.has("slice_point"))64{65CV_Assert(!params.has("begin") && !params.has("size") && !params.has("end"));66const DictValue &indicesValue = params.get("slice_point");67sliceRanges.resize(indicesValue.size() + 1,68std::vector<Range>(axis + 1, Range::all()));69int prevSlice = 0;70for (int i = 0; i < indicesValue.size(); ++i)71{72sliceRanges[i][axis].start = prevSlice;73sliceRanges[i][axis].end = indicesValue.get<int>(i);74prevSlice = sliceRanges[i][axis].end;75}76sliceRanges.back()[axis].start = prevSlice;77}78else if (params.has("begin"))79{80CV_Assert(params.has("size") ^ params.has("end"));81const DictValue &begins = params.get("begin");82const DictValue &sizesOrEnds = params.has("size") ? params.get("size") : params.get("end");83CV_Assert(begins.size() == sizesOrEnds.size());8485sliceRanges.resize(1);86sliceRanges[0].resize(begins.size(), Range::all());87for (int i = 0; i < begins.size(); ++i)88{89int start = begins.get<int>(i);90int sizeOrEnd = sizesOrEnds.get<int>(i); // It may be negative to reverse indexation.91CV_Assert(start >= 0);9293sliceRanges[0][i].start = start;94if (params.has("size"))95{96int size = sizeOrEnd;97CV_Assert(size == -1 || size > 0); // -1 value means range [start, axis_size).98sliceRanges[0][i].end = size > 0 ? (start + size) : -1; // We'll finalize a negative value later.99}100else101{102int end = sizeOrEnd;103CV_Assert(end < 0 || end > start); // End index is excluded.104sliceRanges[0][i].end = end; // We'll finalize a negative value later.105}106}107}108}109110virtual bool supportBackend(int backendId) CV_OVERRIDE111{112return backendId == DNN_BACKEND_OPENCV ||113backendId == DNN_BACKEND_INFERENCE_ENGINE && sliceRanges.size() == 1 && sliceRanges[0].size() == 4;114}115116bool getMemoryShapes(const std::vector<MatShape> &inputs,117const int requiredOutputs,118std::vector<MatShape> &outputs,119std::vector<MatShape> &internals) const CV_OVERRIDE120{121CV_Assert(inputs.size() == 1);122MatShape inpShape = inputs[0];123124if (!sliceRanges.empty())125{126outputs.resize(sliceRanges.size(), inpShape);127for (int i = 0; i < outputs.size(); ++i)128{129CV_Assert(sliceRanges[i].size() <= inpShape.size());130for (int j = 0; j < sliceRanges[i].size(); ++j)131{132outputs[i][j] = clamp(sliceRanges[i][j], inpShape[j]).size();133}134}135}136else // Divide input blob on equal parts by axis.137{138CV_Assert(0 <= axis && axis < inpShape.size());139CV_Assert(requiredOutputs > 0 && inpShape[axis] % requiredOutputs == 0);140inpShape[axis] /= requiredOutputs;141outputs.resize(requiredOutputs, inpShape);142}143return false;144}145146void finalize(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr) CV_OVERRIDE147{148std::vector<Mat> inputs, outputs;149inputs_arr.getMatVector(inputs);150outputs_arr.getMatVector(outputs);151152CV_Assert(inputs.size() == 1);153const MatSize& inpShape = inputs[0].size;154155if (sliceRanges.empty())156{157// Divide input blob on equal parts by axis.158int outAxisSize = inpShape[axis] / outputs.size();159sliceRanges.resize(outputs.size(),160std::vector<Range>(axis + 1, Range::all()));161int prevSlice = 0;162for (int i = 0; i < outputs.size(); ++i)163{164sliceRanges[i][axis].start = prevSlice;165sliceRanges[i][axis].end = sliceRanges[i][axis].start + outAxisSize;166prevSlice = sliceRanges[i][axis].end;167}168}169else170CV_Assert(outputs.size() == sliceRanges.size());171172for (int i = 0; i < outputs.size(); ++i)173{174CV_Assert(sliceRanges[i].size() <= inpShape.dims());175// Clamp.176for (int j = 0; j < sliceRanges[i].size(); ++j)177{178sliceRanges[i][j] = clamp(sliceRanges[i][j], inpShape[j]);179}180// Fill the rest of ranges.181for (int j = sliceRanges[i].size(); j < inpShape.dims(); ++j)182{183sliceRanges[i].push_back(Range::all());184}185}186}187188#ifdef HAVE_OPENCL189bool forward_ocl(InputArrayOfArrays inputs_, OutputArrayOfArrays outputs_, OutputArrayOfArrays internals_)190{191std::vector<UMat> inputs;192std::vector<UMat> outputs;193194bool use_half = (inputs_.depth() == CV_16S);195inputs_.getUMatVector(inputs);196outputs_.getUMatVector(outputs);197198if (inputs[0].dims < 4 || (total(shape(outputs[0]), 0, 2) % 4 != 0) ||199(total(shape(outputs[0]), 2) % 4 != 0))200return false;201202String opts;203if (use_half)204opts = "-DDtype=half -DDtype4=half4 -DDtype8=half8";205else206opts = "-DDtype=float -DDtype4=float4 -DDtype8=float8";207const UMat& inpMat = inputs[0];208for (size_t i = 0; i < outputs.size(); i++)209{210int groups = outputs[i].size[0];211int channels = outputs[i].size[1];212int rows = outputs[i].size[2];213int cols = outputs[i].size[3];214215ocl::Kernel kernel("slice", ocl::dnn::slice_oclsrc, opts);216size_t local[] = { 128 };217size_t global[] = { (size_t)groups * channels / 4 * local[0] };218int idx = 0;219kernel.set(idx++, ocl::KernelArg::PtrReadOnly(inpMat));220kernel.set(idx++, (int)(inpMat.size[2] * inpMat.size[3]));221kernel.set(idx++, (int)(rows * cols));222kernel.set(idx++, (int)inpMat.size[3]);223kernel.set(idx++, (int)cols);224kernel.set(idx++, (int)sliceRanges[i][2].start);225kernel.set(idx++, (int)sliceRanges[i][3].start);226kernel.set(idx++, ocl::KernelArg::PtrWriteOnly(outputs[i]));227bool ret = kernel.run(1, global, local, false);228if (!ret)229return false;230}231232return true;233}234#endif235236void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE237{238CV_TRACE_FUNCTION();239CV_TRACE_ARG_VALUE(name, "name", name.c_str());240241CV_OCL_RUN(IS_DNN_OPENCL_TARGET(preferableTarget),242forward_ocl(inputs_arr, outputs_arr, internals_arr))243244std::vector<Mat> inputs, outputs;245inputs_arr.getMatVector(inputs);246outputs_arr.getMatVector(outputs);247248const Mat& inpMat = inputs[0];249CV_Assert(outputs.size() == sliceRanges.size());250for (size_t i = 0; i < outputs.size(); i++)251{252inpMat(sliceRanges[i]).copyTo(outputs[i]);253}254}255256virtual Ptr<BackendNode> initInfEngine(const std::vector<Ptr<BackendWrapper> >& inputs) CV_OVERRIDE257{258#ifdef HAVE_INF_ENGINE259InferenceEngine::DataPtr input = infEngineDataNode(inputs[0]);260InferenceEngine::LayerParams lp;261lp.name = name;262lp.type = "Crop";263lp.precision = InferenceEngine::Precision::FP32;264std::shared_ptr<InferenceEngine::CropLayer> ieLayer(new InferenceEngine::CropLayer(lp));265266CV_Assert(sliceRanges.size() == 1);267268int from, to, step;269if (preferableTarget == DNN_TARGET_MYRIAD)270{271from = 1;272to = sliceRanges[0].size() + 1;273step = 1;274}275else276{277from = sliceRanges[0].size() - 1;278to = -1;279step = -1;280}281for (int i = from; i != to; i += step)282{283ieLayer->axis.push_back(i);284ieLayer->offset.push_back(sliceRanges[0][i].start);285ieLayer->dim.push_back(sliceRanges[0][i].end - sliceRanges[0][i].start);286}287return Ptr<BackendNode>(new InfEngineBackendNode(ieLayer));288289#endif // HAVE_INF_ENGINE290return Ptr<BackendNode>();291}292};293294Ptr<SliceLayer> SliceLayer::create(const LayerParams& params)295{296return Ptr<SliceLayer>(new SliceLayerImpl(params));297}298299}300}301302303