tf_importer.cpp 102.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
// 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) 2016, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.

/*
Implementation of Tensorflow models parser
*/

#include "../precomp.hpp"

14 15 16 17 18
#include <opencv2/core/utils/logger.defines.hpp>
#undef CV_LOG_STRIP_LEVEL
#define CV_LOG_STRIP_LEVEL CV_LOG_LEVEL_DEBUG + 1
#include <opencv2/core/utils/logger.hpp>

A
Alexander Alekhin 已提交
19
#ifdef HAVE_PROTOBUF
20
#include "tf_io.hpp"
21 22 23 24 25

#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
26
#include <queue>
D
Dmitry Kurtaev 已提交
27
#include "tf_graph_simplifier.hpp"
28 29 30 31 32 33 34
#endif

namespace cv {
namespace dnn {
CV__DNN_EXPERIMENTAL_NS_BEGIN

#if HAVE_PROTOBUF
35 36 37 38 39 40 41 42 43 44 45

using ::google::protobuf::RepeatedField;
using ::google::protobuf::RepeatedPtrField;
using ::google::protobuf::Message;
using ::google::protobuf::Descriptor;
using ::google::protobuf::FieldDescriptor;
using ::google::protobuf::Reflection;

namespace
{

D
Dmitry Kurtaev 已提交
46 47 48 49 50 51 52
static int toNCHW(int idx)
{
    CV_Assert(-4 <= idx && idx < 4);
    if (idx == 0) return 0;
    else if (idx > 0) return idx % 3 + 1;
    else return (4 + idx) % 3 + 1;
}
53

L
Liubov Batanina 已提交
54 55 56 57 58 59 60 61
static int toNCDHW(int idx)
{
    CV_Assert(-5 <= idx && idx < 5);
    if (idx == 0) return 0;
    else if (idx > 0) return idx % 4 + 1;
    else return (5 + idx) % 4 + 1;
}

62 63 64 65 66
// This values are used to indicate layer output's data layout where it's possible.
enum DataLayout
{
    DATA_LAYOUT_NHWC,
    DATA_LAYOUT_NCHW,
67
    DATA_LAYOUT_NDHWC,
68 69
    DATA_LAYOUT_UNKNOWN,
    DATA_LAYOUT_PLANAR  // 2-dimensional outputs (matmul, flatten, reshape to 2d)
70 71
};

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
typedef std::vector<std::pair<String, int> > StrIntVector;

struct Pin
{
    Pin(const std::string &_name, int _blobIndex = 0) :
        name(_name), blobIndex(_blobIndex) {}

    Pin() :
        name(""), blobIndex(-1) {}

    std::string name;
    int blobIndex;
};

void blobShapeFromTensor(const tensorflow::TensorProto &tensor, MatShape& shape)
{
    shape.clear();
    if (tensor.has_tensor_shape())
    {
        const tensorflow::TensorShapeProto &_shape = tensor.tensor_shape();
        int i, n = _shape.dim_size();
93 94 95
        if (n)
        {
            shape.resize(n);
96

97 98 99 100
            for (i = 0; i < n; i++)
                shape[i] = (int)_shape.dim(i).size();
        }
        else
101
            shape.resize(1, 1);  // Scalar. // FIXIT: should be empty
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
    }
    else
    {
        CV_Error(Error::StsError, "Unknown shape of input tensor");
    }
}

template <typename T>
void parseTensor(const tensorflow::TensorProto &tensor, Mat &dstBlob)
{
    MatShape shape;
    blobShapeFromTensor(tensor, shape);
    int dims = (int)shape.size();

    if (dims == 4)
    {
        // REORDER blob NHWC to NCHW
        swap(shape[2], shape[3]); // NHCW
        swap(shape[1], shape[2]); // NCHW
    }

    dstBlob.create(shape, CV_32F);

125
    Mat tensorContent = getTensorContent(tensor, /*no copy*/false);
126
    int size = tensorContent.total();
127 128 129
    CV_Assert(size == (int)dstBlob.total());

    float *dstData = dstBlob.ptr<float>();
130
    const T *data = reinterpret_cast<const T*>(tensorContent.data);
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160

    if (dims == 4)
    {
        int num = shape[0], channels = shape[1], height = shape[2], width = shape[3];
        int total = num*channels*height*width;
        for(int i_n = 0; i_n < shape[0]; i_n++) {
            for(int i_c = 0; i_c < shape[1]; i_c++) {
                for(int i_h = 0; i_h < shape[2]; i_h++) {
                    for(int i_w = 0; i_w < shape[3]; i_w++) {
                       int dst_i = channels*height*width*i_n + height*width*i_c + width*i_h + i_w;
                       int src_i = channels*height*width*i_n + i_c + channels*width*i_h + channels*i_w;

                       CV_Assert(dst_i < total);
                       CV_Assert(src_i < total);

                       dstData[dst_i] = data[src_i];
                    }
                }
            }
        }
    } else {
        for (int i = 0; i < size; i++)
            dstData[i] = data[i];
    }
}

void blobFromTensor(const tensorflow::TensorProto &tensor, Mat &dstBlob)
{
    switch (tensor.dtype()) {
        case tensorflow::DT_FLOAT:
161
        case tensorflow::DT_HALF:
162 163 164 165 166 167 168 169 170 171 172
            parseTensor<float>(tensor, dstBlob);
            break;
        case tensorflow::DT_DOUBLE:
            parseTensor<double>(tensor, dstBlob);
            break;
        default:
            CV_Error(Error::StsError, "Tensor's data type is not supported");
            break;
    }
}

173
#if 0
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
void printList(const tensorflow::AttrValue::ListValue &val)
{
    std::cout << "(";
    for (int i = 0; i < val.i_size(); i++)
        std::cout << " " << val.i(i);
    std::cout << " )";
}

void printTensorShape(const tensorflow::TensorShapeProto &shape)
{
    std::cout << "[ ";
    for (int d = 0; d < shape.dim_size(); d++)
        std::cout << shape.dim(d).name() <<
                     ":" << shape.dim(d).size() << " ";
    std::cout << "]";
}

void printTensor(const tensorflow::TensorProto &tensor)
{
    printTensorShape(tensor.tensor_shape());

    if (tensor.tensor_content().empty())
        return;

    switch (tensor.dtype())
    {
200
    case tensorflow::DT_FLOAT:
201 202 203 204 205 206 207 208 209
        {
            const float *data = reinterpret_cast<const float*>(tensor.tensor_content().c_str());
            int size = tensor.tensor_content().size() / sizeof(float);
            for (int i = 0; i < std::min(10, size); i++)
                std::cout << " " << data[i];
            if (size > 10)
                std::cout << " ... " << size - 10 << " more";
            break;
        }
210
    case tensorflow::DT_INT32:
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
        {
            const int *data = reinterpret_cast<const int*>(tensor.tensor_content().c_str());
            int size = tensor.tensor_content().size() / sizeof(int);
            for (int i = 0; i < std::min(10, size); i++)
                std::cout << " " << data[i];
            if (size > 10)
                std::cout << " ... " << size - 10 << " more";
            break;
        }
    default:
        CV_Error(Error::StsError, "Tensor type is not supported");
        break;
    }
}

void printLayerAttr(const tensorflow::NodeDef &layer)
{
    std::cout << std::endl << layer.name() << ":" << layer.op();
    for (int ii = 0; ii < layer.input_size(); ii++)
        std::cout << "(" << layer.input(ii) << ")";
    std::cout << std::endl;
    google::protobuf::Map<std::string, tensorflow::AttrValue> attr
            = layer.attr();
    for (google::protobuf::Map<std::string, tensorflow::AttrValue>::const_iterator ai = attr.begin();
         ai != attr.end(); ++ai)
    {
        std::cout << ai->first << ":";
        if (ai->first == "dtype" || ai->first == "T")
            std::cout << ai->second.i();
        else if (ai->first == "padding")
            std::cout << ai->second.s();
        else if (ai->first == "transpose_a" || ai->first == "transpose_b")
            std::cout << ai->second.b();
        //            else if (ai->first == "shape")
        //              printTensorShape(ai->second.shape());
        else if (ai->first == "strides" || ai->first == "ksize")
            printList(ai->second.list());
        else
            printTensor(ai->second.tensor());
        std::cout << std::endl;
    }
}
253
#endif
254 255 256 257 258 259 260 261 262 263 264 265

bool hasLayerAttr(const tensorflow::NodeDef &layer, const std::string &name)
{
    google::protobuf::Map<std::string, tensorflow::AttrValue> attr = layer.attr();
    return attr.find(name) != attr.end();
}

const tensorflow::AttrValue& getLayerAttr(const tensorflow::NodeDef &layer, const std::string &name)
{
    return layer.attr().at(name);
}

266
static DataLayout getDataLayout(const tensorflow::NodeDef& layer)
267 268 269 270 271 272 273 274
{
    if (hasLayerAttr(layer, "data_format"))
    {
        std::string format = getLayerAttr(layer, "data_format").s();
        if (format == "NHWC" || format == "channels_last")
            return DATA_LAYOUT_NHWC;
        else if (format == "NCHW" || format == "channels_first")
            return DATA_LAYOUT_NCHW;
275 276
        else if (format == "NDHWC")
            return DATA_LAYOUT_NDHWC;
277 278 279 280 281 282
        else
            CV_Error(Error::StsParseError, "Unknown data_format value: " + format);
    }
    return DATA_LAYOUT_UNKNOWN;
}

D
Dmitry Kurtaev 已提交
283 284 285 286 287
static inline std::string getNodeName(const std::string& tensorName)
{
    return tensorName.substr(0, tensorName.rfind(':'));
}

288 289 290 291 292
static inline
DataLayout getDataLayout(
        const std::string& layerName,
        const std::map<String, DataLayout>& data_layouts
)
D
Dmitry Kurtaev 已提交
293
{
294
    std::map<String, DataLayout>::const_iterator it = data_layouts.find(getNodeName(layerName));
D
Dmitry Kurtaev 已提交
295 296 297
    return it != data_layouts.end() ? it->second : DATA_LAYOUT_UNKNOWN;
}

298 299 300 301 302
void setStrides(LayerParams &layerParams, const tensorflow::NodeDef &layer)
{
    if (hasLayerAttr(layer, "strides"))
    {
        const tensorflow::AttrValue& val = getLayerAttr(layer, "strides");
303
        int dimX, dimY, dimC, dimD;
304 305 306 307 308
        int layout = getDataLayout(layer);
        if (layout == DATA_LAYOUT_NCHW)
        {
            dimC = 1; dimY = 2; dimX = 3;
        }
309 310 311 312
        else if (layout == DATA_LAYOUT_NDHWC)
        {
            dimD = 1; dimY = 2; dimX = 3; dimC = 4;
        }
313 314 315 316
        else
        {
            dimY = 1; dimX = 2; dimC = 3;
        }
317
        if (!(val.list().i_size() == 4 || val.list().i_size() == 5) ||
318
            val.list().i(0) != 1 || val.list().i(dimC) != 1)
319
            CV_Error(Error::StsError, "Unsupported strides");
320 321 322 323 324 325 326 327 328 329 330
        if (layout == DATA_LAYOUT_NDHWC) {
            int strides[] = {static_cast<int>(val.list().i(dimD)),
                             static_cast<int>(val.list().i(dimY)),
                             static_cast<int>(val.list().i(dimX))};
            layerParams.set("stride",  DictValue::arrayInt(strides, 3));
        }
        else
        {
            layerParams.set("stride_h", static_cast<int>(val.list().i(dimY)));
            layerParams.set("stride_w", static_cast<int>(val.list().i(dimX)));
        }
331 332 333 334 335 336 337 338 339 340 341
    }
}

DictValue parseDims(const tensorflow::TensorProto &tensor) {
    MatShape shape;
    blobShapeFromTensor(tensor, shape);
    int dims = (int)shape.size();

    CV_Assert(tensor.dtype() == tensorflow::DT_INT32);
    CV_Assert(dims == 1);

342 343
    Mat values = getTensorContent(tensor);
    CV_Assert(values.type() == CV_32SC1);
344
    // TODO: add reordering shape if dims == 4
345
    return DictValue::arrayInt((int*)values.data, values.total());
346 347 348 349 350 351 352
}

void setKSize(LayerParams &layerParams, const tensorflow::NodeDef &layer)
{
    if (hasLayerAttr(layer, "ksize"))
    {
        const tensorflow::AttrValue& val = getLayerAttr(layer, "ksize");
353
        int dimX, dimY, dimC, dimD;
354 355 356 357 358
        int layout = getDataLayout(layer);
        if (layout == DATA_LAYOUT_NCHW)
        {
            dimC = 1; dimY = 2; dimX = 3;
        }
359 360 361 362
        else if (layout == DATA_LAYOUT_NDHWC)
        {
            dimD = 1; dimY = 2; dimX = 3; dimC = 4;
        }
363 364 365 366
        else
        {
            dimY = 1; dimX = 2; dimC = 3;
        }
367
        if (!(val.list().i_size() == 4 || val.list().i_size() == 5) ||
368
            val.list().i(0) != 1 || val.list().i(dimC) != 1)
369
            CV_Error(Error::StsError, "Unsupported ksize");
370 371 372 373 374 375 376 377 378 379 380 381

        if (layout == DATA_LAYOUT_NDHWC) {
            int kernel[] = {static_cast<int>(val.list().i(dimD)),
                            static_cast<int>(val.list().i(dimY)),
                            static_cast<int>(val.list().i(dimX))};
            layerParams.set("kernel_size",  DictValue::arrayInt(kernel, 3));
        }
        else
        {
            layerParams.set("kernel_h", static_cast<int>(val.list().i(dimY)));
            layerParams.set("kernel_w", static_cast<int>(val.list().i(dimX)));
        }
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
    }
    else
    {
        layerParams.set("kernel_h", 1);
        layerParams.set("kernel_w", 1);
    }
}

void setPadding(LayerParams &layerParams, const tensorflow::NodeDef &layer)
{
    if (hasLayerAttr(layer, "padding"))
        layerParams.set("pad_mode", getLayerAttr(layer, "padding").s());
}

Pin parsePin(const std::string &name)
{
    Pin pin(name);

400
    size_t delimiter_pos = name.find_first_of(':');
401 402 403 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
    if (delimiter_pos != std::string::npos)
    {
        pin.name = name.substr(0, delimiter_pos);
        std::istringstream(name.substr(delimiter_pos + 1)) >> pin.blobIndex;
    }

    return pin;
}

StrIntVector getNextLayers(const tensorflow::GraphDef& net, const String& layer_name, const String& type = "")
{
   StrIntVector layers;

   for (int li = 0; li < net.node_size(); li++)
   {
       const tensorflow::NodeDef& layer = net.node(li);
       for (int input_id = 0; input_id < layer.input_size(); input_id++) {
           String input_op_name = parsePin(layer.input(input_id)).name;
           bool type_ok = type.empty() ? true : type == layer.op();
           if (input_op_name == layer_name && type_ok)
               layers.push_back(std::make_pair(layer.name(), li));
       }
   }

   return layers;
}

void ExcludeLayer(tensorflow::GraphDef& net, const int layer_index, const int input_blob_index, bool remove_from_net = true) {
    String layer_name = net.node(layer_index).name();
    StrIntVector layers = getNextLayers(net, layer_name);

    String removed_layer_input = net.node(layer_index).input(input_blob_index);

    for (size_t i = 0; i < layers.size(); i++)
    {
        tensorflow::NodeDef* layer = net.mutable_node(layers[i].second);
        for (int input_id = 0; input_id < layer->input_size(); input_id++) {
                String input_op_name = layer->input(input_id);

                if (input_op_name == layer_name) {
                    layer->set_input(input_id, removed_layer_input);
                }
        }
    }

    if (remove_from_net)
        net.mutable_node()->DeleteSubrange(layer_index, 1);
}

450 451
class TFImporter
{
452
public:
453 454
    TFImporter(Net& net, const char *model, const char *config = NULL);
    TFImporter(Net& net, const char *dataModel, size_t lenModel,
455
               const char *dataConfig = NULL, size_t lenConfig = 0);
456 457 458
protected:
    Net& dstNet;
    void populateNet();
459

460 461 462
    void parseNode(const tensorflow::NodeDef& layer);

