onnx_importer.cpp 60.5 KB
Newer Older
1 2 3 4 5 6 7 8
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.

// Copyright (C) 2018, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.

#include "../precomp.hpp"
9
#include <opencv2/dnn/shape_utils.hpp>
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

#ifdef HAVE_PROTOBUF

#include <iostream>
#include <fstream>
#include <string>
#include <limits>
#include <algorithm>


#if defined(__GNUC__) && __GNUC__ >= 5
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wsuggest-override"
#endif
#include "opencv-onnx.pb.h"
#if defined(__GNUC__) && __GNUC__ >= 5
#pragma GCC diagnostic pop
#endif

D
Dmitry Kurtaev 已提交
29 30
#include "onnx_graph_simplifier.hpp"

31 32 33 34 35 36 37 38 39 40 41
namespace cv {
namespace dnn {
CV__DNN_EXPERIMENTAL_NS_BEGIN


class ONNXImporter
{
    opencv_onnx::ModelProto model_proto;
    struct LayerInfo {
        int layerId;
        int outputId;
42
        LayerInfo(int _layerId = 0, int _outputId = 0) : layerId(_layerId), outputId(_outputId) {}
43 44 45 46 47 48 49 50 51
    };

    std::map<std::string, Mat> getGraphTensors(
                                    const opencv_onnx::GraphProto& graph_proto);
    Mat getBlob(const opencv_onnx::NodeProto& node_proto, const std::map<std::string, Mat>& constBlobs, int index);

    LayerParams getLayerParams(const opencv_onnx::NodeProto& node_proto);
    bool isCeilMode(const LayerParams& layerParams);

52 53 54 55 56
    void addLayer(Net& dstNet, LayerParams& layerParams,
                  const opencv_onnx::NodeProto& node_proto,
                  std::map<std::string, LayerInfo>& layer_id,
                  std::map<std::string, MatShape>& outShapes);

57 58 59 60 61 62 63 64 65 66
public:

    ONNXImporter(const char *onnxFile)
    {
        std::fstream input(onnxFile, std::ios::in | std::ios::binary);

        if (!model_proto.ParseFromIstream(&input))
            CV_Error(Error::StsUnsupportedFormat, "Failed to parse onnx model");
    }

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    ONNXImporter(const char* buffer, size_t sizeBuffer)
    {
        struct _Buf : public std::streambuf
        {
            _Buf(const char* buffer, size_t sizeBuffer)
            {
                char* p = const_cast<char*>(buffer);
                setg(p, p, p + sizeBuffer);
            }
        };

        _Buf buf(buffer, sizeBuffer);
        std::istream input(&buf);

        if (!model_proto.ParseFromIstream(&input))
            CV_Error(Error::StsUnsupportedFormat, "Failed to parse onnx model from in-memory byte array.");
    }

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    void populateNet(Net dstNet);
};

inline void replaceLayerParam(LayerParams& layerParams, const String& oldKey, const String& newKey)
{
    if (layerParams.has(oldKey)) {
        layerParams.set(newKey, layerParams.get(oldKey));
        layerParams.erase(oldKey);
    }
}

void releaseONNXTensor(opencv_onnx::TensorProto& tensor_proto)
{
    if (!tensor_proto.raw_data().empty()) {
        delete tensor_proto.release_raw_data();
    }
}

103
void runLayer(LayerParams& params, const std::vector<Mat>& inputs,
104 105
              std::vector<Mat>& outputs)
{
106
    Ptr<Layer> layer = LayerFactory::createLayerInstance(params.type, params);
A
Alexander Alekhin 已提交
107 108
    CV_Assert((bool)layer);

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
    std::vector<MatShape> inpShapes(inputs.size());
    int ddepth = CV_32F;
    for (size_t i = 0; i < inputs.size(); ++i)
    {
        inpShapes[i] = shape(inputs[i]);
        if (i > 0 && ddepth != inputs[i].depth())
            CV_Error(Error::StsNotImplemented, "Mixed input data types.");
        ddepth = inputs[i].depth();
    }

    std::vector<MatShape> outShapes, internalShapes;
    layer->getMemoryShapes(inpShapes, 0, outShapes, internalShapes);

    std::vector<Mat> internals(internalShapes.size());
    outputs.resize(outShapes.size());
    for (size_t i = 0; i < outShapes.size(); ++i)
        outputs[i].create(outShapes[i], ddepth);
    for (size_t i = 0; i < internalShapes.size(); ++i)
        internals[i].create(internalShapes[i], ddepth);

    layer->finalize(inputs, outputs);
    layer->forward(inputs, outputs, internals);
}

133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
std::map<std::string, Mat> ONNXImporter::getGraphTensors(
                                        const opencv_onnx::GraphProto& graph_proto)
{
  opencv_onnx::TensorProto tensor_proto;
  std::map<std::string, Mat> layers_weights;

  for (int i = 0; i < graph_proto.initializer_size(); i++)
  {
    tensor_proto = graph_proto.initializer(i);
    Mat mat = getMatFromTensor(tensor_proto);
    releaseONNXTensor(tensor_proto);
    layers_weights.insert(std::make_pair(tensor_proto.name(), mat));
  }
  return layers_weights;
}

149 150 151 152 153 154
static DictValue parse(const ::google::protobuf::RepeatedField< ::google::protobuf::int64>& src) {
    std::vector<int32_t> dst(src.size());
    convertInt64ToInt32(src, dst, src.size());
    return DictValue::arrayInt(&dst[0], src.size());
}

155 156 157 158 159 160 161 162 163 164
LayerParams ONNXImporter::getLayerParams(const opencv_onnx::NodeProto& node_proto)
{
    LayerParams lp;
    for(int i = 0; i < node_proto.attribute_size(); i++)
    {
        opencv_onnx::AttributeProto attribute_proto = node_proto.attribute(i);
        std::string attribute_name = attribute_proto.name();

        if(attribute_name == "kernel_shape")
        {
165 166
            CV_Assert(attribute_proto.ints_size() == 2 || attribute_proto.ints_size() == 3);
            lp.set("kernel_size", parse(attribute_proto.ints()));
167 168 169
        }
        else if(attribute_name == "strides")
        {
170 171
            CV_Assert(attribute_proto.ints_size() == 2 || attribute_proto.ints_size() == 3);
            lp.set("stride", parse(attribute_proto.ints()));
172 173 174
        }
        else if(attribute_name == "pads")
        {
D
Dmitry Kurtaev 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
            if (node_proto.op_type() == "Pad")
            {
                // Padding layer.
                // Paddings are in order begin0, begin1, .. beginN, end0, end1, ..., endN.
                // We need to shuffle it to begin0, end0, begin1, end1, ...
                CV_Assert(attribute_proto.ints_size() % 2 == 0);
                const int dims = attribute_proto.ints_size() / 2;
                std::vector<int32_t> paddings;
                paddings.reserve(attribute_proto.ints_size());
                for (int i = 0; i < dims; ++i)
                {
                    paddings.push_back(attribute_proto.ints(i));
                    paddings.push_back(attribute_proto.ints(dims + i));
                }
                lp.set("paddings", DictValue::arrayInt(&paddings[0], paddings.size()));
            }
            else
            {
                // Convolution or pooling.
194 195
                CV_Assert(attribute_proto.ints_size() == 4 || attribute_proto.ints_size() == 6);
                lp.set("pad", parse(attribute_proto.ints()));
D
Dmitry Kurtaev 已提交
196
            }
197 198 199 200 201 202 203 204 205 206 207 208
        }
        else if(attribute_name == "auto_pad")
        {
            if (attribute_proto.s() == "SAME_UPPER" || attribute_proto.s() == "SAME_LOWER") {
                lp.set("pad_mode",  "SAME");
            }
            else if (attribute_proto.s() == "VALID") {
                lp.set("pad_mode", "VALID");
            }
        }
        else if(attribute_name == "dilations")
        {
209 210
            CV_Assert(attribute_proto.ints_size() == 2 || attribute_proto.ints_size() == 3);
            lp.set("dilation", parse(attribute_proto.ints()));
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
        }
        else if (attribute_proto.has_i())
        {
            ::google::protobuf::int64 src = attribute_proto.i();
            if (src < std::numeric_limits<int32_t>::min() || src > std::numeric_limits<int32_t>::max())
                CV_Error(Error::StsOutOfRange, "Input is out of OpenCV 32S range");
            else
                lp.set(attribute_name, saturate_cast<int32_t>(src));
        }
        else if (attribute_proto.has_f())
        {
            lp.set(attribute_name, attribute_proto.f());
        }
        else if (attribute_proto.has_s())
        {
            lp.set(attribute_name, attribute_proto.s());
        }
        else if (attribute_proto.floats_size() > 0)
        {
            lp.set(attribute_name, DictValue::arrayReal(
D
Dmitry Kurtaev 已提交
231
                attribute_proto.floats().data(), attribute_proto.floats_size()));
232 233 234
        }
        else if (attribute_proto.ints_size() > 0)
        {
235
            lp.set(attribute_proto.name(), parse(attribute_proto.ints()));
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
        }
        else if (attribute_proto.has_t())
        {
            opencv_onnx::TensorProto tensor = attribute_proto.t();
            Mat blob = getMatFromTensor(tensor);
            lp.blobs.push_back(blob);
        }
        else if (attribute_proto.has_g() || attribute_proto.strings_size() > 0 ||
                    attribute_proto.tensors_size() > 0 || attribute_proto.graphs_size() > 0)
        {
                CV_Error(Error::StsNotImplemented, "Unexpected attribute type");
        }
        else
            CV_Error(Error::StsNotImplemented, "Unsupported attribute type");
    }
    return lp;
}

Mat ONNXImporter::getBlob(const opencv_onnx::NodeProto& node_proto,
                    const std::map<std::string, Mat>& constBlobs, int index)
{
    CV_Assert(index < node_proto.input_size());
    std::map<std::string, Mat>::const_iterator constBlob;
    constBlob = constBlobs.find(node_proto.input(index));
    if (constBlob == constBlobs.end()) {
        CV_Error(Error::StsObjectNotFound,
             "Blob " + node_proto.input(index) + " not found in const blobs");
    }
    return constBlob->second;
}

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
void ONNXImporter::addLayer(Net& dstNet, LayerParams& layerParams,
                            const opencv_onnx::NodeProto& node_proto,
                            std::map<std::string, LayerInfo>& layer_id,
                            std::map<std::string, MatShape>& outShapes)
{
    std::map<std::string, LayerInfo>::iterator layerId;
    std::map<std::string, MatShape>::iterator shapeIt;

    int id = dstNet.addLayer(layerParams.name, layerParams.type, layerParams);
    for (int i = 0; i < node_proto.output_size(); ++i)
    {
        layer_id.insert(std::make_pair(node_proto.output(i), LayerInfo(id, i)));
    }

    std::vector<MatShape> layerInpShapes, layerOutShapes, layerInternalShapes;
    int inpNum = 0;
    for (int j = 0; j < node_proto.input_size(); j++) {
        layerId = layer_id.find(node_proto.input(j));
        if (layerId != layer_id.end()) {
            dstNet.connect(layerId->second.layerId, layerId->second.outputId, id, inpNum);
            ++inpNum;
            // Collect input shapes.
            shapeIt = outShapes.find(node_proto.input(j));
            CV_Assert(shapeIt != outShapes.end());
            layerInpShapes.push_back(shapeIt->second);
        }
    }
    // Compute shape of output blob for this layer.
    Ptr<Layer> layer = dstNet.getLayer(id);
    layer->getMemoryShapes(layerInpShapes, 0, layerOutShapes, layerInternalShapes);
    for (int i = 0; i < node_proto.output_size() && i < (int)layerOutShapes.size(); ++i)
    {
        outShapes[node_proto.output(i)] = layerOutShapes[i];
    }
}

303 304 305 306 307 308 309 310 311
static void addConstant(const std::string& name,
                        const Mat& blob,
                        std::map<std::string, Mat>& constBlobs,
                        std::map<std::string, MatShape>& outShapes)
{
    constBlobs.insert(std::make_pair(name, blob));
    outShapes.insert(std::make_pair(name, shape(blob)));
}

312 313 314 315
void ONNXImporter::populateNet(Net dstNet)
{
    CV_Assert(model_proto.has_graph());
    opencv_onnx::GraphProto graph_proto = model_proto.graph();
D
Dmitry Kurtaev 已提交
316 317 318

    simplifySubgraphs(graph_proto);

319
    std::map<std::string, Mat> constBlobs = getGraphTensors(graph_proto);
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
    // List of internal blobs shapes.
    std::map<std::string, MatShape> outShapes;
    // Add all the inputs shapes. It includes as constant blobs as network's inputs shapes.
    for (int i = 0; i < graph_proto.input_size(); ++i)
    {
        opencv_onnx::ValueInfoProto valueInfoProto = graph_proto.input(i);
        CV_Assert(valueInfoProto.has_type());
        opencv_onnx::TypeProto typeProto = valueInfoProto.type();
        CV_Assert(typeProto.has_tensor_type());
        opencv_onnx::TypeProto::Tensor tensor = typeProto.tensor_type();
        CV_Assert(tensor.has_shape());
        opencv_onnx::TensorShapeProto tensorShape = tensor.shape();

        MatShape inpShape(tensorShape.dim_size());
        for (int j = 0; j < inpShape.size(); ++j)
        {
            inpShape[j] = tensorShape.dim(j).dim_value();
        }
        outShapes[valueInfoProto.name()] = inpShape;
    }
340 341 342 343 344 345 346 347 348

    std::string framework_name;
    if (model_proto.has_producer_name()) {
        framework_name = model_proto.producer_name();
    }

    // create map with network inputs (without const blobs)
    std::map<std::string, LayerInfo> layer_id;
    std::map<std::string, LayerInfo>::iterator layerId;
349
    std::map<std::string, MatShape>::iterator shapeIt;
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
    // fill map: push layer name, layer id and output id
    std::vector<String> netInputs;
    for (int j = 0; j < graph_proto.input_size(); j++)
    {
        const std::string& name = graph_proto.input(j).name();
        if (constBlobs.find(name) == constBlobs.end()) {
            netInputs.push_back(name);
            layer_id.insert(std::make_pair(name, LayerInfo(0, netInputs.size() - 1)));
        }
    }
    dstNet.setInputsNames(netInputs);

    int layersSize = graph_proto.node_size();
    LayerParams layerParams;
    opencv_onnx::NodeProto node_proto;

366
    for(int li = 0; li < layersSize; li++)
367
    {
368
        node_proto = graph_proto.node(li);
369 370 371 372 373 374
        layerParams = getLayerParams(node_proto);
        CV_Assert(node_proto.output_size() >= 1);
        layerParams.name = node_proto.output(0);

        std::string layer_type = node_proto.op_type();
        layerParams.type = layer_type;
D
Dmitry Kurtaev 已提交
375

376

377 378 379 380
        if (layer_type == "MaxPool")
        {
            layerParams.type = "Pooling";
            layerParams.set("pool", "MAX");
381
            layerParams.set("ceil_mode", layerParams.has("pad_mode"));
382 383 384 385 386
        }
        else if (layer_type == "AveragePool")
        {
            layerParams.type = "Pooling";
            layerParams.set("pool", "AVE");
387
            layerParams.set("ceil_mode", layerParams.has("pad_mode"));
388 389
            layerParams.set("ave_pool_padded_area", framework_name == "pytorch");
        }
390
        else if (layer_type == "GlobalAveragePool" || layer_type == "GlobalMaxPool" || layer_type == "ReduceMean")
391
        {
392
            CV_Assert(node_proto.input_size() == 1);
393
            layerParams.type = "Pooling";
394 395 396 397 398 399 400 401 402 403
            layerParams.set("pool", layer_type == "GlobalMaxPool"? "MAX" : "AVE");
            layerParams.set("global_pooling", layer_type == "GlobalAveragePool" || layer_type == "GlobalMaxPool");

            if (layer_type == "ReduceMean")
            {
                if (layerParams.get<int>("keepdims") == 0 || !layerParams.has("axes"))
                    CV_Error(Error::StsNotImplemented, "Unsupported mode of ReduceMean operation.");

                MatShape inpShape = outShapes[node_proto.input(0)];
                DictValue axes = layerParams.get("axes");
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
                if (inpShape.size() == 3 && axes.size() <= 2)
                {
                    int axis = axes.get<int>(0);
                    CV_CheckNE(axis, 0, "");
                    outShapes[layerParams.name] = inpShape;
                    outShapes[layerParams.name][axis] = 1;

                    LayerParams reshapeLp;
                    reshapeLp.name = layerParams.name + "/reshape";
                    reshapeLp.type = "Reshape";
                    CV_Assert(layer_id.find(reshapeLp.name) == layer_id.end());
                    reshapeLp.set("axis", 0);
                    reshapeLp.set("num_axes", 1);
                    int newShape[] = {1, -1};
                    reshapeLp.set("dim", DictValue::arrayInt(&newShape[0], 2));

                    opencv_onnx::NodeProto proto;
                    proto.add_input(node_proto.input(0));
                    proto.add_output(reshapeLp.name);
                    addLayer(dstNet, reshapeLp, proto, layer_id, outShapes);

                    LayerParams avgLp;
                    avgLp.name = layerParams.name + "/avg";
                    avgLp.type = "Pooling";
                    CV_Assert(layer_id.find(avgLp.name) == layer_id.end());
                    avgLp.set("pool", "ave");
                    if (axes.size() == 2)
                    {
                        CV_CheckEQ(axes.get<int>(0), 1, "Unsupported ReduceMean mode");
                        CV_CheckEQ(axes.get<int>(1), 2, "Unsupported ReduceMean mode");
                        avgLp.set("global_pooling", true);
                        outShapes[layerParams.name][axes.get<int>(1)] = 1;
                    }
                    else
                    {
                        avgLp.set(axis == 2 ? "global_pooling_w" : "global_pooling_h", true);
                        avgLp.set(axis == 2 ? "kernel_h" : "kernel_w", 1);
                    }

                    node_proto.set_input(0, reshapeLp.name);
                    node_proto.set_output(0, avgLp.name);
                    addLayer(dstNet, avgLp, node_proto, layer_id, outShapes);

                    layerParams.type = "Flatten";
                    layerParams.set("axis", 0);
                    layerParams.set("end_axis", 1);

                    node_proto.set_input(0, avgLp.name);
                    node_proto.set_output(0, layerParams.name);
453
                }
454 455 456 457
                else
                {
                    if (inpShape.size() != 4 && inpShape.size() != 5)
                    CV_Error(Error::StsNotImplemented, "Unsupported input shape of reduce_mean operation.");
458

459 460 461 462 463 464 465 466 467
                    CV_Assert(axes.size() <= inpShape.size() - 2);
                    std::vector<int> kernel_size(inpShape.size() - 2, 1);
                    for (int i = 0; i < axes.size(); i++) {
                        int axis = axes.get<int>(i);
                        CV_Assert_N(axis >= 2 + i, axis < inpShape.size());
                        kernel_size[axis - 2] = inpShape[axis];
                    }
                    layerParams.set("kernel_size", DictValue::arrayInt(&kernel_size[0], kernel_size.size()));
                }
468
            }
469
        }
470 471
        else if (layer_type == "Slice")
        {
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
            int axis = 0;
            std::vector<int> begin;
            std::vector<int> end;
            int inp_size = node_proto.input_size();

            if (inp_size == 1)
            {
                if (layerParams.has("steps"))
                {
                    DictValue steps = layerParams.get("steps");
                    for (int i = 0; i < steps.size(); ++i)
                    {
                        if (steps.get<int>(i) != 1)
                            CV_Error(Error::StsNotImplemented,
                                "Slice layer only supports steps = 1");
                    }
                }
                if (layerParams.has("axes")) {
                    DictValue axes = layerParams.get("axes");
                    for (int i = 1; i < axes.size(); ++i) {
                        CV_Assert(axes.get<int>(i - 1) == axes.get<int>(i) - 1);
                    }
                    axis = axes.get<int>(0);
495 496
                }

497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
                DictValue starts = layerParams.get("starts");
                DictValue ends = layerParams.get("ends");
                CV_Assert(starts.size() == ends.size());

                if (axis > 0) {
                    begin.resize(axis, 0);
                    end.resize(axis, -1);
                }
                for (int i = 0; i < starts.size(); ++i)
                {
                    begin.push_back(starts.get<int>(i));
                    int finish = ends.get<int>(i);
                    end.push_back((finish < 0) ? --finish : finish); // numpy doesn't include last dim
                }
            } else {
                CV_Assert(inp_size >= 3);
                for (int i = 1; i < inp_size; i++) {
                    CV_Assert(constBlobs.find(node_proto.input(i)) != constBlobs.end());
                }
                Mat start_blob = getBlob(node_proto, constBlobs, 1);
                Mat end_blob   = getBlob(node_proto, constBlobs, 2);
                CV_Assert(start_blob.total() == end_blob.total());

                if (inp_size > 3) {
                    Mat axes_blob = getBlob(node_proto, constBlobs, 3);
                    const int* axes = (int*)axes_blob.data;
                    for (int i = 1; i < axes_blob.total(); ++i) {
                        CV_Assert(axes[i - 1] == axes[i] - 1);
                    }
                    axis = axes[0];
527 528
                }

529 530 531 532 533 534 535 536 537 538 539 540
                const int* starts = start_blob.ptr<int>();
                const int* ends   = end_blob.ptr<int>();
                if (axis > 0) {
                    begin.resize(axis, 0);
                    end.resize(axis, -1);
                }
                std::copy(starts, starts + start_blob.total(), std::back_inserter(begin));
                for (int i = 0; i < end_blob.total(); ++i)
                {
                    int finish = ends[i];
                    end.push_back((finish < 0) ? --finish : finish); // numpy doesn't include last dim
                }
541

542 543 544
                if (inp_size == 5) {
                    CV_Assert(constBlobs.find(node_proto.input(4)) != constBlobs.end());
                    Mat step_blob = getBlob(node_proto, constBlobs, 4);
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561

                    // Very strange application for Slice op with tensor reversing.
                    // We just workaround it for 2d constants.
                    if (constBlobs.find(node_proto.input(0)) != constBlobs.end() &&
                        axis == 0 &&
                        start_blob.at<int>(0) == -1 && step_blob.at<int>(0) == -1 &&
                        end_blob.at<int>(0) == std::numeric_limits<int32_t>::min())
                    {
                        Mat inp = getBlob(node_proto, constBlobs, 0);
                        if (inp.dims == 2)
                        {
                            Mat flipped;
                            flip(inp, flipped, 0);
                            addConstant(layerParams.name, flipped, constBlobs, outShapes);
                            continue;
                        }
                    }
562 563
                    CV_CheckEQ(countNonZero(step_blob != 1), 0, "Slice layer only supports steps = 1");
                }
564
            }
565 566 567
            layerParams.set("begin", DictValue::arrayInt(&begin[0], begin.size()));
            layerParams.set("end", DictValue::arrayInt(&end[0], end.size()));
            layerParams.set("axis", axis);
568

569
            if (constBlobs.find(node_proto.input(0)) != constBlobs.end())
570
            {
571 572 573 574 575
                Mat inp = getBlob(node_proto, constBlobs, 0);
                std::vector<Mat> inputs, sliced;
                inputs.push_back(inp);
                runLayer(layerParams, inputs, sliced);
                CV_Assert(sliced.size() == 1);
576
                addConstant(layerParams.name, sliced[0], constBlobs, outShapes);
577
                continue;
578
            }
579
        }
580 581
        else if (layer_type == "Split")
        {
582 583 584 585 586
            if (layerParams.has("split"))
            {
                DictValue splits = layerParams.get("split");
                const int numSplits = splits.size();
                CV_Assert(numSplits > 1);
587

588 589 590 591 592 593 594 595
                std::vector<int> slicePoints(numSplits - 1, splits.get<int>(0));
                for (int i = 1; i < splits.size() - 1; ++i)
                {
                    slicePoints[i] = slicePoints[i - 1] + splits.get<int>(i - 1);
                }
                layerParams.set("slice_point", DictValue::arrayInt(&slicePoints[0], slicePoints.size()));
            }
            else
596
            {
597
                layerParams.set("num_split", node_proto.output_size());
598 599
            }
            layerParams.type = "Slice";
600
        }
D
Dmitry Kurtaev 已提交
601
        else if (layer_type == "Add" || layer_type == "Sum" || layer_type == "Sub")
602
        {
D
Dmitry Kurtaev 已提交
603 604
            bool isSub = layer_type == "Sub";
            CV_CheckEQ(node_proto.input_size(), 2, "");
605 606 607
            bool is_const_0 = layer_id.find(node_proto.input(0)) == layer_id.end();
            bool is_const_1 = layer_id.find(node_proto.input(1)) == layer_id.end();
            if (is_const_0 && is_const_1)
608
            {
609 610 611 612
                Mat blob_0 = getBlob(node_proto, constBlobs, 0);
                Mat blob_1 = getBlob(node_proto, constBlobs, 1);
                CV_Assert(blob_0.size == blob_1.size);
                Mat output = isSub ? (blob_0 - blob_1) : (blob_0 + blob_1);
613
                addConstant(layerParams.name, output, constBlobs, outShapes);
614 615 616 617
                continue;
            }
            else if (is_const_0 || is_const_1)
            {
618 619 620 621
                int const_blob_id = is_const_0 ? 0 : 1;
                Mat blob = getBlob(node_proto, constBlobs, const_blob_id);
                int blob_total = blob.total();
                if (blob_total == 1) {
622
                    layerParams.type = "Power";
D
Dmitry Kurtaev 已提交
623
                    layerParams.set("shift", (isSub ? -1 : 1) * blob.at<float>(0));
624 625
                }
                else {
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
                    MatShape inpShape = outShapes[node_proto.input(1 - const_blob_id)];
                    if (shape(blob) == inpShape)
                    {
                        LayerParams constParams;
                        constParams.name = layerParams.name + "/const";
                        constParams.type = "Const";
                        constParams.blobs.push_back(blob);
                        int id = dstNet.addLayer(constParams.name, constParams.type, constParams);
                        layer_id.insert(std::make_pair(constParams.name, LayerInfo(id, 0)));
                        outShapes[constParams.name] = shape(blob);

                        layerParams.type = "Eltwise";
                        node_proto.set_input(const_blob_id, constParams.name);
                    }
                    else
                    {
                        layerParams.type = "Scale";
                        layerParams.set("bias_term", true);
                        blob = blob.reshape(1, 1);
                        layerParams.blobs.push_back((isSub ? -1 : 1) * blob);
                    }
647 648
                }
            }
D
Dmitry Kurtaev 已提交
649 650
            else if (outShapes[node_proto.input(0)] == outShapes[node_proto.input(1)])
            {
651
                layerParams.type = "Eltwise";
D
Dmitry Kurtaev 已提交
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
                if (isSub)
                {
                    static float subCoeffs[] = {1.f, -1.f};
                    layerParams.set("coeff", DictValue::arrayReal<float*>(subCoeffs, 2));
                }
            }
            else
            {
                if (isSub)
                {
                    LayerParams powerParams;
                    powerParams.name = layerParams.name + "/neg";
                    powerParams.type = "Power";
                    powerParams.set("scale", -1);

                    //Create Power layer
                    int id = dstNet.addLayer(powerParams.name, powerParams.type, powerParams);
                    //Connect to input
                    layerId = layer_id.find(node_proto.input(1));
                    CV_Assert(layerId != layer_id.end());
                    dstNet.connect(layerId->second.layerId, layerId->second.outputId, id, 0);
                    //Add shape
                    layer_id.insert(std::make_pair(powerParams.name, LayerInfo(id, 0)));
                    outShapes[powerParams.name] = outShapes[node_proto.input(1)];

                    //Replace input to Power
                    node_proto.set_input(1, powerParams.name);
                }
                layerParams.type = "Scale";
                layerParams.set("bias_term", true);
682 683
            }
        }
684 685 686 687 688
        else if (layer_type == "Max")
        {
            layerParams.type = "Eltwise";
            layerParams.set("operation", "max");
        }
689 690 691 692 693
        else if (layer_type == "Neg")
        {
            layerParams.type = "Power";
            layerParams.set("scale", -1);
        }
694 695 696 697
        else if (layer_type == "Constant")
        {
            CV_Assert(node_proto.input_size() == 0);
            CV_Assert(layerParams.blobs.size() == 1);
698
            addConstant(layerParams.name, layerParams.blobs[0], constBlobs, outShapes);
699 700
            continue;
        }
D
Dmitry Kurtaev 已提交
701 702
        else if (layer_type == "LSTM")
        {
703 704 705
            LayerParams lstmParams = layerParams;
            lstmParams.name += "/lstm";

D
Dmitry Kurtaev 已提交
706
            // https://pytorch.org/docs/stable/nn.html#lstm
D
Dmitry Kurtaev 已提交
707 708 709 710
            CV_Assert(node_proto.input_size() == 7);
            Mat Wx = getBlob(node_proto, constBlobs, 1);
            Mat Wh = getBlob(node_proto, constBlobs, 2);
            Mat b = getBlob(node_proto, constBlobs, 3);
711 712
            CV_CheckEQ(countNonZero(getBlob(node_proto, constBlobs, 5)), 0, "Unsupported non zero initial_h");
            CV_CheckEQ(countNonZero(getBlob(node_proto, constBlobs, 6)), 0, "Unsupported non zero initial_c");
D
Dmitry Kurtaev 已提交
713
            b = b.reshape(1, b.size[0]);
D
Dmitry Kurtaev 已提交
714

715
            const int numHidden = lstmParams.get<int>("hidden_size");
D
Dmitry Kurtaev 已提交
716 717 718 719 720
            const int numDirs = Wx.size[0];  // Is 1 for forward only and 2 for bidirectional LSTM.
            const int numFeatures = Wx.size[2];
            Mat bx = b.colRange(0, b.cols / 2);
            Mat bh = b.colRange(b.cols / 2, b.cols);
            b = bx + bh;
D
Dmitry Kurtaev 已提交
721

D
Dmitry Kurtaev 已提交
722
            // IFGO->IGFO
D
Dmitry Kurtaev 已提交
723
            for (int k = 0; k < numDirs; ++k)
D
Dmitry Kurtaev 已提交
724
            {
D
Dmitry Kurtaev 已提交
725 726 727 728
                float* WxData = Wx.ptr<float>(k);
                float* WhData = Wh.ptr<float>(k);
                float* biasData = b.ptr<float>(k);
                for (int j = 0; j < numHidden; ++j)
D
Dmitry Kurtaev 已提交
729
                {
D
Dmitry Kurtaev 已提交
730 731 732 733 734 735 736 737 738 739 740
                    for (int i = 0; i < numFeatures; ++i)
                    {
                        std::swap(WxData[(numHidden + j) * numFeatures + i],
                                  WxData[(numHidden * 2 + j) * numFeatures + i]);
                    }
                    for (int i = 0; i < numHidden; ++i)
                    {
                        std::swap(WhData[(numHidden + j) * numHidden + i],
                                  WhData[(numHidden * 2 + j) * numHidden + i]);
                    }
                    std::swap(biasData[numHidden + j], biasData[numHidden * 2 + j]);
D
Dmitry Kurtaev 已提交
741 742
                }
            }
D
Dmitry Kurtaev 已提交
743 744
            Wx = Wx.reshape(1, Wx.size[0] * Wx.size[1]);
            Wh = Wh.reshape(1, Wh.size[0] * Wh.size[1]);
745 746 747 748 749

            lstmParams.blobs.resize(3);
            lstmParams.blobs[0] = Wh;
            lstmParams.blobs[1] = Wx;
            lstmParams.blobs[2] = b;
D
Dmitry Kurtaev 已提交
750
            lstmParams.set("bidirectional", lstmParams.get<String>("direction", "") == "bidirectional");
751 752 753 754 755 756 757 758 759 760 761 762 763

            node_proto.set_output(0, lstmParams.name);  // set different name so output shapes will be registered on that name
            addLayer(dstNet, lstmParams, node_proto, layer_id, outShapes);

            MatShape lstmShape = outShapes[node_proto.output(0)];

            // Add fake 1 as it is done in ONNX
            lstmShape.insert(lstmShape.begin() + 1, 1);

            layerParams.type = "Reshape";
            layerParams.set("dim", DictValue::arrayInt(&lstmShape[0], lstmShape.size()));
            node_proto.set_input(0, lstmParams.name);  // redirect input to LSTM
            node_proto.set_output(0, layerParams.name);  // keep origin LSTM's name
D
Dmitry Kurtaev 已提交
764
        }
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
        else if (layer_type == "ImageScaler")
        {
            const float scale = layerParams.has("scale") ? layerParams.get<float>("scale") : 1.0f;
            layerParams.erase("scale");

            if (layerParams.has("bias"))
            {
                layerParams.type = "Scale";
                layerParams.blobs.push_back(
                    Mat(Size(1,  layerParams.get("bias").size()), CV_32FC1, scale));

                layerParams.set("bias_term", true);
                Mat bias(1, layerParams.get("bias").size(), CV_32FC1);
                for (int j = 0; j < bias.total(); j++) {
                    bias.at<float>(0, j) = layerParams.get("bias").getRealValue(j);
                }
                layerParams.blobs.push_back(bias);
                layerParams.erase("bias");
            }
            else {
                layerParams.set("scale", scale);
                layerParams.type = "Power";
            }
        }
789 790 791 792 793 794 795
        else if (layer_type == "Clip")
        {
            layerParams.type = "ReLU6";
            replaceLayerParam(layerParams, "min", "min_value");
            replaceLayerParam(layerParams, "max", "max_value");

        }
796 797 798 799 800
        else if (layer_type == "LeakyRelu")
        {
            layerParams.type = "ReLU";
            replaceLayerParam(layerParams, "alpha", "negative_slope");
        }
D
Dmitry Kurtaev 已提交
801 802 803 804
        else if (layer_type == "Relu")
        {
            layerParams.type = "ReLU";
        }
D
Dmitry Kurtaev 已提交
805 806 807 808
        else if (layer_type == "Elu")
        {
            layerParams.type = "ELU";
        }
D
Dmitry Kurtaev 已提交
809 810 811 812 813
        else if (layer_type == "PRelu")
        {
            layerParams.type = "PReLU";
            layerParams.blobs.push_back(getBlob(node_proto, constBlobs, 1));
        }
814 815 816 817
        else if (layer_type == "LRN")
        {
            replaceLayerParam(layerParams, "size", "local_size");
        }
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
        else if (layer_type == "InstanceNormalization")
        {
            if (node_proto.input_size() != 3)
                CV_Error(Error::StsNotImplemented,
                         "Expected input, scale, bias");

            layerParams.blobs.resize(4);
            layerParams.blobs[2] = getBlob(node_proto, constBlobs, 1);  // weightData
            layerParams.blobs[3] = getBlob(node_proto, constBlobs, 2);  // biasData
            layerParams.set("has_bias", true);
            layerParams.set("has_weight", true);

            // Get number of channels in input
            int size = layerParams.blobs[2].total();
            layerParams.blobs[0] = Mat::zeros(size, 1, CV_32F); // mean
            layerParams.blobs[1] = Mat::ones(size, 1, CV_32F); // std

            LayerParams mvnParams;
            mvnParams.name = layerParams.name + "/MVN";
            mvnParams.type = "MVN";
            mvnParams.set("eps", layerParams.get<float>("epsilon"));
            layerParams.erase("epsilon");

            //Create MVN layer
            int id = dstNet.addLayer(mvnParams.name, mvnParams.type, mvnParams);
            //Connect to input
            layerId = layer_id.find(node_proto.input(0));
            CV_Assert(layerId != layer_id.end());
            dstNet.connect(layerId->second.layerId, layerId->second.outputId, id, 0);
            //Add shape
            layer_id.insert(std::make_pair(mvnParams.name, LayerInfo(id, 0)));
            outShapes[mvnParams.name] = outShapes[node_proto.input(0)];

            //Replace Batch Norm's input to MVN
            node_proto.set_input(0, mvnParams.name);
            layerParams.type = "BatchNorm";
        }
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
        else if (layer_type == "BatchNormalization")
        {
            if (node_proto.input_size() != 5)
                CV_Error(Error::StsNotImplemented,
                         "Expected input, scale, bias, mean and var");

            layerParams.type = "BatchNorm";
            replaceLayerParam(layerParams, "epsilon", "eps");
            replaceLayerParam(layerParams, "spatial", "use_global_stats");

            Mat meanData = getBlob(node_proto, constBlobs, 3);
            Mat stdData =  getBlob(node_proto, constBlobs, 4);

            layerParams.blobs.push_back(meanData);
            layerParams.blobs.push_back(stdData);

            if (!node_proto.input(1).empty()) {
                layerParams.set("has_weight", true);
                layerParams.blobs.push_back(getBlob(node_proto, constBlobs, 1));  // weightData
            } else {
                layerParams.set("has_weight", false);
            }

            if (!node_proto.input(2).empty()) {
                layerParams.set("has_bias", true);
                layerParams.blobs.push_back(getBlob(node_proto, constBlobs, 2)); // biasData
            } else {
                layerParams.set("has_bias", false);
            }
        }
        else if (layer_type == "Gemm")
        {
            CV_Assert(node_proto.input_size() >= 2);
            layerParams.type = "InnerProduct";
            Mat weights = getBlob(node_proto, constBlobs, 1);
            int ind_num_out = 0;
            if (layerParams.has("transB") && !layerParams.get<int>("transB")) {
                transpose(weights, weights);
                ind_num_out = 1;
            }
            layerParams.blobs.push_back(weights);

            if (node_proto.input_size() == 3) {
                Mat bias = getBlob(node_proto, constBlobs, 2);
                layerParams.blobs.push_back(bias);
            }

            layerParams.set("num_output", layerParams.blobs[0].size[ind_num_out]);
            layerParams.set("bias_term", node_proto.input_size() == 3);
        }
        else if (layer_type == "MatMul")
        {
            CV_Assert(node_proto.input_size() == 2);
            layerParams.type = "InnerProduct";
            layerParams.set("bias_term", false);
910 911 912 913 914 915 916

            if (constBlobs.find(node_proto.input(1)) != constBlobs.end())
            {
                Mat blob = getBlob(node_proto, constBlobs, 1);
                layerParams.blobs.push_back(blob.t());
                layerParams.set("num_output", layerParams.blobs[0].size[0]);
            }
917
        }
918
        else if (layer_type == "Mul" || layer_type == "Div")
919 920
        {
            CV_Assert(node_proto.input_size() == 2);
921 922 923 924 925 926 927 928 929 930 931 932 933 934

            bool isDiv = layer_type == "Div";
            int constId = -1;
            bool haveVariables = false;
            for (int i = 0; i < 2; ++i)
            {
                if (constBlobs.find(node_proto.input(i)) != constBlobs.end())
                    constId = i;
                else
                    haveVariables = true;
            }
            if (constId != -1 && haveVariables)
            {
                Mat blob = getBlob(node_proto, constBlobs, constId);
935 936
                blob = blob.reshape(1, 1);
                if (blob.total() == 1) {
937 938
                    float coeff = isDiv ? 1.0 / blob.at<float>(0) : blob.at<float>(0);
                    layerParams.set("scale", coeff);
939 940 941
                    layerParams.type = "Power";
                }
                else {
942 943
                    if (isDiv)
                        divide(1.0, blob, blob);
944 945 946 947
                    layerParams.blobs.push_back(blob);
                    layerParams.type = "Scale";
                }
            }
D
Dmitry Kurtaev 已提交
948 949
            else if (outShapes[node_proto.input(0)] == outShapes[node_proto.input(1)])
            {
950
                layerParams.type = "Eltwise";
951 952
                layerParams.set("operation", isDiv ? "div" : "prod");
            }
D
Dmitry Kurtaev 已提交
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
            else
            {
                if (isDiv)
                {
                    LayerParams powerParams;
                    powerParams.name = layerParams.name + "/inv";
                    powerParams.type = "Power";
                    powerParams.set("power", -1);

                    //Create Power layer
                    int id = dstNet.addLayer(powerParams.name, powerParams.type, powerParams);
                    //Connect to input
                    layerId = layer_id.find(node_proto.input(1));
                    CV_Assert(layerId != layer_id.end());
                    dstNet.connect(layerId->second.layerId, layerId->second.outputId, id, 0);
                    //Add shape
                    layer_id.insert(std::make_pair(powerParams.name, LayerInfo(id, 0)));
                    outShapes[powerParams.name] = outShapes[node_proto.input(1)];

                    //Replace input to Power
                    node_proto.set_input(1, powerParams.name);
                }
                layerParams.type = "Scale";
            }
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992

            if (!haveVariables)
            {
                Mat inp0 = getBlob(node_proto, constBlobs, 0);
                Mat inp1 = getBlob(node_proto, constBlobs, 1);
                if (inp0.size != inp1.size)
                    CV_Error(Error::StsNotImplemented, "Constant multiply with different shapes");

                Mat out;
                if (isDiv)
                    divide(inp0, inp1, out);
                else
                    multiply(inp0, inp1, out);

                out = out.reshape(1, inp0.dims, inp0.size);
                out.dims = inp0.dims;  // to workaround dims == 1
993
                addConstant(layerParams.name, out, constBlobs, outShapes);
994
                continue;
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
            }
        }
        else if (layer_type == "Conv")
        {
            CV_Assert(node_proto.input_size() >= 2);
            layerParams.type = "Convolution";
            for (int j = 1; j < node_proto.input_size(); j++) {
                layerParams.blobs.push_back(getBlob(node_proto, constBlobs, j));
            }
            layerParams.set("num_output", layerParams.blobs[0].size[0]);
            layerParams.set("bias_term", node_proto.input_size() == 3);
        }
1007 1008 1009 1010 1011 1012 1013
        else if (layer_type == "ConvTranspose")
        {
            CV_Assert(node_proto.input_size() >= 2);
            layerParams.type = "Deconvolution";
            for (int j = 1; j < node_proto.input_size(); j++) {
                layerParams.blobs.push_back(getBlob(node_proto, constBlobs, j));
            }
A
Ayush Pandey 已提交
1014
            layerParams.set("num_output", layerParams.blobs[0].size[1] * layerParams.get<int>("group", 1));
1015
            layerParams.set("bias_term", node_proto.input_size() == 3);
1016

1017 1018 1019 1020
            if (!layerParams.has("kernel_size"))
                CV_Error(Error::StsNotImplemented,
                         "Required attribute 'kernel_size' is not present.");

1021 1022 1023
            if (layerParams.has("output_shape"))
            {
                const DictValue& outShape = layerParams.get("output_shape");
1024 1025
                DictValue strides = layerParams.get("stride");
                DictValue kernel = layerParams.get("kernel_size");
1026

1027 1028 1029
                String padMode;
                std::vector<int> adjust_pads;
                if (layerParams.has("pad_mode"))
1030
                {
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
                    padMode = toUpperCase(layerParams.get<String>("pad_mode"));
                    if (padMode != "SAME" && padMode != "VALID")
                        CV_Error(Error::StsError, "Unsupported padding mode " + padMode);

                    for (int i = 0; i < strides.size(); i++)
                    {
                        int sz = outShape.get<int>(2 + i);
                        int stride = strides.get<int>(i);
                        adjust_pads.push_back(padMode == "SAME"? (sz - 1) % stride :
                                                                 (sz - kernel.get<int>(i)) % stride);
                    }
                    layerParams.set("adj", DictValue::arrayInt(&adjust_pads[0], adjust_pads.size()));
1043 1044
                }
            }
L
Liubov Batanina 已提交
1045 1046
            else if (layerParams.has("output_padding"))
            {
1047
                replaceLayerParam(layerParams, "output_padding", "adj");
L
Liubov Batanina 已提交
1048
            }
1049
        }
1050 1051 1052 1053
        else if (layer_type == "Transpose")
        {
            layerParams.type = "Permute";
            replaceLayerParam(layerParams, "perm", "order");
1054 1055 1056 1057 1058 1059 1060

            CV_Assert(node_proto.input_size() == 1);
            if (constBlobs.find(node_proto.input(0)) != constBlobs.end())
            {
                std::vector<Mat> inputs(1, getBlob(node_proto, constBlobs, 0)), transposed;
                runLayer(layerParams, inputs, transposed);
                CV_Assert(transposed.size() == 1);
1061
                addConstant(layerParams.name, transposed[0], constBlobs, outShapes);
1062 1063
                continue;
            }
1064
        }
1065 1066 1067
        else if (layer_type == "Squeeze")
        {
            CV_Assert_N(node_proto.input_size() == 1, layerParams.has("axes"));
D
Dmitry Kurtaev 已提交
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
            DictValue axes_dict = layerParams.get("axes");
            MatShape inpShape = outShapes[node_proto.input(0)];

            std::vector<bool> maskedAxes(inpShape.size(), false);
            for (int i = 0; i < axes_dict.size(); ++i)
            {
                int axis = axes_dict.getIntValue(i);
                CV_CheckLE(axis, static_cast<int>(inpShape.size()), "Squeeze axis");
                maskedAxes[axis] = inpShape[axis] == 1;
            }
            MatShape outShape;
            for (int i = 0; i < inpShape.size(); ++i)
            {
                if (!maskedAxes[i])
                    outShape.push_back(inpShape[i]);
            }
            if (outShape.size() != inpShape.size())
            {
                layerParams.type = "Reshape";
                layerParams.set("dim", DictValue::arrayInt(&outShape[0], outShape.size()));
            }
            else
                layerParams.type = "Identity";
1091 1092 1093 1094 1095 1096

            if (constBlobs.find(node_proto.input(0)) != constBlobs.end())
            {
                Mat inp = getBlob(node_proto, constBlobs, 0);
                Mat out = inp.reshape(1, outShape);
                out.dims = outShape.size();  // to workaround dims == 1
1097
                addConstant(layerParams.name, out, constBlobs, outShapes);
1098 1099
                continue;
            }
1100
        }
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
        else if (layer_type == "Flatten")
        {
            CV_CheckEQ(node_proto.input_size(), 1, "");
            if (constBlobs.find(node_proto.input(0)) != constBlobs.end())
            {
                Mat input = getBlob(node_proto, constBlobs, 0);
                int axis = clamp(layerParams.get<int>("axis", 1), input.dims);

                std::vector<int> out_size(&input.size[0], &input.size[0] + axis);
                out_size.push_back(input.total(axis));
                Mat output = input.reshape(1, out_size);
1112
                addConstant(layerParams.name, output, constBlobs, outShapes);
1113 1114 1115
                continue;
            }
        }
1116 1117 1118 1119
        else if (layer_type == "Unsqueeze")
        {
            CV_Assert(node_proto.input_size() == 1);
            DictValue axes = layerParams.get("axes");
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
            if (constBlobs.find(node_proto.input(0)) != constBlobs.end())
            {
                // Constant input.
                Mat input = getBlob(node_proto, constBlobs, 0);

                std::vector<int> dims;
                for (int j = 0; j < input.dims; j++) {
                    dims.push_back(input.size[j]);
                }
                CV_Assert(axes.getIntValue(axes.size()-1) <= dims.size());
                for (int j = 0; j < axes.size(); j++) {
                    dims.insert(dims.begin() + axes.getIntValue(j), 1);
                }

                Mat out = input.reshape(0, dims);
1135
                addConstant(layerParams.name, out, constBlobs, outShapes);
1136
                continue;
1137 1138
            }

1139 1140 1141 1142
            // Variable input.
            if (axes.size() != 1)
                CV_Error(Error::StsNotImplemented, "Multidimensional unsqueeze");

1143 1144 1145 1146 1147
            MatShape inpShape = outShapes[node_proto.input(0)];
            int axis = axes.getIntValue(0);
            CV_Assert(0 <= axis && axis <= inpShape.size());
            std::vector<int> outShape = inpShape;
            outShape.insert(outShape.begin() + axis, 1);
1148
            layerParams.type = "Reshape";
1149
            layerParams.set("dim", DictValue::arrayInt(&outShape[0], outShape.size()));
1150
        }
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
        else if (layer_type == "Expand")
        {
            CV_CheckEQ(node_proto.input_size(), 2, "");
            CV_Assert(constBlobs.find(node_proto.input(1)) != constBlobs.end());
            Mat newShapeMat = getBlob(node_proto, constBlobs, 1);
            MatShape targetShape(newShapeMat.ptr<int>(), newShapeMat.ptr<int>() + newShapeMat.total());

            shapeIt = outShapes.find(node_proto.input(0));
            CV_Assert(shapeIt != outShapes.end());
            MatShape inpShape = shapeIt->second;
            CV_CheckEQ(inpShape.size(), targetShape.size(), "Unsupported Expand op with different dims");

            std::vector<int> broadcast_axes;
            for (int i = 0; i < targetShape.size(); i++)
            {
                if (targetShape[i] != inpShape[i])
                {
                    if (inpShape[i] == 1)
                        broadcast_axes.push_back(i);
                    else
                        CV_Error(Error::StsError, format("Could not be broadcast by axis: %d", i));
                }
            }

            if (broadcast_axes.size() == 2 &&
                broadcast_axes[0] == broadcast_axes[1] - 1 && broadcast_axes[1] == inpShape.size() - 1)
            {
                LayerParams constParams;
                constParams.name = layerParams.name + "/const";
                CV_Assert(layer_id.find(constParams.name) == layer_id.end());
                constParams.type = "Const";

                Mat inp = Mat::ones(newShapeMat.total(), newShapeMat.ptr<int>(), CV_32F);
                constParams.blobs.push_back(inp);

                opencv_onnx::NodeProto proto;
                proto.add_output(constParams.name);
                addLayer(dstNet, constParams, proto, layer_id, outShapes);

                layerParams.type = "Scale";
                layerParams.set("bias_term", false);
                node_proto.set_input(0, constParams.name);
                node_proto.set_input(1, shapeIt->first);
            }
            else if (broadcast_axes.size() == 1 && broadcast_axes[0] <= 1)
            {
                String base_name = layerParams.name + "/copy_";
                std::vector<std::string> input_names;
                for (int j = 0; j < targetShape[broadcast_axes[0]]; j++)
                {
                    std::ostringstream ss;
                    ss << j;
                    LayerParams copyLP;
                    copyLP.name = base_name + ss.str();
                    copyLP.type = "Identity";
                    CV_Assert(layer_id.find(copyLP.name) == layer_id.end());
                    input_names.push_back(copyLP.name);

                    node_proto.set_output(0, copyLP.name);
                    addLayer(dstNet, copyLP, node_proto, layer_id, outShapes);
                }
                node_proto.clear_input();
                for (int i = 0; i < input_names.size(); i++)
                {
                    node_proto.add_input(input_names[i]);
                }
                layerParams.set("axis", broadcast_axes[0]);
                layerParams.type = "Concat";
            }
            else
                CV_Error(Error::StsNotImplemented, "Unsupported Expand op");
        }
1223 1224 1225 1226 1227 1228 1229 1230
        else if (layer_type == "Reshape")
        {
            CV_Assert(node_proto.input_size() == 2 || layerParams.has("shape"));

            if (node_proto.input_size() == 2) {
                Mat blob = getBlob(node_proto, constBlobs, 1);
                CV_Assert(blob.type() == CV_32SC1);

1231 1232 1233
                layerParams.set("dim", DictValue::arrayInt<int*>(
                            blob.ptr<int>(), blob.total() ));

1234
                if (layer_id.find(node_proto.input(0)) == layer_id.end()) {
1235 1236
                    std::vector<Mat> inputs(1, getBlob(node_proto, constBlobs, 0)), outputs;
                    runLayer(layerParams, inputs, outputs);
1237
                    addConstant(layerParams.name, outputs[0], constBlobs, outShapes);
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
                    continue;
                }
            }
            else {
                DictValue shape = layerParams.get("shape");
                std::vector<int> dim;
                for (int j = 0; j < shape.size(); j++) {
                    dim.push_back(shape.getIntValue(j));
                }

                if (layer_id.find(node_proto.input(0)) == layer_id.end()) {
                    Mat input = getBlob(node_proto, constBlobs, 0);
                    Mat out = input.reshape(0, dim);
1251
                    addConstant(layerParams.name, out, constBlobs, outShapes);
1252 1253 1254 1255 1256
                    continue;
                }
                replaceLayerParam(layerParams, "shape", "dim");
            }
        }
D
Dmitry Kurtaev 已提交
1257 1258 1259
        else if (layer_type == "Pad")
        {
            layerParams.type = "Padding";
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
            replaceLayerParam(layerParams, "mode", "type");
            if (node_proto.input_size() == 3 || node_proto.input_size() == 2)
            {
                // Paddings are in order begin0, begin1, .. beginN, end0, end1, ..., endN.
                // We need to shuffle it to begin0, end0, begin1, end1, ...
                Mat paddings = getBlob(node_proto, constBlobs, 1).reshape(1, 2);
                paddings = paddings.t();
                layerParams.set("paddings", DictValue::arrayInt(paddings.ptr<int>(), paddings.total()));

                if (node_proto.input_size() == 3)
                {
                    Mat value = getBlob(node_proto, constBlobs, 2);
                    layerParams.set("value", value.at<float>(0));
                }
            }
D
Dmitry Kurtaev 已提交
1275
        }
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
        else if (layer_type == "Shape")
        {
            CV_Assert(node_proto.input_size() == 1);
            shapeIt = outShapes.find(node_proto.input(0));
            CV_Assert(shapeIt != outShapes.end());
            MatShape inpShape = shapeIt->second;

            Mat shapeMat(inpShape.size(), 1, CV_32S);
            for (int j = 0; j < inpShape.size(); ++j)
                shapeMat.at<int>(j) = inpShape[j];
            shapeMat.dims = 1;

1288
            addConstant(layerParams.name, shapeMat, constBlobs, outShapes);
1289 1290
            continue;
        }
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
        else if (layer_type == "Cast")
        {
            if (constBlobs.find(node_proto.input(0)) != constBlobs.end())
            {
                Mat blob = getBlob(node_proto, constBlobs, 0);
                int type;
                switch (layerParams.get<int>("to"))
                {
                    case opencv_onnx::TensorProto_DataType_FLOAT:   type = CV_32F; break;
                    case opencv_onnx::TensorProto_DataType_UINT8:   type = CV_8U; break;
                    case opencv_onnx::TensorProto_DataType_UINT16:  type = CV_16U; break;
                    case opencv_onnx::TensorProto_DataType_FLOAT16: type = CV_16S; break;
                    case opencv_onnx::TensorProto_DataType_INT8:
                    case opencv_onnx::TensorProto_DataType_INT16:
                    case opencv_onnx::TensorProto_DataType_INT32:
                    case opencv_onnx::TensorProto_DataType_INT64:   type = CV_32S; break;
                    default: type = blob.type();
                }
                blob.convertTo(blob, type);
1310
                addConstant(layerParams.name, blob, constBlobs, outShapes);
1311 1312 1313 1314 1315
                continue;
            }
            else
                layerParams.type = "Identity";
        }
D
Dmitry Kurtaev 已提交
1316 1317
        else if (layer_type == "ConstantOfShape" || layer_type == "ConstantFill")
        {
1318
            int depth = CV_32F;
D
Dmitry Kurtaev 已提交
1319 1320 1321 1322
            float fill_value;
            if (!layerParams.blobs.empty())
            {
                CV_Assert(!layerParams.has("value"));
1323 1324 1325 1326
                depth = layerParams.blobs[0].depth();
                Mat floats;
                layerParams.blobs[0].convertTo(floats, CV_32F);
                fill_value = floats.at<float>(0, 0);
D
Dmitry Kurtaev 已提交
1327 1328 1329 1330
            }
            else
                fill_value = layerParams.get("value", 0);

1331 1332 1333
            MatShape inpShape = getBlob(node_proto, constBlobs, 0);
            for (int i = 0; i < inpShape.size(); i++)
                CV_CheckGT(inpShape[i], 0, "");
1334 1335
            Mat tensor(inpShape.size(), &inpShape[0], depth, Scalar(fill_value));
            addConstant(layerParams.name, tensor, constBlobs, outShapes);
1336 1337
            continue;
        }
1338 1339 1340 1341 1342 1343 1344 1345
        else if (layer_type == "Gather")
        {
            CV_Assert(node_proto.input_size() == 2);
            Mat input = getBlob(node_proto, constBlobs, 0);
            Mat indexMat = getBlob(node_proto, constBlobs, 1);
            CV_Assert_N(indexMat.type() == CV_32S, indexMat.total() == 1);
            int index = indexMat.at<int>(0);

D
Dmitry Kurtaev 已提交
1346 1347 1348 1349 1350 1351 1352
            Mat out;
            if (layerParams.has("axis"))
            {
                int axis = layerParams.get<int>("axis");

                std::vector<cv::Range> ranges(input.dims, Range::all());
                ranges[axis] = Range(index, index + 1);
1353

D
Dmitry Kurtaev 已提交
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
                out = input(ranges);
            }
            else
            {
                CV_Assert(index < input.total());
                const int dims = input.dims;
                input = input.reshape(1, 1);
                input.dims = 2;
                out = input.reshape(1, 1).colRange(index, index + 1);
                out.dims = dims;
            }
1365
            addConstant(layerParams.name, out, constBlobs, outShapes);
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
            continue;
        }
        else if (layer_type == "Concat")
        {
            bool hasVariableInps = false;
            for (int i = 0; i < node_proto.input_size(); ++i)
            {
                if (layer_id.find(node_proto.input(i)) != layer_id.end())
                {
                    hasVariableInps = true;
                    break;
                }
            }

            if (!hasVariableInps)
            {
                std::vector<Mat> inputs(node_proto.input_size()), concatenated;
                for (size_t i = 0; i < inputs.size(); ++i)
                {
                    inputs[i] = getBlob(node_proto, constBlobs, i);
                }
1387
                runLayer(layerParams, inputs, concatenated);
1388 1389

                CV_Assert(concatenated.size() == 1);
1390
                addConstant(layerParams.name, concatenated[0], constBlobs, outShapes);
1391 1392 1393
                continue;
            }
        }
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
        else if (layer_type == "Resize")
        {
            for (int i = 1; i < node_proto.input_size(); i++)
                CV_Assert(layer_id.find(node_proto.input(i)) == layer_id.end());

            String interp_mode = layerParams.get<String>("coordinate_transformation_mode");
            CV_Assert_N(interp_mode != "tf_crop_and_resize", interp_mode != "asymmetric",
                        interp_mode != "tf_half_pixel_for_nn");

            layerParams.set("align_corners", interp_mode == "align_corners");
            Mat shapes = getBlob(node_proto, constBlobs, node_proto.input_size() - 1);
            CV_CheckEQ(shapes.size[0], 4, "");
            CV_CheckEQ(shapes.size[1], 1, "");
            CV_CheckTypeEQ(shapes.depth(), CV_32S, "");
            int height = shapes.at<int>(2);
            int width  = shapes.at<int>(3);
            if (node_proto.input_size() == 3)
            {
                shapeIt = outShapes.find(node_proto.input(0));
                CV_Assert(shapeIt != outShapes.end());
                MatShape scales = shapeIt->second;
                height *= scales[2];
                width  *= scales[3];
            }
            layerParams.set("width", width);
            layerParams.set("height", height);

            if (layerParams.get<String>("mode") == "linear") {
                layerParams.set("mode", interp_mode == "pytorch_half_pixel" ?
                                        "opencv_linear" : "bilinear");
            }
            replaceLayerParam(layerParams, "mode", "interpolation");
        }
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
        else if (layer_type == "Upsample")
        {
            layerParams.type = "Resize";
            if (layerParams.has("scales"))
            {
                // Pytorch layer
                DictValue scales = layerParams.get("scales");
                CV_Assert(scales.size() == 4);
                layerParams.set("zoom_factor_y", scales.getIntValue(2));
                layerParams.set("zoom_factor_x", scales.getIntValue(3));
            }
            else
            {
                // Caffe2 layer
                replaceLayerParam(layerParams, "height_scale", "zoom_factor_y");
                replaceLayerParam(layerParams, "width_scale", "zoom_factor_x");
            }
            replaceLayerParam(layerParams, "mode", "interpolation");
1445 1446 1447 1448 1449 1450 1451 1452 1453

            if (layerParams.get<String>("interpolation") == "linear" && framework_name == "pytorch") {
                layerParams.type = "Resize";
                Mat scales = getBlob(node_proto, constBlobs, 1);
                CV_Assert(scales.total() == 4);
                layerParams.set("interpolation", "opencv_linear");
                layerParams.set("zoom_factor_y", scales.at<float>(2));
                layerParams.set("zoom_factor_x", scales.at<float>(3));
            }
1454
        }
D
Dmitry Kurtaev 已提交
1455
        else if (layer_type == "SoftMax" || layer_type == "LogSoftmax")
D
dianlujitao 已提交
1456 1457
        {
            layerParams.type = "Softmax";
D
Dmitry Kurtaev 已提交
1458
            layerParams.set("log_softmax", layer_type == "LogSoftmax");
D
dianlujitao 已提交
1459
        }
1460 1461 1462 1463 1464 1465
        else
        {
            for (int j = 0; j < node_proto.input_size(); j++) {
                if (layer_id.find(node_proto.input(j)) == layer_id.end())
                    layerParams.blobs.push_back(getBlob(node_proto, constBlobs, j));
            }
D
dianlujitao 已提交
1466
        }
1467
        addLayer(dstNet, layerParams, node_proto, layer_id, outShapes);
D
dianlujitao 已提交
1468 1469
    }
}
1470 1471 1472 1473 1474 1475 1476 1477 1478

Net readNetFromONNX(const String& onnxFile)
{
    ONNXImporter onnxImporter(onnxFile.c_str());
    Net net;
    onnxImporter.populateNet(net);
    return net;
}

1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
Net readNetFromONNX(const char* buffer, size_t sizeBuffer)
{
    ONNXImporter onnxImporter(buffer, sizeBuffer);
    Net net;
    onnxImporter.populateNet(net);
    return net;
}

Net readNetFromONNX(const std::vector<uchar>& buffer)
{
    return readNetFromONNX(reinterpret_cast<const char*>(buffer.data()), buffer.size());
}

1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
Mat readTensorFromONNX(const String& path)
{
    opencv_onnx::TensorProto tensor_proto = opencv_onnx::TensorProto();
    std::fstream input(path.c_str(), std::ios::in | std::ios::binary);
    if (!tensor_proto.ParseFromIstream(&input)) {
        CV_Error(Error::StsUnsupportedFormat, "Failed to parse data");
    }
    Mat mat = getMatFromTensor(tensor_proto);
    releaseONNXTensor(tensor_proto);
    return mat;
}

CV__DNN_EXPERIMENTAL_NS_END
}} // namespace

#endif