    DataLayout predictOutputDataLayout(const tensorflow::NodeDef& layer);
463 464 465 466 467 468 469 470 471 472 473

    void kernelFromTensor(const tensorflow::TensorProto &tensor, Mat &dstBlob);

    void connect(const std::map<String, int>& layers_name_id_map, Net& network, const Pin& outPin,
                 const int input_layer_id, const int input_blob_id);
    void connectToAllBlobs(const std::map<String, int>& layer_id, Net& network, const Pin& outPin,
                           const int input_layer_id, const int input_blobs_count);
    const tensorflow::TensorProto& getConstBlob(const tensorflow::NodeDef &layer, std::map<String, int> const_layers,
                                                int input_blob_index = -1, int* actual_inp_blob_idx = 0);


474 475 476 477 478 479
    // Binary serialized TensorFlow graph includes weights.
    tensorflow::GraphDef netBin;
    // Optional text definition of TensorFlow graph. More flexible than binary format
    // and may be used to build the network using binary format only as a weights storage.
    // This approach is similar to Caffe's `.prorotxt` and `.caffemodel`.
    tensorflow::GraphDef netTxt;
480 481

    std::vector<String> netInputsNames;
482
    std::vector<MatShape> netInputShapes;
483 484 485 486 487 488 489 490 491 492

    std::set<String> layers_to_ignore;
    std::map<String, DataLayout> data_layouts;

    // find all Const layers for params
    std::map<String, int> value_id;
    // A map with constant blobs which are shared between multiple layers.
    std::map<String, Mat> sharedWeights;

    std::map<String, int> layer_id;
493 494
};

495 496
TFImporter::TFImporter(Net& net, const char *model, const char *config)
    : dstNet(net)
497 498
{
    if (model && model[0])
499 500
    {
        CV_LOG_DEBUG(NULL, "DNN/TF: processing TensorFlow model from file: " << model);
501
        ReadTFNetParamsFromBinaryFileOrDie(model, &netBin);
502
    }
503
    if (config && config[0])
504 505
    {
        CV_LOG_DEBUG(NULL, "DNN/TF: processing TensorFlow config from file: " << config);
506
        ReadTFNetParamsFromTextFileOrDie(config, &netTxt);
507 508 509
    }

    populateNet();
510 511
}

512 513 514 515 516 517
TFImporter::TFImporter(
        Net& net,
        const char *dataModel, size_t lenModel,
        const char *dataConfig, size_t lenConfig
)
    : dstNet(net)
518 519
{
    if (dataModel != NULL && lenModel > 0)
520 521
    {
        CV_LOG_DEBUG(NULL, "DNN/TF: processing TensorFlow model from memory (" << lenModel << " bytes)");
522
        ReadTFNetParamsFromBinaryBufferOrDie(dataModel, lenModel, &netBin);
523
    }
524
    if (dataConfig != NULL && lenConfig > 0)
525 526
    {
        CV_LOG_DEBUG(NULL, "DNN/TF: processing TensorFlow config from memory (" << lenConfig << " bytes)");
527
        ReadTFNetParamsFromTextBufferOrDie(dataConfig, lenConfig, &netTxt);
528 529
    }
    populateNet();
530 531
}

532 533 534 535 536 537 538
void TFImporter::kernelFromTensor(const tensorflow::TensorProto &tensor, Mat &dstBlob)
{
    MatShape shape;
    blobShapeFromTensor(tensor, shape);
    int dims = (int)shape.size();

    // TODO: other blob types
539 540
    CV_Assert(tensor.dtype() == tensorflow::DT_FLOAT ||
              tensor.dtype() == tensorflow::DT_HALF);
541
    CV_Assert(dims == 4 || dims == 5);
542

543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
    int out_c, input_c, depth, height, width;
    if (dims == 4)
    {
        // REORDER kernel HWIO to OIHW
        swap(shape[0], shape[2]); // IWHO
        swap(shape[1], shape[3]); // IOHW
        swap(shape[0], shape[1]); // OIHW
        depth = 1; height = shape[2]; width = shape[3];
    }
    else
    {
        // REORDER kernel DHWIO to OIDHW
        swap(shape[0], shape[4]); // OHWID
        swap(shape[1], shape[3]); // OIWHD
        swap(shape[2], shape[4]); // OIDHW
        depth = shape[2]; height = shape[3]; width = shape[4];
    }
    out_c = shape[0]; input_c = shape[1];
561 562 563

    dstBlob.create(shape, CV_32F);

564
    Mat tensorContent = getTensorContent(tensor, /*no copy*/false);
565
    int size = tensorContent.total();
566 567 568
    CV_Assert(size == (int)dstBlob.total());

    float *dstData = dstBlob.ptr<float>();
569
    const float *data = reinterpret_cast<const float*>(tensorContent.data);
570

571 572 573 574 575 576 577 578 579 580 581 582 583 584
    int total = out_c * input_c * depth * height * width;
    for (int i_oc = 0; i_oc < out_c; i_oc++) {
        for (int i_ic = 0; i_ic < input_c; i_ic++) {
            for (int i_d = 0; i_d < depth; i_d++) {
                for (int i_h = 0; i_h < height; i_h++) {
                    for (int i_w = 0; i_w < width; i_w++) {
                        int dst_i = input_c * depth * height * width * i_oc +
                                    depth * height * width * i_ic + height * width * i_d + width * i_h + i_w;
                        int src_i = out_c * input_c * width * height * i_d +
                                    out_c * input_c * width * i_h + out_c * input_c * i_w + out_c * i_ic + i_oc;
                        CV_Assert(dst_i < total);
                        CV_Assert(src_i < total);
                       dstData[dst_i] = data[src_i];
                   }
585 586 587 588 589 590 591 592 593 594 595 596
                }
            }
        }
    }
}

void TFImporter::connect(const std::map<String, int>& layers_name_id_map, Net& network, const Pin& outPin,
             const int input_layer_id, const int input_blob_id)
{
    std::map<String, int>::const_iterator it = layers_name_id_map.find(outPin.name);
    if (it == layers_name_id_map.end())
        CV_Error(Error::StsError, "Input layer not found: " + outPin.name);
597 598 599 600 601 602 603 604

    std::vector<String>::iterator inpNameIt = std::find(netInputsNames.begin(), netInputsNames.end(), outPin.name);
    int blobIndex;
    if (inpNameIt == netInputsNames.end())
        blobIndex = outPin.blobIndex;
    else
        blobIndex = inpNameIt - netInputsNames.begin();
    network.connect(it->second, blobIndex, input_layer_id, input_blob_id);
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
}

void TFImporter::connectToAllBlobs(const std::map<String, int>& layer_id, Net& network, const Pin& outPin,
                     const int input_layer_id, const int input_blobs_count)
{
    for (int input_blob_id = 0; input_blob_id < input_blobs_count; input_blob_id++)
        connect(layer_id, network, outPin, input_layer_id, input_blob_id);
}

const tensorflow::TensorProto& TFImporter::getConstBlob(const tensorflow::NodeDef &layer, std::map<String, int> const_layers,
                                              int input_blob_index, int* actual_inp_blob_idx) {
    if (input_blob_index == -1) {
        for(int i = 0; i < layer.input_size(); i++) {
            Pin input = parsePin(layer.input(i));
            if (const_layers.find(input.name) != const_layers.end()) {
                if (input_blob_index != -1)
                    CV_Error(Error::StsError, "More than one input is Const op");

                input_blob_index = i;
            }
        }
    }

    if (input_blob_index == -1)
        CV_Error(Error::StsError, "Const input blob for weights not found");

    Pin kernel_inp = parsePin(layer.input(input_blob_index));
    if (const_layers.find(kernel_inp.name) == const_layers.end())
633 634
        CV_Error(Error::StsError, "Input [" + layer.input(input_blob_index) +
                                  "] for node [" + layer.name() + "] not found");
635 636 637 638 639 640 641
    if (kernel_inp.blobIndex != 0)
        CV_Error(Error::StsError, "Unsupported kernel input");

    if(actual_inp_blob_idx) {
        *actual_inp_blob_idx = input_blob_index;
    }

642 643 644 645 646 647 648
    int nodeIdx = const_layers.at(kernel_inp.name);
    if (nodeIdx < netBin.node_size() && netBin.node(nodeIdx).name() == kernel_inp.name)
    {
        return netBin.node(nodeIdx).attr().at("value").tensor();
    }
    else
    {
649 650
        CV_Assert_N(nodeIdx < netTxt.node_size(),
                    netTxt.node(nodeIdx).name() == kernel_inp.name);
651 652
        return netTxt.node(nodeIdx).attr().at("value").tensor();
    }
653 654
}

D
Dmitry Kurtaev 已提交
655
static void addConstNodes(tensorflow::GraphDef& net, std::map<String, int>& const_layers,
656
                          std::set<String>& layers_to_ignore)
657
{
658
    CV_LOG_DEBUG(NULL, "DNN/TF: addConstNodes(): handling " << net.node_size() << " nodes...");
659
    for (int li = 0; li < net.node_size(); li++)
660 661 662 663 664
    {
        const tensorflow::NodeDef &layer = net.node(li);
        String name = layer.name();
        String type = layer.op();

665 666 667
        //CV_LOG_DEBUG(NULL, "DNN/TF: layer_id=" << li << " - '" << name << "' @ " << type);

        try
D
Dmitry Kurtaev 已提交
668
        {
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
            if (type == "Dequantize")
            {
                // Example of Dequantize node:
                //   name: "conv2d_1/bias"
                //   op: "Dequantize"
                //   input: "conv2d_1/bias_quantized_const" (tensor of dtype DT_QUINT8)
                //   input: "conv2d_1/bias_quantized_min"
                //   input: "conv2d_1/bias_quantized_max"
                //   attr { key: "T" value { type: DT_QUINT8 } }   (quantized type)
                //   attr { key: "mode" value { s: "MIN_FIRST" } } (quantization technique)
                CV_CheckEQ(layer.input_size(), 3, "Dequantize: 3 inputs is supported only");
                for (int i = 0; i < 3; ++i)
                    CV_Assert(const_layers.find(layer.input(i)) != const_layers.end());
                CV_Assert(hasLayerAttr(layer, "mode") &&
                          getLayerAttr(layer, "mode").s() == "MIN_FIRST");

                int tensorId = const_layers[layer.input(0)];
                int minId = const_layers[layer.input(1)];
                int maxId = const_layers[layer.input(2)];

                tensorflow::TensorProto* tensor = net.mutable_node(tensorId)
                                                    ->mutable_attr()->at("value")
                                                     .mutable_tensor();
                CV_CheckEQ((int)tensor->dtype(), (int)tensorflow::DT_QUINT8, "");

                Mat qMin = getTensorContent(net.node(minId).attr().at("value").tensor());
                Mat qMax = getTensorContent(net.node(maxId).attr().at("value").tensor());
                CV_CheckEQ(qMin.total(), (size_t)1, "");
                CV_CheckTypeEQ(qMin.type(), CV_32FC1, "");
                CV_CheckEQ(qMax.total(), (size_t)1, "");
                CV_CheckTypeEQ(qMax.type(), CV_32FC1, "");

                Mat content = getTensorContent(*tensor);

                float minVal = qMin.at<float>(0);
                float rangeScale = (qMax.at<float>(0) - minVal) / 255;
                CV_Assert(rangeScale >= 0);
                content.convertTo(content, CV_32FC1, rangeScale,
                                  rangeScale * cvRound(minVal / rangeScale));

                tensor->set_dtype(tensorflow::DT_FLOAT);
                tensor->set_tensor_content(content.data, content.total() * content.elemSize1());

                net.mutable_node(tensorId)->set_name(name);
                CV_Assert(const_layers.insert(std::make_pair(name, tensorId)).second);
                layers_to_ignore.insert(name);
                continue;
            }
            else if (type != "Const")
                continue;  // only Const parameters are supported

            if (layer.attr().find("value") != layer.attr().end())
            {
                CV_Assert(const_layers.insert(std::make_pair(name, li)).second);
            }
D
Dmitry Kurtaev 已提交
724 725
            layers_to_ignore.insert(name);
        }
726
        catch (const std::exception& e)
727
        {
728 729
            CV_LOG_ERROR(NULL, "DNN/TF: Can't handle node='" << name << "'. Exception: " << e.what());
            throw;
730 731
        }
    }
732
    CV_LOG_DEBUG(NULL, "DNN/TF: layers_to_ignore.size() = " << layers_to_ignore.size());
733 734
}

735 736
// If all inputs of specific layer have the same data layout we can say that
// this layer's output has this data layout too. Returns DATA_LAYOUT_UNKNOWN otherwise.
737
DataLayout TFImporter::predictOutputDataLayout(const tensorflow::NodeDef& layer)
738
{
739
    DataLayout layout = getDataLayout(layer);
740
    if (layout != DATA_LAYOUT_UNKNOWN)
741 742
    {
        CV_LOG_DEBUG(NULL, "DNN/TF: predictOutputDataLayout(" << layer.name() << " @ " << layer.op() << ") => " << (int)layout << " (from attrs)");
743
        return layout;
744
    }
D
Dmitry Kurtaev 已提交
745 746

    // Determine layout by layer's inputs
747 748
    for (int i = 0, n = layer.input_size(); i < n; ++i)
    {
749
        std::map<String, DataLayout>::const_iterator it = data_layouts.find(getNodeName(layer.input(i)));
750 751
        if (it != data_layouts.end())
        {
752
            if (layout != DATA_LAYOUT_UNKNOWN)
753
            {
754
                if (it->second != layout && it->second != DATA_LAYOUT_UNKNOWN)
755 756
                    return DATA_LAYOUT_UNKNOWN;
            }
757 758
            else
                layout = it->second;
759 760
        }
    }
761 762

    if (layout != DATA_LAYOUT_UNKNOWN)
763 764
    {
        CV_LOG_DEBUG(NULL, "DNN/TF: predictOutputDataLayout(" << layer.name() << " @ " << layer.op() << ") => " << (int)layout << " (from inputs)");
765
        return layout;
766
    }
767 768

    // Determine layout by layer's consumers recursively.
769
    std::map<String, DataLayout>::const_iterator it = data_layouts.find(layer.name());
770 771
    CV_Assert(it != data_layouts.end());
    return it->second;
772 773
}

774
void TFImporter::populateNet()
775
{
776
    CV_Assert(netBin.ByteSize() || netTxt.ByteSize());
777

778 779 780 781
    CV_LOG_INFO(NULL, "DNN/TF: parsing model"
        << (netBin.has_versions() ? cv::format(" produced by TF v%d (min_consumer=%d)", (int)netBin.versions().producer(), (int)netBin.versions().min_consumer()) : cv::String(" (N/A version info)"))
        << ". Number of nodes = " << netBin.node_size()
    );
782

783
    if (netTxt.ByteSize())
784
    {
785 786 787 788 789 790 791 792 793 794 795 796
        CV_LOG_INFO(NULL, "DNN/TF: parsing config"
            << (netTxt.has_versions() ? cv::format(" produced by TF v%d (min_consumer=%d)", (int)netTxt.versions().producer(), (int)netTxt.versions().min_consumer()) : cv::String(" (N/A version info)"))
            << ". Number of nodes = " << netTxt.node_size()
        );

        RemoveIdentityOps(netBin);
        CV_LOG_DEBUG(NULL, "DNN/TF: RemoveIdentityOps(model) => " << netBin.node_size() << " nodes");
        RemoveIdentityOps(netTxt);
        CV_LOG_DEBUG(NULL, "DNN/TF: RemoveIdentityOps(config) => " << netTxt.node_size() << " nodes");

        sortByExecutionOrder(netTxt);
        CV_LOG_DEBUG(NULL, "DNN/TF: sortByExecutionOrder(config) => " << netTxt.node_size() << " nodes");
797
    }
D
Dmitry Kurtaev 已提交
798 799
    else
    {
800 801
        removePhaseSwitches(netBin);
        CV_LOG_DEBUG(NULL, "DNN/TF: removePhaseSwitches(model) => " << netBin.node_size() << " nodes");
802

803 804 805 806 807 808 809 810
        RemoveIdentityOps(netBin);
        CV_LOG_DEBUG(NULL, "DNN/TF: RemoveIdentityOps(model) => " << netBin.node_size() << " nodes");

        simplifySubgraphs(netBin);
        CV_LOG_DEBUG(NULL, "DNN/TF: simplifySubgraphs(model) => " << netBin.node_size() << " nodes");
        sortByExecutionOrder(netBin);
        CV_LOG_DEBUG(NULL, "DNN/TF: sortByExecutionOrder(model) => " << netBin.node_size() << " nodes");
    }
811 812 813 814 815

    tensorflow::GraphDef& net = netTxt.ByteSize() != 0 ? netTxt : netBin;

    int layersSize = net.node_size();

816 817
    // Pre-fill data layouts where they are set explicitly.
    // Assuming that nodes are in topological order
818
    for (int i = layersSize - 1; i >= 0; --i)
819 820 821 822
    {
        const tensorflow::NodeDef& layer = net.node(i);
        std::string name = layer.name();

823
        CV_LOG_DEBUG(NULL, "DNN/TF: node(" << i << " - '" << name << "') propagating layout...");
824

825
        try
826
        {
827 828
            DataLayout layout = getDataLayout(layer);
            std::map<String, DataLayout>::iterator it = data_layouts.find(name);
829 830 831 832 833 834 835
            if (it != data_layouts.end())
            {
                if (layout != DATA_LAYOUT_UNKNOWN)
                {
                    if (it->second == DATA_LAYOUT_UNKNOWN)
                        it->second = layout;
                    else if (it->second != layout)
836
                    {
837
                        it->second = DATA_LAYOUT_UNKNOWN;
838 839
                        layout = DATA_LAYOUT_UNKNOWN;
                    }
840
                }
841 842
                else
                    layout = it->second;
843 844 845
            }
            else
                data_layouts[name] = layout;
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869

            // Specify input layers to have the same data layout.
            for (int j = 0; j < layer.input_size(); ++j)
            {
                name = getNodeName(layer.input(j));
                it = data_layouts.find(name);
                if (it != data_layouts.end())
                {
                    if (layout != DATA_LAYOUT_UNKNOWN)
                    {
                        if (it->second == DATA_LAYOUT_UNKNOWN)
                            it->second = layout;
                        else if (it->second != layout)
                            it->second = DATA_LAYOUT_UNKNOWN;
                    }
                }
                else
                    data_layouts[name] = layout;
            }
        }
        catch (const std::exception& e)
        {
            CV_LOG_ERROR(NULL, "DNN/TF: Can't propagate layout for node='" << name << "'. Exception: " << e.what());
            throw;
870 871
        }
    }
872

873 874
    addConstNodes(netBin, value_id, layers_to_ignore);
    addConstNodes(netTxt, value_id, layers_to_ignore);
875 876 877 878


    for (int li = 0; li < layersSize; li++)
    {
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
        const tensorflow::NodeDef& layer = net.node(li);

        const std::string name = layer.name();
        const std::string type = layer.op();
        const int ninputs = layer.input_size();
        CV_LOG_DEBUG(NULL, "DNN/TF: (" << li << "/" << layersSize << ") Parse layer " << name << " @ " << type << " with " << ninputs << " inputs");

        parseNode(layer);
    }

    for (size_t i = 0; i < netInputsNames.size(); i++)
    {
        CV_LOG_DEBUG(NULL, "DNN/TF: Model input: " << i << " - '" << netInputsNames[i] << "'");
        CV_Assert(!netInputsNames[i].empty());
    }
    dstNet.setInputsNames(netInputsNames);
    CV_LOG_DEBUG(NULL, "DNN/TF: ===================== Import completed =====================");
}

void TFImporter::parseNode(const tensorflow::NodeDef& layer_)
{
    tensorflow::NodeDef layer = layer_;

    tensorflow::GraphDef& net = netTxt.ByteSize() != 0 ? netTxt : netBin;

    /*const*/ std::string name = layer.name();
    /*const*/ std::string type = layer.op();
    /*const*/ int num_inputs = layer.input_size();

    try
    {
910 911
        LayerParams layerParams;

912 913 914 915 916
        if (layers_to_ignore.find(name) != layers_to_ignore.end())
        {
            CV_LOG_DEBUG(NULL, "DNN/TF:     ignored");
            return;
        }
917

918
        DataLayout predictedLayout = predictOutputDataLayout(layer);
919
        data_layouts[name] = predictedLayout;
920

921
        if (type == "Conv2D" || type == "SpaceToBatchND" || type == "DepthwiseConv2dNative" || type == "Pad" || type == "MirrorPad" || type == "Conv3D")
922
        {
923
            CV_CheckGT(num_inputs, 0, "");
924 925 926
            // The first node of dilated convolution subgraph.
            // Extract input node, dilation rate and paddings.
            std::string input = layer.input(0);
927 928 929 930 931 932 933
            StrIntVector next_layers;
            if (type == "SpaceToBatchND" || type == "Pad")
            {
                next_layers = getNextLayers(net, name, "Conv2D");
                if (next_layers.empty())
                    next_layers = getNextLayers(net, name, "DepthwiseConv2dNative");
            }
934

935 936 937 938 939 940
            if (type == "SpaceToBatchND")
            {
                // op: "SpaceToBatchND"
                // input: "input"
                // input: "SpaceToBatchND/block_shape"
                // input: "SpaceToBatchND/paddings"
941
                CV_CheckEQ(num_inputs, 3, "");
942 943

                DictValue dilation = parseDims(getConstBlob(layer, value_id, 1));
944 945 946
                CV_Assert(dilation.size() == 2);
                layerParams.set("dilation_h", dilation.get<int>(0));
                layerParams.set("dilation_w", dilation.get<int>(1));
947 948 949 950 951 952 953 954 955

                Mat paddings;
                parseTensor<int>(getConstBlob(layer, value_id, 2), paddings);

                // paddings is a 2x2 matrix: [[top, bot], [left, right]]
                layerParams.set("pad_h", paddings.at<float>(0));
                layerParams.set("pad_w", paddings.at<float>(2));

                CV_Assert(next_layers.size() == 1);
956
                layers_to_ignore.insert(next_layers[0].first);
957 958 959

                // FIXIT don't override, rewrite this code
                layer = net.node(next_layers[0].second);
960 961
                name = layer.name();
                type = layer.op();
962 963
                num_inputs = layer.input_size();
                CV_LOG_DEBUG(NULL, "DNN/TF:     switched to layer " << name << " @ " << type << ") with " << num_inputs << " inputs");
964
            }
965
            else if (type == "Pad" || type == "MirrorPad")
966 967 968 969 970
            {
                Mat paddings = getTensorContent(getConstBlob(layer, value_id, 1));
                CV_Assert(paddings.type() == CV_32SC1);
                if (paddings.total() == 8)
                {
L
luz.paz 已提交
971
                    // Perhaps, we have NHWC padding dimensions order.
972 973 974 975 976 977 978 979 980 981 982
                    //  N    H    W    C
                    // 0 1  2 3  4 5  6 7
                    std::swap(paddings.at<int32_t>(2), paddings.at<int32_t>(6));
                    std::swap(paddings.at<int32_t>(3), paddings.at<int32_t>(7));
                    //  N    C    W    H
                    // 0 1  2 3  4 5  6 7
                    std::swap(paddings.at<int32_t>(4), paddings.at<int32_t>(6));
                    std::swap(paddings.at<int32_t>(5), paddings.at<int32_t>(7));
                    //  N    C    H    W
                    // 0 1  2 3  4 5  6 7
                }
983

984 985
                if (next_layers.empty() || paddings.total() != 8 ||
                    paddings.at<int32_t>(4) != paddings.at<int32_t>(5) ||
986
                    paddings.at<int32_t>(6) != paddings.at<int32_t>(7) || type == "MirrorPad")
987 988 989
                {
                    // Just a single padding layer.
                    layerParams.set("paddings", DictValue::arrayInt<int*>((int*)paddings.data, paddings.total()));
990 991
                    if (type == "MirrorPad")
                        layerParams.set("type", "reflect");
992 993 994 995 996

                    int id = dstNet.addLayer(name, "Padding", layerParams);
                    layer_id[name] = id;

                    connect(layer_id, dstNet, parsePin(input), id, 0);
997
                    return;
998 999 1000 1001 1002 1003 1004 1005 1006 1007
                }
                else
                {
                    // Merge with subsequent convolutional layer.
                    CV_Assert(next_layers.size() == 1);

                    layerParams.set("pad_h", paddings.at<int32_t>(4));
                    layerParams.set("pad_w", paddings.at<int32_t>(6));

                    layers_to_ignore.insert(next_layers[0].first);
1008 1009 1010

                    // FIXIT don't override, rewrite this code
                    layer = net.node(next_layers[0].second);
1011 1012
                    name = layer.name();
                    type = layer.op();
1013 1014
                    num_inputs = layer.input_size();
                    CV_LOG_DEBUG(NULL, "DNN/TF:     switched to layer " << name << " @ " << type << ") with " << num_inputs << " inputs");
1015 1016
                }
            }
1017

1018 1019 1020 1021 1022 1023 1024
            // For the object detection networks, TensorFlow Object Detection API
            // predicts deltas for bounding boxes in yxYX (ymin, xmin, ymax, xmax)
            // order. We can manage it at DetectionOutput layer parsing predictions
            // or shuffle last convolution's weights.
            bool locPredTransposed = hasLayerAttr(layer, "loc_pred_transposed") &&
                                     getLayerAttr(layer, "loc_pred_transposed").b();

1025 1026 1027
            layerParams.set("bias_term", false);
            layerParams.blobs.resize(1);

1028
            next_layers = getNextLayers(net, name, "BiasAdd");
1029 1030 1031 1032 1033 1034 1035 1036
            if (next_layers.size() == 1) {
                layerParams.set("bias_term", true);
                layerParams.blobs.resize(2);

                int weights_layer_index = next_layers[0].second;

                blobFromTensor(getConstBlob(net.node(weights_layer_index), value_id), layerParams.blobs[1]);
                ExcludeLayer(net, weights_layer_index, 0, false);
1037
                layers_to_ignore.insert(next_layers[0].first);
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049

                // Shuffle bias from yxYX to xyXY.
                if (locPredTransposed)
                {
                    const int numWeights = layerParams.blobs[1].total();
                    float* biasData = reinterpret_cast<float*>(layerParams.blobs[1].data);
                    CV_Assert(numWeights % 4 == 0);
                    for (int i = 0; i < numWeights; i += 2)
                    {
                        std::swap(biasData[i], biasData[i + 1]);
                    }
                }
1050 1051
            }

1052 1053 1054 1055 1056
            int kernelTensorInpId = -1;
            const tensorflow::TensorProto& kernelTensor = getConstBlob(layer, value_id, -1, &kernelTensorInpId);
            const String kernelTensorName = layer.input(kernelTensorInpId);
            std::map<String, Mat>::iterator sharedWeightsIt = sharedWeights.find(kernelTensorName);
            if (sharedWeightsIt == sharedWeights.end())
1057
            {
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
                kernelFromTensor(kernelTensor, layerParams.blobs[0]);
                releaseTensor(const_cast<tensorflow::TensorProto*>(&kernelTensor));

                int* kshape = layerParams.blobs[0].size.p;
                const int outCh = kshape[0];
                const int inCh = kshape[1];
                const int height = kshape[2];
                const int width = kshape[3];
                if (type == "DepthwiseConv2dNative")
                {
                    CV_Assert(!locPredTransposed);
                    const int chMultiplier = kshape[0];

                    Mat copy = layerParams.blobs[0].clone();
                    float* src = (float*)copy.data;
                    float* dst = (float*)layerParams.blobs[0].data;
                    for (int i = 0; i < chMultiplier; ++i)
                        for (int j = 0; j < inCh; ++j)
                            for (int s = 0; s < height * width; ++s)
                                {
                                    int src_i = (i * inCh + j) * height * width + s;
                                    int dst_i = (j * chMultiplier + i) * height* width + s;
                                    dst[dst_i] = src[src_i];
                                }
                    // TODO Use reshape instead
                    kshape[0] = inCh * chMultiplier;
                    kshape[1] = 1;
                    size_t* kstep = layerParams.blobs[0].step.p;
                    kstep[0] = kstep[1]; // fix steps too
                }
1088

1089 1090
                // Shuffle output channels from yxYX to xyXY.
                if (locPredTransposed)
1091
                {
1092 1093 1094 1095 1096 1097 1098
                    const int slice = height * width * inCh;
                    for (int i = 0; i < outCh; i += 2)
                    {
                        cv::Mat src(1, slice, CV_32F, layerParams.blobs[0].ptr<float>(i));
                        cv::Mat dst(1, slice, CV_32F, layerParams.blobs[0].ptr<float>(i + 1));
                        std::swap_ranges(src.begin<float>(), src.end<float>(), dst.begin<float>());
                    }
1099
                }
1100
                sharedWeights[kernelTensorName] = layerParams.blobs[0];
1101
            }
1102 1103 1104 1105
            else
            {
                layerParams.blobs[0] = sharedWeightsIt->second;
            }
1106 1107
            Mat weights = layerParams.blobs[0];
            layerParams.set("kernel_size",  DictValue::arrayInt(&weights.size[2], weights.dims - 2));
1108 1109

            layerParams.set("num_output", layerParams.blobs[0].size[0]);
1110 1111

            setStrides(layerParams, layer);
1112 1113
            if (!layerParams.has("pad_w") && !layerParams.has("pad_h"))
                setPadding(layerParams, layer);
1114

1115 1116 1117 1118 1119 1120
            // The final node of dilated convolution subgraph.
            next_layers = getNextLayers(net, name, "BatchToSpaceND");
            if (!next_layers.empty())
            {
                CV_Assert(next_layers.size() == 1);
                ExcludeLayer(net, next_layers[0].second, 0, false);
1121
                layers_to_ignore.insert(next_layers[0].first);
1122 1123
            }

1124 1125 1126 1127
            int id = dstNet.addLayer(name, "Convolution", layerParams);
            layer_id[name] = id;

            // one input only
1128
            connect(layer_id, dstNet, parsePin(input), id, 0);
1129

D
Dmitry Kurtaev 已提交
1130 1131

            if (getDataLayout(name, data_layouts) == DATA_LAYOUT_UNKNOWN)
1132
                data_layouts[name] = DATA_LAYOUT_NHWC;
1133
        }
D
Dmitry Kurtaev 已提交
1134
        else if (type == "BiasAdd" || type == "Add" || type == "AddV2" || type == "Sub" || type=="AddN")
1135
        {
1136
            CV_CheckGT(num_inputs, 0, "");
D
dkurt 已提交
1137
            bool haveConst = false;
1138
            for(int ii = 0; !haveConst && ii < num_inputs; ++ii)
D
dkurt 已提交
1139 1140 1141 1142
            {
                Pin input = parsePin(layer.input(ii));
                haveConst = value_id.find(input.name) != value_id.end();
            }
1143
            CV_Assert(!haveConst || num_inputs == 2);
1144

D
dkurt 已提交
1145 1146
            if (haveConst)
            {
1147 1148
                Mat values = getTensorContent(getConstBlob(layer, value_id));
                CV_Assert(values.type() == CV_32FC1);
1149 1150
                if (type == "Sub")
                    values *= -1.0f;
1151

1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
                int id;
                if (values.total() == 1)  // is a scalar.
                {
                    layerParams.set("shift", values.at<float>(0));
                    id = dstNet.addLayer(name, "Power", layerParams);
                }
                else  // is a vector
                {
                    layerParams.blobs.resize(1, values);
                    id = dstNet.addLayer(name, "Shift", layerParams);
                }
D
dkurt 已提交
1163
                layer_id[name] = id;
1164

D
dkurt 已提交
1165 1166 1167 1168 1169 1170
                // one input only
                connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
            }
            else
            {
                layerParams.set("operation", "sum");
1171 1172 1173 1174 1175 1176
                if (type == "Sub")
                {
                    static float subCoeffs[] = {1.f, -1.f};
                    layerParams.set("coeff", DictValue::arrayReal<float*>(subCoeffs, 2));
                }

D
dkurt 已提交
1177 1178 1179
                int id = dstNet.addLayer(name, "Eltwise", layerParams);
                layer_id[name] = id;

1180
                for (int ii = 0; ii < num_inputs; ii++)
D
dkurt 已提交
1181 1182 1183 1184
                {
                    Pin inp = parsePin(layer.input(ii));
                    if (layer_id.find(inp.name) == layer_id.end())
                        CV_Error(Error::StsError, "Input layer not found: " + inp.name);
1185
                    connect(layer_id, dstNet, inp, id, ii);
D
dkurt 已提交
1186 1187
                }
            }
1188 1189 1190
        }
        else if (type == "MatMul")
        {
1191
            CV_CheckEQ(num_inputs, 2, "");
1192

1193 1194 1195 1196 1197 1198 1199
            // For the object detection networks, TensorFlow Object Detection API
            // predicts deltas for bounding boxes in yxYX (ymin, xmin, ymax, xmax)
            // order. We can manage it at DetectionOutput layer parsing predictions
            // or shuffle last Faster-RCNN's matmul weights.
            bool locPredTransposed = hasLayerAttr(layer, "loc_pred_transposed") &&
                                     getLayerAttr(layer, "loc_pred_transposed").b();

1200 1201 1202
            layerParams.set("bias_term", false);
            layerParams.blobs.resize(1);

1203
            StrIntVector next_layers = getNextLayers(net, name, "BiasAdd");  // FIXIT Use layers fusion instead
1204 1205 1206 1207
            if (next_layers.empty())
            {
                next_layers = getNextLayers(net, name, "Add");
            }
1208 1209 1210 1211 1212 1213 1214
            if (next_layers.size() == 1) {
                layerParams.set("bias_term", true);
                layerParams.blobs.resize(2);

                int weights_layer_index = next_layers[0].second;
                blobFromTensor(getConstBlob(net.node(weights_layer_index), value_id), layerParams.blobs[1]);
                ExcludeLayer(net, weights_layer_index, 0, false);
1215
                layers_to_ignore.insert(next_layers[0].first);
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226

                if (locPredTransposed)
                {
                    const int numWeights = layerParams.blobs[1].total();
                    float* biasData = reinterpret_cast<float*>(layerParams.blobs[1].data);
                    CV_Assert(numWeights % 4 == 0);
                    for (int i = 0; i < numWeights; i += 2)
                    {
                        std::swap(biasData[i], biasData[i + 1]);
                    }
                }
1227 1228 1229
            }

            int kernel_blob_index = -1;
1230
            const tensorflow::TensorProto& kernelTensor = getConstBlob(layer, value_id, -1, &kernel_blob_index);
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
            const String kernelTensorName = layer.input(kernel_blob_index);
            std::map<String, Mat>::iterator sharedWeightsIt = sharedWeights.find(kernelTensorName);
            if (sharedWeightsIt == sharedWeights.end())
            {
                blobFromTensor(kernelTensor, layerParams.blobs[0]);
                releaseTensor(const_cast<tensorflow::TensorProto*>(&kernelTensor));
                sharedWeights[kernelTensorName] = layerParams.blobs[0];
            }
            else
            {
                layerParams.blobs[0] = sharedWeightsIt->second;
            }
1243 1244 1245 1246 1247 1248 1249

            if (kernel_blob_index == 1) { // In this case output is computed by x*W formula - W should be transposed
                Mat data = layerParams.blobs[0].t();
                layerParams.blobs[0] = data.clone();
            }

            layerParams.set("num_output", layerParams.blobs[0].size[0]);
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
            if (locPredTransposed)
            {
                CV_Assert(layerParams.blobs[0].dims == 2);
                for (int i = 0; i < layerParams.blobs[0].size[0]; i += 2)
                {
                    cv::Mat src = layerParams.blobs[0].row(i);
                    cv::Mat dst = layerParams.blobs[0].row(i + 1);
                    std::swap_ranges(src.begin<float>(), src.end<float>(), dst.begin<float>());
                }
            }
1260 1261 1262 1263 1264 1265 1266

            int id = dstNet.addLayer(name, "InnerProduct", layerParams);
            layer_id[name] = id;

            // one input only
            int input_blob_index = kernel_blob_index == 0 ? 1 : 0;
            connect(layer_id, dstNet, parsePin(layer.input(input_blob_index)), id, 0);
1267
            data_layouts[name] = DATA_LAYOUT_PLANAR;
1268 1269 1270
        }
        else if (type == "Reshape")
        {
1271
            CV_CheckGT(num_inputs, 0, "");
1272
            Pin inpId = parsePin(layer.input(0));
1273
            DataLayout inpLayout = getDataLayout(layer.input(0), data_layouts);
1274 1275 1276
            // There are two possible implementations: reshape an input using
            // predefined sizes or use a second input blob as a source of new shape.
            if (value_id.find(layer.input(1)) != value_id.end())
1277
            {
1278
                Mat newShape = getTensorContent(getConstBlob(layer, value_id, 1));
D
Dmitry Kurtaev 已提交
1279 1280 1281 1282 1283 1284
                if (newShape.total() == 4)
                {
                    // NHWC->NCHW
                    std::swap(*newShape.ptr<int32_t>(0, 2), *newShape.ptr<int32_t>(0, 3));
                    std::swap(*newShape.ptr<int32_t>(0, 1), *newShape.ptr<int32_t>(0, 2));
                }
1285
                if (inpLayout == DATA_LAYOUT_NHWC)
1286
                {
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
                    if (newShape.total() != 4 || newShape.at<int>(1) == 1)
                    {
                        LayerParams permLP;
                        int order[] = {0, 2, 3, 1};  // From OpenCV's NCHW to NHWC.
                        permLP.set("order", DictValue::arrayInt<int*>(order, 4));

                        std::string permName = name + "/nchw";
                        CV_Assert(layer_id.find(permName) == layer_id.end());
                        int permId = dstNet.addLayer(permName, "Permute", permLP);
                        layer_id[permName] = permId;
                        connect(layer_id, dstNet, inpId, permId, 0);
                        inpId = Pin(permName);
                        inpLayout = DATA_LAYOUT_NCHW;
                    }
1301 1302 1303 1304 1305 1306 1307 1308 1309
                }
                layerParams.set("dim", DictValue::arrayInt<int*>(newShape.ptr<int>(), newShape.total()));

                int id = dstNet.addLayer(name, "Reshape", layerParams);
                layer_id[name] = id;

                // one input only
                connect(layer_id, dstNet, inpId, id, 0);
                data_layouts[name] = newShape.total() == 2 ? DATA_LAYOUT_PLANAR : inpLayout;
1310
            }
1311
            else
D
Dmitry Kurtaev 已提交
1312
            {
1313 1314 1315 1316 1317
                int id = dstNet.addLayer(name, "Reshape", layerParams);
                layer_id[name] = id;
                connect(layer_id, dstNet, inpId, id, 0);
                connect(layer_id, dstNet, parsePin(layer.input(1)), id, 1);
                data_layouts[name] = inpLayout;
D
Dmitry Kurtaev 已提交
1318
            }
1319
        }
1320
        else if (type == "Flatten" || type == "Squeeze")
1321
        {
1322
            CV_CheckGT(num_inputs, 0, "");
1323
            Pin inpId = parsePin(layer.input(0));
D
Dmitry Kurtaev 已提交
1324
            int inpLayout = getDataLayout(layer.input(0), data_layouts);
1325 1326 1327 1328
            if (type == "Squeeze")
            {
                CV_Assert(hasLayerAttr(layer, "squeeze_dims"));
                const tensorflow::AttrValue& dims = getLayerAttr(layer, "squeeze_dims");
1329 1330 1331 1332 1333 1334 1335
                std::vector<int> dimsVector(dims.list().i_size());
                for (int i = 0; i < dimsVector.size(); ++i)
                    dimsVector[i] = dims.list().i(i);

                // Flatten layer can squeeze dimensions range into one.
                std::sort(dimsVector.begin(), dimsVector.end());
                for (int i = 1; i < dimsVector.size(); ++i)
1336
                {
1337
                    if (dimsVector[i] != dimsVector[i - 1] + 1)
1338 1339
                        CV_Error(Error::StsNotImplemented, "Unsupported squeeze configuration");
                }
1340 1341
                int start = dimsVector.front() - 1, end = dimsVector.back();
                if (start == -1 && end == 0)  // squeeze 0th dimension
1342
                {
1343 1344
                    start = 0;
                    end = 1;
1345
                }
1346 1347
                layerParams.set("axis", start);
                layerParams.set("end_axis", end);
1348 1349
            }
            if (inpLayout == DATA_LAYOUT_NHWC)
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
            {
                LayerParams permLP;
                int order[] = {0, 2, 3, 1};  // From OpenCV's NCHW to NHWC.
                permLP.set("order", DictValue::arrayInt<int*>(order, 4));

                std::string permName = name + "/nchw";
                CV_Assert(layer_id.find(permName) == layer_id.end());
                int permId = dstNet.addLayer(permName, "Permute", permLP);
                layer_id[permName] = permId;
                connect(layer_id, dstNet, inpId, permId, 0);
                inpId = Pin(permName);
            }
1362 1363
            int id = dstNet.addLayer(name, "Flatten", layerParams);
            layer_id[name] = id;
1364
            connect(layer_id, dstNet, inpId, id, 0);
1365
            data_layouts[name] = DATA_LAYOUT_PLANAR;
1366 1367 1368
        }
        else if (type == "Transpose")
        {
1369
            CV_CheckGT(num_inputs, 0, "");
1370 1371 1372 1373 1374
            Mat perm = getTensorContent(getConstBlob(layer, value_id, 1));
            CV_Assert(perm.type() == CV_32SC1);
            int* permData = (int*)perm.data;
            if (perm.total() == 4)
            {
1375 1376
                // Only NHWC <-> NCHW permutations are allowed. OpenCV is always
                // keep NCHW layout this way.
D
Dmitry Kurtaev 已提交
1377
                int inpLayout = getDataLayout(layer.input(0), data_layouts);
D
Dmitry Kurtaev 已提交
1378
                std::string type = "Identity";
D
Dmitry Kurtaev 已提交
1379
                if (inpLayout == DATA_LAYOUT_NHWC)
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
                {
                    if (permData[0] == 0 && permData[1] == 3 && permData[2] == 1 && permData[3] == 2)
                    {
                        // in TensorFlow: NHWC->NCHW
                        // in OpenCV: NCHW->NCHW
                        data_layouts[name] = DATA_LAYOUT_NCHW;
                    }
                    else if (permData[0] == 0 && permData[1] == 1 && permData[2] == 2 && permData[3] == 3)
                    {
                        // in TensorFlow: NHWC->NHWC
                        // in OpenCV: NCHW->NCHW
                        data_layouts[name] = DATA_LAYOUT_NHWC;
                    }
D
Dmitry Kurtaev 已提交
1393 1394 1395 1396 1397 1398 1399 1400 1401
                    else if (permData[0] == 0 && permData[1] == 3 && permData[2] == 2 && permData[3] == 1)
                    {
                        // in TensorFlow: NHWC->NCWH
                        // in OpenCV: NCHW->NCWH
                        int permData[] = {0, 1, 3, 2};
                        layerParams.set("order", DictValue::arrayInt<int*>(permData, perm.total()));
                        data_layouts[name] = DATA_LAYOUT_NCHW;  // we keep track NCHW because channels position only matters
                        type = "Permute";
                    }
1402
                    else
1403
                        CV_Error(Error::StsParseError, "Only NHWC <-> NCHW permutations are allowed.");
1404
                }
D
Dmitry Kurtaev 已提交
1405
                else if (inpLayout == DATA_LAYOUT_NCHW)
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
                {
                    if (permData[0] == 0 && permData[1] == 2 && permData[2] == 3 && permData[3] == 1)
                    {
                        // in TensorFlow: NCHW->NHWC
                        // in OpenCV: NCHW->NCHW
                        data_layouts[name] = DATA_LAYOUT_NHWC;
                    }
                    else if (permData[0] == 0 && permData[1] == 1 && permData[2] == 2 && permData[3] == 3)
                    {
                        // in TensorFlow: NCHW->NCHW
                        // in OpenCV: NCHW->NCHW
                        data_layouts[name] = DATA_LAYOUT_NCHW;
                    }
                    else
1420
                        CV_Error(Error::StsParseError, "Only NHWC <-> NCHW permutations are allowed.");
1421
                }
D
Dmitry Kurtaev 已提交
1422
                int id = dstNet.addLayer(name, type, layerParams);
1423 1424
                layer_id[name] = id;
                connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
1425
            }
1426 1427 1428
            else
            {
                layerParams.set("order", DictValue::arrayInt<int*>(permData, perm.total()));
1429

1430 1431
                int id = dstNet.addLayer(name, "Permute", layerParams);
                layer_id[name] = id;
1432

1433 1434 1435 1436
                // one input only
                connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
                data_layouts[name] = DATA_LAYOUT_UNKNOWN;
            }
1437
        }
1438 1439 1440 1441 1442
        else if (type == "Const")
        {
        }
        else if (type == "LRN")
        {
1443
            CV_CheckGT(num_inputs, 0, "");
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
            if(hasLayerAttr(layer, "alpha")) {
                layerParams.set("alpha", getLayerAttr(layer, "alpha").f());
            }
            if(hasLayerAttr(layer, "beta")) {
                layerParams.set("beta", getLayerAttr(layer, "beta").f());
            }
            if(hasLayerAttr(layer, "depth_radius")) {
                int radius = (int)getLayerAttr(layer, "depth_radius").i();
                layerParams.set("local_size", 2*radius + 1);
            }
            if(hasLayerAttr(layer, "bias")) {
                layerParams.set("bias", getLayerAttr(layer, "bias").f());
            }
            layerParams.set("norm_by_size", false);

            int id = dstNet.addLayer(name, "LRN", layerParams);
            layer_id[name] = id;

1462
            connectToAllBlobs(layer_id, dstNet, parsePin(layer.input(0)), id, num_inputs);
1463
        }
D
dkurt 已提交
1464
        else if (type == "Concat" || type == "ConcatV2")
1465
        {
1466 1467
            CV_CheckGT(num_inputs, 0, "");
            int axisId = (type == "Concat" ? 0 : num_inputs - 1);
D
dkurt 已提交
1468
            int axis = getConstBlob(layer, value_id, axisId).int_val().Get(0);
1469

D
Dmitry Kurtaev 已提交
1470
            if (getDataLayout(name, data_layouts) == DATA_LAYOUT_NHWC)
1471
                axis = toNCHW(axis);
L
Liubov Batanina 已提交
1472 1473
            else if (getDataLayout(name, data_layouts) == DATA_LAYOUT_NDHWC)
                axis = toNCDHW(axis);
1474
            layerParams.set("axis", axis);
1475

1476
            // input(0) or input(n-1) is concat_dim
D
dkurt 已提交
1477
            int from = (type == "Concat" ? 1 : 0);
1478
            int to = (type == "Concat" ? num_inputs : num_inputs - 1);
D
dkurt 已提交
1479

1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
            for (int ii = from; ii < to; ii++)
            {
                Pin inp = parsePin(layer.input(ii));
                if (layer_id.find(inp.name) == layer_id.end())
                {
                    // There are constant inputs.
                    LayerParams lp;
                    lp.name = inp.name;
                    lp.type = "Const";
                    lp.blobs.resize(1);
                    blobFromTensor(getConstBlob(layer, value_id, ii), lp.blobs.back());
                    CV_Assert_N(!lp.blobs[0].empty(), lp.blobs[0].type() == CV_32F);

                    int constInpId = dstNet.addLayer(lp.name, lp.type, lp);
                    layer_id[lp.name] = constInpId;
                }
            }

            int id = dstNet.addLayer(name, "Concat", layerParams);
            layer_id[name] = id;

D
dkurt 已提交
1501
            for (int ii = from; ii < to; ii++)
1502 1503 1504 1505
            {
                Pin inp = parsePin(layer.input(ii));
                if (layer_id.find(inp.name) == layer_id.end())
                    CV_Error(Error::StsError, "Input layer not found: " + inp.name);
1506
                connect(layer_id, dstNet, inp, id, ii - from);
1507 1508
            }
        }
1509
        else if (type == "MaxPool" || type == "MaxPool3D")
1510
        {
1511
            CV_CheckGT(num_inputs, 0, "");
1512 1513 1514 1515 1516
            layerParams.set("pool", "max");

            setKSize(layerParams, layer);
            setStrides(layerParams, layer);
            setPadding(layerParams, layer);
1517 1518
            // Test_TensorFlow_nets.EAST_text_detection/1, NGRAPH/CPU
            layerParams.set("ceil_mode", false);
1519 1520 1521 1522

            int id = dstNet.addLayer(name, "Pooling", layerParams);
            layer_id[name] = id;

1523
            connectToAllBlobs(layer_id, dstNet, parsePin(layer.input(0)), id, num_inputs);
1524
        }
1525
        else if (type == "AvgPool" || type == "AvgPool3D")
1526
        {
1527
            CV_CheckGT(num_inputs, 0, "");
1528
            layerParams.set("pool", "ave");
1529
            layerParams.set("ave_pool_padded_area", false);
1530 1531 1532 1533 1534 1535 1536
            setKSize(layerParams, layer);
            setStrides(layerParams, layer);
            setPadding(layerParams, layer);

            int id = dstNet.addLayer(name, "Pooling", layerParams);
            layer_id[name] = id;

1537
            connectToAllBlobs(layer_id, dstNet, parsePin(layer.input(0)), id, num_inputs);
1538
        }
G
gal0is 已提交
1539 1540
        else if (type == "MaxPoolGrad")
        {
1541
            CV_CheckEQ(num_inputs, 3, "");
G
gal0is 已提交
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556

            layerParams.set("pool_k_h", 0);
            layerParams.set("pool_k_w", 0);
            layerParams.set("pool_stride_h", 0);
            layerParams.set("pool_stride_w", 0);
            layerParams.set("pool_pad_h", 0);
            layerParams.set("pool_pad_w", 0);

            int id = dstNet.addLayer(name, "MaxUnpool", layerParams);
            layer_id[name] = id;

            connect(layer_id, dstNet, parsePin(layer.input(2)), id, 0);
            connect(layer_id, dstNet, parsePin(layer.input(1) + ":1"), id, 1);
            connect(layer_id, dstNet, parsePin(layer.input(0)), id, 2);
        }
1557 1558
        else if (type == "Placeholder")
        {
1559 1560 1561 1562 1563 1564
            if (!hasLayerAttr(layer, "dtype") ||
                getLayerAttr(layer, "dtype").type() != tensorflow::DT_BOOL)  // If input is not a train/test flag.
            {
                netInputsNames.push_back(name);
                layer_id[name] = 0;
            }
1565
            tensorflow::TensorShapeProto shape;
1566
            if (hasLayerAttr(layer, "shape"))
1567 1568 1569 1570 1571 1572 1573 1574
                shape = getLayerAttr(layer, "shape").shape();
            else if (hasLayerAttr(layer, "_output_shapes"))
            {
                tensorflow::AttrValue_ListValue list = getLayerAttr(layer, "_output_shapes").list();
                if (list.shape_size())
                    shape = list.shape()[0];
            }
            if (shape.dim_size())
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593
            {
                MatShape dims(shape.dim_size());
                for (int i = 0; i < dims.size(); ++i)
                    dims[i] = shape.dim(i).size();
                if (dims.size() == 4 && predictedLayout == DATA_LAYOUT_NHWC)
                {
                    std::swap(dims[1], dims[3]);  // NHWC->NCWH
                    std::swap(dims[2], dims[3]);  // NCWH->NCHW
                    if (dims[0] == -1)  // It's OK to have undetermined batch size
                        dims[0] = 1;
                }
                bool hasNeg = false;
                for (int i = 0; i < dims.size() && !hasNeg; ++i)
                {
                    hasNeg = dims[i] < 0;
                }
                if (!hasNeg)
                    netInputShapes.push_back(dims);
            }
1594 1595
        }
        else if (type == "Split") {
L
luz.paz 已提交
1596
            // TODO: determining axis index remapping by input dimensions order of input blob
1597
            // TODO: slicing input may be Const op
L
luz.paz 已提交
1598
            // TODO: slicing kernels for convolutions - in current implementation it is impossible
1599
            // TODO: add parsing num of slices parameter
1600
            CV_CheckEQ(num_inputs, 2, "");
1601 1602 1603
            // num_split
            // 1st blob is dims tensor
            int axis = getConstBlob(layer, value_id, 0).int_val().Get(0);
1604 1605 1606
            if (getDataLayout(name, data_layouts) == DATA_LAYOUT_NHWC)
                axis = toNCHW(axis);
            layerParams.set("axis", axis);
1607

L
Liubov Batanina 已提交
1608 1609 1610
            if (hasLayerAttr(layer, "num_split"))
                layerParams.set("num_split", getLayerAttr(layer, "num_split").i());

1611 1612 1613 1614 1615 1616
            int id = dstNet.addLayer(name, "Slice", layerParams);
            layer_id[name] = id;

            // one input only
            connect(layer_id, dstNet, parsePin(layer.input(1)), id, 0);
        }
1617 1618 1619 1620 1621 1622
        else if (type == "Slice")
        {
            // op: "Slice"
            // input: "input_node"
            // input: "Slice/begin"
            // input: "Slice/size"
1623
            CV_CheckEQ(num_inputs, 3, "");
D
Dmitry Kurtaev 已提交
1624 1625
            Mat begins = getTensorContent(getConstBlob(layer, value_id, 1));
            Mat sizes = getTensorContent(getConstBlob(layer, value_id, 2));
1626 1627 1628
            CV_Assert_N(!begins.empty(), !sizes.empty());
            CV_CheckTypeEQ(begins.type(), CV_32SC1, "");
            CV_CheckTypeEQ(sizes.type(), CV_32SC1, "");
1629

D
Dmitry Kurtaev 已提交
1630
            if (begins.total() == 4 && getDataLayout(name, data_layouts) == DATA_LAYOUT_NHWC)
D
Dmitry Kurtaev 已提交
1631
            {
1632
                // Swap NHWC parameters' order to NCHW.
D
Dmitry Kurtaev 已提交
1633 1634 1635 1636 1637 1638 1639
                std::swap(*begins.ptr<int32_t>(0, 2), *begins.ptr<int32_t>(0, 3));
                std::swap(*begins.ptr<int32_t>(0, 1), *begins.ptr<int32_t>(0, 2));
                std::swap(*sizes.ptr<int32_t>(0, 2), *sizes.ptr<int32_t>(0, 3));
                std::swap(*sizes.ptr<int32_t>(0, 1), *sizes.ptr<int32_t>(0, 2));
            }
            layerParams.set("begin", DictValue::arrayInt((int*)begins.data, begins.total()));
            layerParams.set("size", DictValue::arrayInt((int*)sizes.data, sizes.total()));
1640 1641 1642

            int id = dstNet.addLayer(name, "Slice", layerParams);
            layer_id[name] = id;
D
Dmitry Kurtaev 已提交
1643 1644 1645 1646 1647

            connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
        }
        else if (type == "StridedSlice")
        {
1648
            CV_CheckEQ(num_inputs, 4, "");
D
Dmitry Kurtaev 已提交
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
            Mat begins = getTensorContent(getConstBlob(layer, value_id, 1));
            Mat ends = getTensorContent(getConstBlob(layer, value_id, 2));
            Mat strides = getTensorContent(getConstBlob(layer, value_id, 3));
            CV_CheckTypeEQ(begins.type(), CV_32SC1, "");
            CV_CheckTypeEQ(ends.type(), CV_32SC1, "");
            CV_CheckTypeEQ(strides.type(), CV_32SC1, "");
            const int num = begins.total();
            CV_Assert_N(num == ends.total(), num == strides.total());

            int end_mask = getLayerAttr(layer, "end_mask").i();
            for (int i = 0; i < num; ++i)
            {
1661 1662
                if (ends.at<int>(i) < 0)
                    ends.at<int>(i) -= 1;
D
Dmitry Kurtaev 已提交
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
                if (end_mask & (1 << i))
                    ends.at<int>(i) = -1;
                if (strides.at<int>(i) != 1)
                    CV_Error(Error::StsNotImplemented,
                             format("StridedSlice with stride %d", strides.at<int>(i)));
            }
            if (begins.total() == 4 && getDataLayout(name, data_layouts) == DATA_LAYOUT_NHWC)
            {
                // Swap NHWC parameters' order to NCHW.
                std::swap(begins.at<int>(2), begins.at<int>(3));
                std::swap(begins.at<int>(1), begins.at<int>(2));
                std::swap(ends.at<int>(2), ends.at<int>(3));
                std::swap(ends.at<int>(1), ends.at<int>(2));
            }
            layerParams.set("begin", DictValue::arrayInt((int*)begins.data, begins.total()));
            layerParams.set("end", DictValue::arrayInt((int*)ends.data, ends.total()));

            int id = dstNet.addLayer(name, "Slice", layerParams);
            layer_id[name] = id;
1682 1683 1684

            connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
        }
D
Dmitry Kurtaev 已提交
1685
        else if (type == "Mul" || type == "RealDiv")
D
dkurt 已提交
1686
        {
1687
            CV_CheckGT(num_inputs, 0, "");
D
Dmitry Kurtaev 已提交
1688
            int constId = -1;
1689
            for(int ii = 0; ii < num_inputs; ++ii)
D
dkurt 已提交
1690 1691
            {
                Pin input = parsePin(layer.input(ii));
D
Dmitry Kurtaev 已提交
1692 1693 1694 1695 1696
                if (value_id.find(input.name) != value_id.end())
                {
                    constId = ii;
                    break;
                }
D
dkurt 已提交
1697
            }
1698
            CV_Assert((constId != -1) || (num_inputs == 2));
D
dkurt 已提交
1699

D
Dmitry Kurtaev 已提交
1700
            if (constId != -1)
D
dkurt 已提交
1701 1702
            {
                // Multiplication by constant.
1703
                CV_CheckEQ(num_inputs, 2, "");
1704 1705
                Mat scaleMat = getTensorContent(getConstBlob(layer, value_id));
                CV_Assert(scaleMat.type() == CV_32FC1);
D
Dmitry Kurtaev 已提交
1706 1707 1708 1709 1710 1711
                if (type == "RealDiv")
                {
                    if (constId == 0)
                        CV_Error(Error::StsNotImplemented, "Division of constant over variable");
                    scaleMat = 1.0f / scaleMat;
                }
D
dkurt 已提交
1712

1713 1714
                int id;
                if (scaleMat.total() == 1)  // is a scalar.
1715
                {
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
                    // Try to match with a LeakyRelu:
                    // node {
                    //   name: "LeakyRelu/mul"
                    //   op: "Mul"
                    //   input: "LeakyRelu/alpha"
                    //   input: "input"
                    // }
                    // node {
                    //   name: "LeakyRelu/Maximum"
                    //   op: "Maximum"
                    //   input: "LeakyRelu/mul"
                    //   input: "input"
                    // }
                    StrIntVector next_layers = getNextLayers(net, name, "Maximum");
                    if (!next_layers.empty())
                    {
                        int maximumLayerIdx = next_layers[0].second;
1733 1734 1735 1736 1737 1738 1739

                        CV_Assert(net.node(maximumLayerIdx).input_size() == 2);

                        // The input from the Mul layer can also be at index 1.
                        int mulInputIdx = (net.node(maximumLayerIdx).input(0) == name) ? 0 : 1;

                        ExcludeLayer(net, maximumLayerIdx, mulInputIdx, false);
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750
                        layers_to_ignore.insert(next_layers[0].first);

                        layerParams.set("negative_slope", scaleMat.at<float>(0));
                        id = dstNet.addLayer(name, "ReLU", layerParams);
                    }
                    else
                    {
                        // Just a multiplication.
                        layerParams.set("scale", scaleMat.at<float>(0));
                        id = dstNet.addLayer(name, "Power", layerParams);
                    }
1751 1752 1753 1754
                }
                else  // is a vector
                {
                    layerParams.blobs.resize(1, scaleMat);
1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767

                   StrIntVector next_layers = getNextLayers(net, name, "Add");
                   if (!next_layers.empty())
                   {
                       layerParams.set("bias_term", true);
                       layerParams.blobs.resize(2);

                       int weights_layer_index = next_layers[0].second;
                       blobFromTensor(getConstBlob(net.node(weights_layer_index), value_id), layerParams.blobs.back());
                       ExcludeLayer(net, weights_layer_index, 0, false);
                       layers_to_ignore.insert(next_layers[0].first);
                   }

1768 1769 1770
                    if (hasLayerAttr(layer, "axis"))
                        layerParams.set("axis", getLayerAttr(layer, "axis").i());

1771
                    id = dstNet.addLayer(name, "Scale", layerParams);
1772
                }
D
dkurt 已提交
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
                layer_id[name] = id;

                Pin inp0 = parsePin(layer.input(0));
                if (layer_id.find(inp0.name) != layer_id.end())
                    // First operand is a constant.
                    connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
                else
                    connect(layer_id, dstNet, parsePin(layer.input(1)), id, 0);
            }
            else
            {
1784 1785 1786
                // Check if all the inputs have the same shape.
                bool equalInpShapes = true;
                MatShape outShape0;
1787
                for (int ii = 0; ii < num_inputs && !netInputShapes.empty(); ii++)
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812
                {
                    Pin pin = parsePin(layer.input(ii));
                    int inpId = layer_id.find(pin.name)->second;

                    // Get input shape
                    MatShape outShape;
                    std::vector<MatShape> inpShapes, outShapes;
                    dstNet.getLayerShapes(netInputShapes, inpId, inpShapes, outShapes);
                    CV_CheckGT(static_cast<int>(outShapes.size()), pin.blobIndex, "");
                    outShape = outShapes[pin.blobIndex];

                    if (ii == 0)
                    {
                        outShape0 = outShape;
                    }
                    else if (outShape != outShape0)
                    {
                        equalInpShapes = false;
                        break;
                    }
                }

                int id;
                if (equalInpShapes || netInputShapes.empty())
                {
D
Dmitry Kurtaev 已提交
1813
                    layerParams.set("operation", type == "RealDiv" ? "div" : "prod");
1814 1815 1816
                    id = dstNet.addLayer(name, "Eltwise", layerParams);
                }
                else
D
Dmitry Kurtaev 已提交
1817 1818 1819
                {
                    if (type == "RealDiv")
                        CV_Error(Error::StsNotImplemented, "Division of non equal tensors");
1820
                    id = dstNet.addLayer(name, "Scale", layerParams);
D
Dmitry Kurtaev 已提交
1821
                }
1822

D
dkurt 已提交
1823 1824
                layer_id[name] = id;

1825
                for (int ii = 0; ii < num_inputs; ii++)
D
dkurt 已提交
1826 1827 1828 1829
                {
                    Pin inp = parsePin(layer.input(ii));
                    if (layer_id.find(inp.name) == layer_id.end())
                        CV_Error(Error::StsError, "Input layer not found: " + inp.name);
1830
                    connect(layer_id, dstNet, inp, id, ii);
D
dkurt 已提交
1831 1832 1833
                }
            }
        }
1834
        else if (type == "FusedBatchNorm" || type == "FusedBatchNormV3")
D
dkurt 已提交
1835 1836 1837 1838 1839 1840 1841
        {
            // op: "FusedBatchNorm"
            // input: "input"
            // input: "BatchNorm/gamma"
            // input: "BatchNorm/beta"
            // input: "BatchNorm/moving_mean"
            // input: "BatchNorm/moving_variance"
1842
            CV_CheckEQ(num_inputs, 5, "Expected gamma, beta, mean and std");
1843 1844 1845
            Pin inpId = parsePin(layer.input(0));

            bool isTraining = hasLayerAttr(layer, "is_training") && getLayerAttr(layer, "is_training").b();
D
dkurt 已提交
1846

1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869
            layerParams.blobs.resize(2);

            const tensorflow::TensorProto& gammaTensor = getConstBlob(layer, value_id, 1);
            if (!gammaTensor.tensor_content().empty())
            {
                layerParams.blobs.resize(layerParams.blobs.size() + 1);
                layerParams.set("has_weight", true);
                blobFromTensor(gammaTensor, layerParams.blobs.back());
            }
            else
                layerParams.set("has_weight", false);

            const tensorflow::TensorProto& betaTensor = getConstBlob(layer, value_id, 2);
            if (!betaTensor.tensor_content().empty())
            {
                layerParams.blobs.resize(layerParams.blobs.size() + 1);
                layerParams.set("has_bias", true);
                blobFromTensor(betaTensor, layerParams.blobs.back());
            }
            else
                layerParams.set("has_bias", false);

            Mat mean, std;
1870 1871
            if (isTraining)
            {
1872 1873 1874
                if (layerParams.blobs.size() == 2)
                    CV_Error(Error::StsNotImplemented, "Cannot determine number "
                             "of parameters for batch normalization layer.");
1875 1876
                mean = Mat::zeros(1, layerParams.blobs[2].total(), CV_32F);
                std = Mat::ones(1, layerParams.blobs[2].total(), CV_32F);
1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893

                // Add an extra layer: Mean-Variance normalization
                LayerParams mvnParams;
                std::string mvnName = name + "/MVN";
                CV_Assert(layer_id.find(mvnName) == layer_id.end());
                int mvnId = dstNet.addLayer(mvnName, "MVN", mvnParams);
                layer_id[mvnName] = mvnId;
                connect(layer_id, dstNet, inpId, mvnId, 0);
                inpId = Pin(mvnName);
            }
            else
            {
                blobFromTensor(getConstBlob(layer, value_id, 3), mean);
                blobFromTensor(getConstBlob(layer, value_id, 4), std);
            }
            layerParams.blobs[0] = mean;
            layerParams.blobs[1] = std;
D
dkurt 已提交
1894 1895 1896 1897 1898 1899 1900 1901

            if (hasLayerAttr(layer, "epsilon"))
                layerParams.set("eps", getLayerAttr(layer, "epsilon").f());

            int id = dstNet.addLayer(name, "BatchNorm", layerParams);
            layer_id[name] = id;

            // one input only
1902
            connect(layer_id, dstNet, inpId, id, 0);
D
dkurt 已提交
1903
        }
1904 1905 1906 1907 1908 1909
        else if (type == "Conv2DBackpropInput")
        {
            // op: "Conv2DBackpropInput"
            // input: "conv2d_transpose/output_shape"
            // input: "weights"
            // input: "input"
1910
            CV_CheckEQ(num_inputs, 3, "Expected output shape, weights and input nodes");
1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924

            layerParams.set("bias_term", false);
            layerParams.blobs.resize(1);

            StrIntVector next_layers = getNextLayers(net, name, "BiasAdd");
            if (next_layers.size() == 1)
            {
                layerParams.set("bias_term", true);
                layerParams.blobs.resize(2);

                int weights_layer_index = next_layers[0].second;

                blobFromTensor(getConstBlob(net.node(weights_layer_index), value_id), layerParams.blobs[1]);
                ExcludeLayer(net, weights_layer_index, 0, false);
1925
                layers_to_ignore.insert(next_layers[0].first);
1926 1927 1928 1929 1930
            }

            kernelFromTensor(getConstBlob(layer, value_id, 1), layerParams.blobs[0]);

            const int* kshape = layerParams.blobs[0].size.p;
1931 1932 1933 1934
            const int kernelH = kshape[2];
            const int kernelW = kshape[3];
            layerParams.set("kernel_h", kernelH);
            layerParams.set("kernel_w", kernelW);
1935
            layerParams.set("num_output", kshape[1]);
1936 1937 1938 1939

            setStrides(layerParams, layer);
            setPadding(layerParams, layer);

1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
            // For convolution layer, output shape computes as
            // o = 1 + (i - k + 2*p) / s
            // i - input size, o - output size, k - kernel size, p - pad, s - stride
            // In TensorFlow, p == 0 is padMode == 'VALID' or p == (k - 1) / 2
            // considering that k is odd.
            // SAME:  o = 1 + (i - 1) / s
            // VALID: o = 1 + i / s
            // Deconvolution's layer output shape computes as
            // SAME:  o = 1 + (i - 1)*s
            // VALID: o = (i - 1)*s
            // If output_shape differs from formulas above then adjust padding is applied.

            const int strideY = layerParams.get<int>("stride_h");
            const int strideX = layerParams.get<int>("stride_w");
            Mat outShape = getTensorContent(getConstBlob(layer, value_id, 0));
1955 1956
            const int outH = outShape.at<int>(1);
            const int outW = outShape.at<int>(2);
1957 1958 1959 1960 1961 1962 1963 1964 1965 1966
            if (layerParams.get<String>("pad_mode") == "SAME")
            {
                layerParams.set("adj_w", (outW - 1) % strideX);
                layerParams.set("adj_h", (outH - 1) % strideY);
            }
            else if (layerParams.get<String>("pad_mode") == "VALID")
            {
                layerParams.set("adj_w", (outW - kernelW) % strideX);
                layerParams.set("adj_h", (outH - kernelH) % strideY);
            }
1967 1968 1969 1970 1971 1972
            int id = dstNet.addLayer(name, "Deconvolution", layerParams);
            layer_id[name] = id;

            // one input only
            connect(layer_id, dstNet, parsePin(layer.input(2)), id, 0);
        }
1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
        else if (type == "BlockLSTM")
        {
            // op: "BlockLSTM"
            // input: "lstm_block_wrapper/ToInt64/x"  (ignore, number of time stamps)
            // input: "input"
            // input: "lstm_block_wrapper/zeros"      (ignore)
            // input: "lstm_block_wrapper/zeros"      (ignore)
            // input: "lstm_block_wrapper/kernel"
            // input: "lstm_block_wrapper/w_i_diag"
            // input: "lstm_block_wrapper/w_f_diag"
            // input: "lstm_block_wrapper/w_o_diag"
            // input: "lstm_block_wrapper/bias"
1985
            CV_CheckEQ(num_inputs, 9, "Unexpected number of input nodes");
1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046

            if (hasLayerAttr(layer, "forget_bias"))
                layerParams.set("forget_bias", getLayerAttr(layer, "forget_bias").f());

            if (hasLayerAttr(layer, "forget_bias"))
            {
                float cellClip = getLayerAttr(layer, "cell_clip").f();
                // Cell clip disabled if it's negative.
                if (cellClip >= 0)
                {
                    layerParams.set("use_cell_clip", true);
                    layerParams.set("cell_clip", cellClip);
                }
            }

            Mat W, Wh, Wx, b;
            blobFromTensor(getConstBlob(layer, value_id, 4), W);
            blobFromTensor(getConstBlob(layer, value_id, 8), b);
            const int outSize = W.cols / 4;

            // IGFO->IFOG
            float* weightData = (float*)W.data;
            for (int i = 0; i < W.rows; ++i)
                for (int j = 0; j < outSize; ++j)
                {
                    std::swap(weightData[i * W.cols + 1 * outSize + j],
                              weightData[i * W.cols + 2 * outSize + j]);
                    std::swap(weightData[i * W.cols + 2 * outSize + j],
                              weightData[i * W.cols + 3 * outSize + j]);
                }
            Wx = W.rowRange(0, W.rows - outSize).t();
            Wh = W.rowRange(W.rows - outSize, W.rows).t();

            layerParams.blobs.resize(3);
            layerParams.blobs[0] = Wh;
            layerParams.blobs[1] = Wx;
            layerParams.blobs[2] = b;

            if (hasLayerAttr(layer, "use_peephole"))
            {
                bool usePeephole = getLayerAttr(layer, "use_peephole").b();
                if (usePeephole)
                {
                    layerParams.set("use_peephole", true);
                    layerParams.blobs.resize(6);
                    for (int i = 0; i < 3; ++i)
                    {
                        Mat w;
                        blobFromTensor(getConstBlob(layer, value_id, 5 + i), w);
                        w = w.reshape(1, w.total());  // Single column.
                        w = Mat::diag(w);  // Make a diagonal matrix.
                        layerParams.blobs[3 + i] = w;
                    }
                }
            }

            int id = dstNet.addLayer(name, "LSTM", layerParams);
            layer_id[name] = id;

            // one input only
            connect(layer_id, dstNet, parsePin(layer.input(1)), id, 0);
2047
            data_layouts[name] = DATA_LAYOUT_UNKNOWN;
2048
        }
2049
        else if (type == "ResizeNearestNeighbor" || type == "ResizeBilinear" || type == "FusedResizeAndPadConv2D")
D
Dmitry Kurtaev 已提交
2050
        {
2051
            CV_CheckGT(num_inputs, 0, "");
2052 2053 2054 2055 2056 2057 2058
            std::string convWeights = "";
            if (type == "FusedResizeAndPadConv2D")
            {
                // input: "mul_1"
                // input: "decoder/ResizeBilinear/size"
                // input: "decoder/decoder_conv0/Conv2D_dummy_paddings"
                // input: "decoder/decoder_conv0/weights"
2059
                CV_CheckEQ(num_inputs, 4, "Number of input for FusedResizeAndPadConv2D");
2060 2061 2062 2063 2064

                Mat paddings = getTensorContent(getConstBlob(layer, value_id, 2));
                CV_CheckEQ(countNonZero(paddings), 0, "Unsupported mode");

                convWeights = layer.input(3);
2065 2066
                layer.mutable_input()->DeleteSubrange(2, 2);  // FIXIT do NOT modify input model
                num_inputs = layer.input_size();
2067 2068 2069 2070
                name = name + "/resize";

                if (hasLayerAttr(layer, "resize_align_corners"))
                {
2071
                    // FIXIT do NOT modify input model
2072 2073 2074 2075 2076
                    layer.mutable_attr()->insert(
                        ::google::protobuf::MapPair<std::string, tensorflow::AttrValue>("align_corners",
                                                                                        getLayerAttr(layer, "resize_align_corners")));
                }
            }
2077
            if (num_inputs == 2)
D
David 已提交
2078 2079
            {
                Mat outSize = getTensorContent(getConstBlob(layer, value_id, 1));
2080
                CV_CheckTypeEQ(outSize.type(), CV_32SC1, ""); CV_CheckEQ(outSize.total(), (size_t)2, "");
D
David 已提交
2081 2082 2083
                layerParams.set("height", outSize.at<int>(0, 0));
                layerParams.set("width", outSize.at<int>(0, 1));
            }
2084
            else if (num_inputs == 3)
D
David 已提交
2085 2086 2087
            {
                Mat factorHeight = getTensorContent(getConstBlob(layer, value_id, 1));
                Mat factorWidth = getTensorContent(getConstBlob(layer, value_id, 2));
2088 2089 2090 2091
                factorHeight.convertTo(factorHeight, CV_32F);
                factorWidth.convertTo(factorWidth, CV_32F);
                layerParams.set("zoom_factor_x", factorWidth.at<float>(0));
                layerParams.set("zoom_factor_y", factorHeight.at<float>(0));
D
David 已提交
2092 2093
            }
            else
2094
                CV_Check(num_inputs, num_inputs == 2 || num_inputs == 3, "");
D
Dmitry Kurtaev 已提交
2095

D
David 已提交
2096 2097 2098 2099
            if (type == "ResizeNearestNeighbor")
                layerParams.set("interpolation", "nearest");
            else
                layerParams.set("interpolation", "bilinear");
D
Dmitry Kurtaev 已提交
2100 2101 2102 2103

            if (hasLayerAttr(layer, "align_corners"))
                layerParams.set("align_corners", getLayerAttr(layer, "align_corners").b());

2104 2105 2106
            if (hasLayerAttr(layer, "half_pixel_centers"))
                layerParams.set("half_pixel_centers", getLayerAttr(layer, "half_pixel_centers").b());

D
David 已提交
2107
            int id = dstNet.addLayer(name, "Resize", layerParams);
D
Dmitry Kurtaev 已提交
2108 2109 2110
            layer_id[name] = id;

            connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
2111 2112 2113 2114

            // Step back to add convolution
            if (type == "FusedResizeAndPadConv2D")
            {
2115 2116 2117 2118 2119 2120
                tensorflow::NodeDef conv = layer_;
                conv.clear_input();
                conv.add_input(name);
                conv.add_input(convWeights);
                conv.set_op("Conv2D");
                parseNode(conv);
2121
            }
D
Dmitry Kurtaev 已提交
2122
        }
2123 2124 2125 2126
        else if (type == "L2Normalize")
        {
            // op: "L2Normalize"
            // input: "input"
D
Dmitry Kurtaev 已提交
2127
            // input: "reduction_indices" (axis)
2128
            CV_CheckEQ(num_inputs, 2, "");
D
Dmitry Kurtaev 已提交
2129 2130 2131 2132
            Mat reductionIndices = getTensorContent(getConstBlob(layer, value_id, 1));
            CV_Assert(reductionIndices.type() == CV_32SC1);

            const int numAxes = reductionIndices.total();
D
Dmitry Kurtaev 已提交
2133
            if (getDataLayout(name, data_layouts) == DATA_LAYOUT_NHWC)
D
Dmitry Kurtaev 已提交
2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146
                for (int i = 0; i < numAxes; ++i)
                    reductionIndices.at<int>(i) = toNCHW(reductionIndices.at<int>(i));

            cv::sort(reductionIndices, reductionIndices, SORT_ASCENDING);
            for (int i = 1; i < numAxes; ++i)
            {
                CV_Assert(reductionIndices.at<int>(i) == reductionIndices.at<int>(i - 1) + 1);
                // Axes have the same sign.
                CV_Assert(reductionIndices.at<int>(i) * reductionIndices.at<int>(i - 1) >= 0);
            }
            layerParams.set("start_axis", reductionIndices.at<int>(0));
            layerParams.set("end_axis", reductionIndices.at<int>(numAxes - 1));

2147 2148 2149 2150
            int id = dstNet.addLayer(name, "Normalize", layerParams);
            layer_id[name] = id;
            connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
        }
2151 2152
        else if (type == "PriorBox")
        {
2153
            CV_CheckEQ(num_inputs, 2, "");
2154 2155 2156 2157 2158 2159 2160 2161 2162 2163
            if (hasLayerAttr(layer, "min_size"))
                layerParams.set("min_size", getLayerAttr(layer, "min_size").i());
            if (hasLayerAttr(layer, "max_size"))
                layerParams.set("max_size", getLayerAttr(layer, "max_size").i());
            if (hasLayerAttr(layer, "flip"))
                layerParams.set("flip", getLayerAttr(layer, "flip").b());
            if (hasLayerAttr(layer, "clip"))
                layerParams.set("clip", getLayerAttr(layer, "clip").b());
            if (hasLayerAttr(layer, "offset"))
                layerParams.set("offset", getLayerAttr(layer, "offset").f());
2164 2165
            if (hasLayerAttr(layer, "step"))
                layerParams.set("step", getLayerAttr(layer, "step").f());
2166 2167 2168 2169

            const std::string paramNames[] = {"variance", "aspect_ratio", "scales",
                                              "width", "height"};
            for (int i = 0; i < 5; ++i)
2170
            {
2171 2172 2173 2174 2175 2176
                if (hasLayerAttr(layer, paramNames[i]))
                {
                    Mat values = getTensorContent(getLayerAttr(layer, paramNames[i]).tensor());
                    layerParams.set(paramNames[i],
                                    DictValue::arrayReal<float*>((float*)values.data, values.total()));
                }
2177 2178 2179 2180 2181
            }
            int id = dstNet.addLayer(name, "PriorBox", layerParams);
            layer_id[name] = id;
            connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
            connect(layer_id, dstNet, parsePin(layer.input(1)), id, 1);
2182
            data_layouts[name] = DATA_LAYOUT_UNKNOWN;
2183
        }
2184 2185
        else if (type == "Softmax")
        {
2186
            CV_CheckGT(num_inputs, 0, "");
2187 2188 2189 2190 2191
            if (hasLayerAttr(layer, "axis"))
                layerParams.set("axis", getLayerAttr(layer, "axis").i());

            int id = dstNet.addLayer(name, "Softmax", layerParams);
            layer_id[name] = id;
2192
            connectToAllBlobs(layer_id, dstNet, parsePin(layer.input(0)), id, num_inputs);
2193
        }
2194 2195 2196 2197 2198 2199
        else if (type == "CropAndResize")
        {
            // op: "CropAndResize"
            // input: "input"
            // input: "boxes"
            // input: "sizes"
2200
            CV_CheckEQ(num_inputs, 3, "");
2201 2202

            Mat cropSize = getTensorContent(getConstBlob(layer, value_id, 2));
2203
            CV_CheckTypeEQ(cropSize.type(), CV_32SC1, ""); CV_CheckEQ(cropSize.total(), (size_t)2, "");
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213

            layerParams.set("height", cropSize.at<int>(0));
            layerParams.set("width", cropSize.at<int>(1));

            int id = dstNet.addLayer(name, "CropAndResize", layerParams);
            layer_id[name] = id;

            connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
            connect(layer_id, dstNet, parsePin(layer.input(1)), id, 1);
        }
2214
        else if (type == "Mean" || type == "Sum")
D
Dmitry Kurtaev 已提交
2215
        {
L
Liubov Batanina 已提交
2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227
            // Computes the mean of elements across dimensions of a tensor.
            // If keepdims is false (default) reduces input_tensor along the dimensions given in axis,
            // else the reduced dimensions are retained with length 1.
            // if indices = [1, 2] in NHWC layout we use global pooling: NxCxHxW --Pooling--> NxCx1x1
            // if keepdims is false we use Flatten after Pooling: out_shape = NxC
            // if indices = [0] we use a global pooling by indices.
            // To return correct shape, we use Reshape after Pooling. To determine input shape use Slice for input,
            // if keepdims is false we use Flatten after Slice.
            // Example: input_shape = NxCxHxW
            // determine out shape: NxCxHxW --Slice--> 1xCxHxW
            //                      out_shape = 1xCxHxW if keepDims else (1xCxHxW --Flatten--> CxHxW)
            // global pool: NxCxHxW --Flatten--> Nx(C*H*W) --Reshape--> 1x1xNx(C*H*W) --Pooling--> 1x1x1x(C*H*W) --Reshape--> out_shape
2228
            CV_CheckGT(num_inputs, 0, "");
L
Liubov Batanina 已提交
2229

D
Dmitry Kurtaev 已提交
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239
            Mat indices = getTensorContent(getConstBlob(layer, value_id, 1));
            CV_Assert(indices.type() == CV_32SC1);

            // There are two attributes, "keepdims" and a deprecated "keep_dims".
            bool keepDims = false;
            if (hasLayerAttr(layer, "keepdims"))
                keepDims = getLayerAttr(layer, "keepdims").b();
            else if (hasLayerAttr(layer, "keep_dims"))
                keepDims = getLayerAttr(layer, "keep_dims").b();

L
Liubov Batanina 已提交
2240
            if (indices.total() == 1 && indices.at<int>(0) == 0)
D
Dmitry Kurtaev 已提交
2241 2242 2243 2244 2245 2246
            {
                LayerParams flattenLp;
                std::string flattenName = name + "/flatten";
                CV_Assert(layer_id.find(flattenName) == layer_id.end());
                int flattenId = dstNet.addLayer(flattenName, "Flatten", flattenLp);
                layer_id[flattenName] = flattenId;
L
Liubov Batanina 已提交
2247 2248 2249 2250 2251
                connect(layer_id, dstNet, parsePin(layer.input(0)), flattenId, 0);

                LayerParams reshapeLp;
                std::string reshapeName = name + "/reshape";
                CV_Assert(layer_id.find(reshapeName) == layer_id.end());
L
Liubov Batanina 已提交
2252
                reshapeLp.set("axis", 0);
L
Liubov Batanina 已提交
2253
                reshapeLp.set("num_axes", 1);
L
Liubov Batanina 已提交
2254 2255
                int newShape[] = {1, 1, -1};
                reshapeLp.set("dim", DictValue::arrayInt(&newShape[0], 3));
L
Liubov Batanina 已提交
2256 2257 2258 2259 2260 2261 2262 2263

                int reshapeId = dstNet.addLayer(reshapeName, "Reshape", reshapeLp);
                layer_id[reshapeName] = reshapeId;
                connect(layer_id, dstNet, Pin(flattenName), reshapeId, 0);

                LayerParams avgLp;
                std::string avgName = name + "/avg";
                CV_Assert(layer_id.find(avgName) == layer_id.end());
2264
                avgLp.set("pool", type == "Mean" ? "ave" : "sum");
L
Liubov Batanina 已提交
2265
                // pooling kernel H x 1
L
Liubov Batanina 已提交
2266
                avgLp.set("global_pooling_h", true);
L
Liubov Batanina 已提交
2267
                avgLp.set("kernel_w", 1);
L
Liubov Batanina 已提交
2268 2269 2270 2271
                int avgId = dstNet.addLayer(avgName, "Pooling", avgLp);
                layer_id[avgName] = avgId;
                connect(layer_id, dstNet, Pin(reshapeName), avgId, 0);

L
Liubov Batanina 已提交
2272
                LayerParams sliceLp;
L
Liubov Batanina 已提交
2273 2274
                std::string layerShapeName = name + "/slice";
                CV_Assert(layer_id.find(layerShapeName) == layer_id.end());
L
Liubov Batanina 已提交
2275
                sliceLp.set("axis", 0);
L
Liubov Batanina 已提交
2276 2277 2278 2279
                int begin[] = {0};
                int size[] = {1};
                sliceLp.set("begin", DictValue::arrayInt(&begin[0], 1));
                sliceLp.set("size", DictValue::arrayInt(&size[0], 1));
L
Liubov Batanina 已提交
2280 2281
                int sliceId = dstNet.addLayer(layerShapeName, "Slice", sliceLp);
                layer_id[layerShapeName] = sliceId;
L
Liubov Batanina 已提交
2282 2283
                connect(layer_id, dstNet, Pin(layer.input(0)), sliceId, 0);

L
Liubov Batanina 已提交
2284 2285 2286 2287 2288
                if (!keepDims)
                {
                    LayerParams squeezeLp;
                    std::string squeezeName = name + "/squeeze";
                    CV_Assert(layer_id.find(squeezeName) == layer_id.end());
L
Liubov Batanina 已提交
2289 2290
                    squeezeLp.set("axis", 0);
                    squeezeLp.set("end_axis", 1);
L
Liubov Batanina 已提交
2291 2292 2293 2294 2295
                    int squeezeId = dstNet.addLayer(squeezeName, "Flatten", squeezeLp);
                    layer_id[squeezeName] = squeezeId;
                    connect(layer_id, dstNet, Pin(layerShapeName), squeezeId, 0);
                    layerShapeName = squeezeName;
                }
L
Liubov Batanina 已提交
2296

L
Liubov Batanina 已提交
2297 2298 2299
                int id = dstNet.addLayer(name, "Reshape", layerParams);
                layer_id[name] = id;
                connect(layer_id, dstNet, Pin(avgName), id, 0);
L
Liubov Batanina 已提交
2300
                connect(layer_id, dstNet, Pin(layerShapeName), id, 1);
2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333
            } else if (indices.total() == 1) {
                int axis = toNCHW(indices.at<int>(0));
                if (axis == 2 || axis == 3)
                {
                    layerParams.set("pool", type == "Mean" ? "ave" : "sum");
                    layerParams.set(axis == 2 ? "kernel_w" : "kernel_h", 1);
                    layerParams.set(axis == 2 ? "global_pooling_h" : "global_pooling_w", true);
                    int id = dstNet.addLayer(name, "Pooling", layerParams);
                    layer_id[name] = id;
                    connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);

                    if (!keepDims)
                    {
                        // To keep correct order after squeeze dims we first need to change layout from NCHW to NHWC
                        LayerParams permLP;
                        int order[] = {0, 2, 3, 1};  // From OpenCV's NCHW to NHWC.
                        permLP.set("order", DictValue::arrayInt<int*>(order, 4));
                        std::string permName = name + "/nchw";
                        CV_Assert(layer_id.find(permName) == layer_id.end());
                        int permId = dstNet.addLayer(permName, "Permute", permLP);
                        layer_id[permName] = permId;
                        connect(layer_id, dstNet, Pin(name), permId, 0);

                        LayerParams squeezeLp;
                        std::string squeezeName = name + "/squeeze";
                        CV_Assert(layer_id.find(squeezeName) == layer_id.end());
                        squeezeLp.set("axis", indices.at<int>(0));
                        squeezeLp.set("end_axis", indices.at<int>(0) + 1);
                        int squeezeId = dstNet.addLayer(squeezeName, "Flatten", squeezeLp);
                        layer_id[squeezeName] = squeezeId;
                        connect(layer_id, dstNet, Pin(permName), squeezeId, 0);
                    }
                }
L
Liubov Batanina 已提交
2334 2335
            } else {
                if (indices.total() != 2 || indices.at<int>(0) != 1 || indices.at<int>(1) != 2)
2336
                    CV_Error(Error::StsNotImplemented, "Unsupported mode of reduce_mean or reduce_sum operation.");
L
Liubov Batanina 已提交
2337

2338
                layerParams.set("pool", type == "Mean" ? "ave" : "sum");
L
Liubov Batanina 已提交
2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352
                layerParams.set("global_pooling", true);
                int id = dstNet.addLayer(name, "Pooling", layerParams);
                layer_id[name] = id;
                connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);

                if (!keepDims)
                {
                    LayerParams flattenLp;
                    std::string flattenName = name + "/flatten";
                    CV_Assert(layer_id.find(flattenName) == layer_id.end());
                    int flattenId = dstNet.addLayer(flattenName, "Flatten", flattenLp);
                    layer_id[flattenName] = flattenId;
                    connect(layer_id, dstNet, Pin(name), flattenId, 0);
                }
D
Dmitry Kurtaev 已提交
2353 2354
            }
        }
L
Liubov Batanina 已提交
2355 2356
        else if (type == "Pack")
        {
L
Liubov Batanina 已提交
2357 2358 2359 2360 2361 2362
            // op: tf.stack(list of tensors, axis=0)
            // Join a list of inputs along a new axis.
            // The "axis" specifies the index of the new axis in the dimensions of the output.
            // Example: given a list with "N" tensors of shape (C, H, W):
            // if axis == 0 then the output tensor will have the shape (N, C, H, W),
            // if axis == 1 then the output tensor will have the shape (C, N, H, W).
2363
            CV_CheckGT(num_inputs, 0, "");
L
Liubov Batanina 已提交
2364 2365 2366 2367 2368 2369 2370
            CV_Assert(hasLayerAttr(layer, "axis"));
            int dim = (int)getLayerAttr(layer, "axis").i();
            if (dim != 0)
                CV_Error(Error::StsNotImplemented, "Unsupported mode of pack operation.");

            CV_Assert(hasLayerAttr(layer, "N"));
            int num = (int)getLayerAttr(layer, "N").i();
2371
            CV_CheckEQ(num_inputs, num, "");
L
Liubov Batanina 已提交
2372
            std::string base_name = name + "/reshape_";
L
Liubov Batanina 已提交
2373
            std::vector<int> reshape_ids;
L
Liubov Batanina 已提交
2374
            for (int i = 0; i < num; i++) {
L
Liubov Batanina 已提交
2375 2376 2377
                std::ostringstream ss;
                ss << i;
                std::string reshape_name = base_name + ss.str();
L
Liubov Batanina 已提交
2378 2379 2380
                LayerParams reshapeLP;
                reshapeLP.set("axis", dim);
                reshapeLP.set("num_axes", 1);
L
Liubov Batanina 已提交
2381 2382
                int outShape[] = {1, -1};
                reshapeLP.set("dim", DictValue::arrayInt(&outShape[0], 2));
L
Liubov Batanina 已提交
2383 2384
                int id = dstNet.addLayer(reshape_name, "Reshape", reshapeLP);
                layer_id[reshape_name] = id;
L
Liubov Batanina 已提交
2385
                reshape_ids.push_back(id);
L
Liubov Batanina 已提交
2386 2387 2388 2389 2390 2391 2392
                connect(layer_id, dstNet, parsePin(layer.input(i)), id, 0);
            }

            layerParams.set("axis", dim);
            int id = dstNet.addLayer(name, "Concat", layerParams);
            layer_id[name] = id;

L
Liubov Batanina 已提交
2393
            for (int li = 0; li < num; li++)
L
Liubov Batanina 已提交
2394
                dstNet.connect(reshape_ids[li], 0, id, li);
L
Liubov Batanina 已提交
2395
        }
D
Dmitry Kurtaev 已提交
2396 2397 2398 2399 2400 2401
        else if (type == "ClipByValue")
        {
            // op: "ClipByValue"
            // input: "input"
            // input: "mix"
            // input: "max"
2402
            CV_CheckEQ(num_inputs, 3, "");
D
Dmitry Kurtaev 已提交
2403 2404 2405

            Mat minValue = getTensorContent(getConstBlob(layer, value_id, 1));
            Mat maxValue = getTensorContent(getConstBlob(layer, value_id, 2));
2406 2407
            CV_CheckEQ(minValue.total(), (size_t)1, ""); CV_CheckTypeEQ(minValue.type(), CV_32FC1, "");
            CV_CheckEQ(maxValue.total(), (size_t)1, ""); CV_CheckTypeEQ(maxValue.type(), CV_32FC1, "");
D
Dmitry Kurtaev 已提交
2408 2409 2410 2411 2412 2413 2414 2415 2416

            layerParams.set("min_value", minValue.at<float>(0));
            layerParams.set("max_value", maxValue.at<float>(0));

            int id = dstNet.addLayer(name, "ReLU6", layerParams);
            layer_id[name] = id;

            connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
        }
D
dkurt 已提交
2417
        else if (type == "Abs" || type == "Tanh" || type == "Sigmoid" ||
2418
                 type == "Relu" || type == "Elu" ||
2419
                 type == "Identity" || type == "Relu6")
D
dkurt 已提交
2420
        {
2421
            CV_CheckGT(num_inputs, 0, "");
D
dkurt 已提交
2422 2423 2424 2425
            std::string dnnType = type;
            if (type == "Abs") dnnType = "AbsVal";
            else if (type == "Tanh") dnnType = "TanH";
            else if (type == "Relu") dnnType = "ReLU";
2426
            else if (type == "Relu6") dnnType = "ReLU6";
D
dkurt 已提交
2427 2428 2429 2430
            else if (type == "Elu") dnnType = "ELU";

            int id = dstNet.addLayer(name, dnnType, layerParams);
            layer_id[name] = id;
2431
            connectToAllBlobs(layer_id, dstNet, parsePin(layer.input(0)), id, num_inputs);
D
dkurt 已提交
2432
        }
2433 2434
        else
        {
2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454
            // Importer does not know how to map this TensorFlow's operation onto OpenCV's layer.
            // However we create a layer with the same type and rely that user defined a custom layer.

            // All the attributes are added to LayerParams.
            google::protobuf::Map<std::string, tensorflow::AttrValue> attr = layer.attr();
            for (google::protobuf::Map<std::string, tensorflow::AttrValue>::const_iterator ai = attr.begin();
                 ai != attr.end(); ++ai)
            {
                if (ai->second.value_case() == tensorflow::AttrValue::kS)  // string
                    layerParams.set(ai->first, ai->second.s());
                if (ai->second.value_case() == tensorflow::AttrValue::kI)  // int64
                    layerParams.set(ai->first, ai->second.i());
                if (ai->second.value_case() == tensorflow::AttrValue::kF)  // float
                    layerParams.set(ai->first, ai->second.f());
                if (ai->second.value_case() == tensorflow::AttrValue::kB)  // bool
                    layerParams.set(ai->first, ai->second.b());
            }

            // All the Const input nodes are added to layer's blobs.
            std::vector<std::string> inputsNames;
2455
            for (int i = 0; i < num_inputs; ++i)
2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472
            {
                // Check if input is a Const node.
                if (value_id.find(layer.input(i)) != value_id.end())
                {
                    Mat blob = getTensorContent(getConstBlob(layer, value_id, i));
                    layerParams.blobs.push_back(blob);
                }
                else
                    inputsNames.push_back(layer.input(i));
            }
            int id = dstNet.addLayer(name, type, layerParams);
            layer_id[name] = id;

            for (int i = 0; i < inputsNames.size(); ++i)
            {
                connect(layer_id, dstNet, parsePin(inputsNames[i]), id, i);
            }
2473 2474
        }
    }
2475 2476 2477 2478 2479
    catch (const std::exception& e)
    {
        CV_LOG_ERROR(NULL, "DNN/TF: Can't parse layer for node='" << name << "'. Exception: " << e.what());
        throw;
    }
2480 2481 2482 2483 2484 2485
}

} // namespace

#endif //HAVE_PROTOBUF

2486
Net readNetFromTensorflow(const String &model, const String &config)
2487 2488
{
    Net net;
2489
    TFImporter importer(net, model.c_str(), config.c_str());
2490 2491
    return net;
}
2492

2493 2494 2495 2496
Net readNetFromTensorflow(const char* bufferModel, size_t lenModel,
                          const char* bufferConfig, size_t lenConfig)
{
    Net net;
2497
    TFImporter importer(net, bufferModel, lenModel, bufferConfig, lenConfig);
2498 2499 2500
    return net;
}

2501
Net readNetFromTensorflow(const std::vector<uchar>& bufferModel, const std::vector<uchar>& bufferConfig)
2502
{
2503 2504 2505 2506 2507
    const char* bufferModelPtr = reinterpret_cast<const char*>(&bufferModel[0]);
    const char* bufferConfigPtr = bufferConfig.empty() ? NULL :
                                  reinterpret_cast<const char*>(&bufferConfig[0]);
    return readNetFromTensorflow(bufferModelPtr, bufferModel.size(),
                                 bufferConfigPtr, bufferConfig.size());
2508 2509
}

2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538
void writeTextGraph(const String& _model, const String& output)
{
    String model = _model;
    const std::string modelExt = model.substr(model.rfind('.') + 1);
    if (modelExt != "pb")
        CV_Error(Error::StsNotImplemented, "Only TensorFlow models support export to text file");

    tensorflow::GraphDef net;
    ReadTFNetParamsFromBinaryFileOrDie(model.c_str(), &net);

    sortByExecutionOrder(net);

    RepeatedPtrField<tensorflow::NodeDef>::iterator it;
    for (it = net.mutable_node()->begin(); it != net.mutable_node()->end(); ++it)
    {
        if (it->op() == "Const")
        {
            it->mutable_attr()->at("value").mutable_tensor()->clear_tensor_content();
        }
    }

    std::string content;
    google::protobuf::TextFormat::PrintToString(net, &content);

    std::ofstream ofs(output.c_str());
    ofs << content;
    ofs.close();
}

2539 2540
CV__DNN_EXPERIMENTAL_NS_END
}} // namespace