tf_importer.cpp 119.0 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
#include <opencv2/core/utils/logger.defines.hpp>
15
#include <opencv2/dnn/shape_utils.hpp>
16 17 18 19
#undef CV_LOG_STRIP_LEVEL
#define CV_LOG_STRIP_LEVEL CV_LOG_LEVEL_DEBUG + 1
#include <opencv2/core/utils/logger.hpp>

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

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

namespace cv {
namespace dnn {
33
CV__DNN_INLINE_NS_BEGIN
34

35 36
extern bool DNN_DIAGNOSTICS_RUN;

37
#if HAVE_PROTOBUF
38 39 40 41 42 43 44 45 46 47 48

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 已提交
49 50 51 52 53 54 55
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;
}
56

L
Liubov Batanina 已提交
57 58 59 60 61 62 63 64
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;
}

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

75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
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();
96 97 98
        if (n)
        {
            shape.resize(n);
99

100 101 102 103
            for (i = 0; i < n; i++)
                shape[i] = (int)_shape.dim(i).size();
        }
        else
104
            shape.resize(1, 1);  // Scalar. // FIXIT: should be empty
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    }
    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);
127
    CV_Assert(dstBlob.isContinuous());
128

129
    Mat tensorContent = getTensorContent(tensor, /*no copy*/false);
130
    CV_Assert(tensorContent.isContinuous());
131
    int size = tensorContent.total();
132 133 134
    CV_Assert(size == (int)dstBlob.total());

    float *dstData = dstBlob.ptr<float>();
135
    const T *data = reinterpret_cast<const T*>(tensorContent.data);
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 161 162 163 164 165

    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:
166
        case tensorflow::DT_HALF:
167 168 169 170 171 172 173 174 175 176 177
            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;
    }
}

178
#if 0
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
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())
    {
205
    case tensorflow::DT_FLOAT:
206 207 208 209 210 211 212 213 214
        {
            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;
        }
215
    case tensorflow::DT_INT32:
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 253 254 255 256 257
        {
            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;
    }
}
258
#endif
259 260 261 262 263 264 265 266 267 268 269 270

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);
}

271
static DataLayout getDataLayout(const tensorflow::NodeDef& layer)
272 273 274 275 276 277 278 279
{
    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;
280 281
        else if (format == "NDHWC")
            return DATA_LAYOUT_NDHWC;
282 283 284 285 286 287
        else
            CV_Error(Error::StsParseError, "Unknown data_format value: " + format);
    }
    return DATA_LAYOUT_UNKNOWN;
}

D
Dmitry Kurtaev 已提交
288 289 290 291 292
static inline std::string getNodeName(const std::string& tensorName)
{
    return tensorName.substr(0, tensorName.rfind(':'));
}

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

303 304 305 306 307 308 309 310 311 312
static
bool hasAllOnes(const Mat &inputs, int startPos, int endPos)
{
    CV_CheckLE(inputs.dims, 2, "");
    CV_CheckGE(startPos, 0, "");
    CV_CheckLE(startPos, endPos, "");
    CV_CheckLT((size_t)endPos, inputs.total(), "");

    for (int i = startPos; i < endPos; i++)
    {
A
Anastasia Murzova 已提交
313
        if (inputs.at<int>(i) != 1 && inputs.at<int>(i) != -1)
314 315 316 317 318
            return false;
    }
    return true;
}

319 320 321 322 323
void setStrides(LayerParams &layerParams, const tensorflow::NodeDef &layer)
{
    if (hasLayerAttr(layer, "strides"))
    {
        const tensorflow::AttrValue& val = getLayerAttr(layer, "strides");
324
        int dimX, dimY, dimC, dimD;
325 326 327 328 329
        int layout = getDataLayout(layer);
        if (layout == DATA_LAYOUT_NCHW)
        {
            dimC = 1; dimY = 2; dimX = 3;
        }
330 331 332 333
        else if (layout == DATA_LAYOUT_NDHWC)
        {
            dimD = 1; dimY = 2; dimX = 3; dimC = 4;
        }
334 335 336 337
        else
        {
            dimY = 1; dimX = 2; dimC = 3;
        }
338
        if (!(val.list().i_size() == 4 || val.list().i_size() == 5) ||
339
            val.list().i(0) != 1 || val.list().i(dimC) != 1)
340
            CV_Error(Error::StsError, "Unsupported strides");
341 342 343 344 345 346 347 348 349 350 351
        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)));
        }
352 353 354 355 356 357 358 359 360 361 362
    }
}

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);

363 364
    Mat values = getTensorContent(tensor);
    CV_Assert(values.type() == CV_32SC1);
365
    // TODO: add reordering shape if dims == 4
366
    return DictValue::arrayInt((int*)values.data, values.total());
367 368 369 370 371 372 373
}

void setKSize(LayerParams &layerParams, const tensorflow::NodeDef &layer)
{
    if (hasLayerAttr(layer, "ksize"))
    {
        const tensorflow::AttrValue& val = getLayerAttr(layer, "ksize");
374
        int dimX, dimY, dimC, dimD;
375 376 377 378 379
        int layout = getDataLayout(layer);
        if (layout == DATA_LAYOUT_NCHW)
        {
            dimC = 1; dimY = 2; dimX = 3;
        }
380 381 382 383
        else if (layout == DATA_LAYOUT_NDHWC)
        {
            dimD = 1; dimY = 2; dimX = 3; dimC = 4;
        }
384 385 386 387
        else
        {
            dimY = 1; dimX = 2; dimC = 3;
        }
388
        if (!(val.list().i_size() == 4 || val.list().i_size() == 5) ||
389
            val.list().i(0) != 1 || val.list().i(dimC) != 1)
390
            CV_Error(Error::StsError, "Unsupported ksize");
391 392 393 394 395 396 397 398 399 400 401 402

        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)));
        }
403 404 405 406 407 408 409 410
    }
    else
    {
        layerParams.set("kernel_h", 1);
        layerParams.set("kernel_w", 1);
    }
}

411
void setPadMode(LayerParams &layerParams, const tensorflow::NodeDef &layer)
412 413 414 415 416
{
    if (hasLayerAttr(layer, "padding"))
        layerParams.set("pad_mode", getLayerAttr(layer, "padding").s());
}

417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
bool getExplicitPadding(LayerParams &layerParams, const tensorflow::NodeDef &layer, int64_t (&pads)[8])
{
    if (!layerParams.has("pad_mode") ||
        layerParams.get("pad_mode").getStringValue() != "EXPLICIT")
    {
        return false;
    }

    CV_Assert(hasLayerAttr(layer, "explicit_paddings"));

    const tensorflow::AttrValue& protoPads = getLayerAttr(layer, "explicit_paddings");
    if (protoPads.list().i_size() != 8)
    {
        CV_Error(Error::StsNotImplemented, "Unsupported asymmetric padding configuration.");
    }

    int n = sizeof(pads) / sizeof(pads[0]);
    for (int i = 0; i < n; ++i)
    {
        pads[i] = protoPads.list().i(i);
    }

    if (getDataLayout(layer) != DATA_LAYOUT_NCHW)
    {
        CV_LOG_DEBUG(NULL, "DNN/TF:     Data format " << getLayerAttr(layer, "data_format").s() << ", assuming NHWC.");
        // Perhaps, we have NHWC padding dimensions order.
        //  N    H    W    C
        // 0 1  2 3  4 5  6 7
        std::swap(pads[2], pads[6]);
        std::swap(pads[3], pads[7]);
        //  N    C    W    H
        // 0 1  2 3  4 5  6 7
        std::swap(pads[4], pads[6]);
        std::swap(pads[5], pads[7]);
        //  N    C    H    W
        // 0 1  2 3  4 5  6 7
    }

    return true;
}

458 459 460 461
Pin parsePin(const std::string &name)
{
    Pin pin(name);

462
    size_t delimiter_pos = name.find_first_of(':');
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
    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);
}

512
class TFLayerHandler;
S
Smirnov Egor 已提交
513

514 515
class TFImporter
{
516
public:
517 518
    TFImporter(Net& net, const char *model, const char *config = NULL);
    TFImporter(Net& net, const char *dataModel, size_t lenModel,
519
               const char *dataConfig = NULL, size_t lenConfig = 0);
520
protected:
521
    std::unique_ptr<TFLayerHandler> layerHandler;
522 523
    Net& dstNet;
    void populateNet();
524

525 526 527
    void parseNode(const tensorflow::NodeDef& layer);

    DataLayout predictOutputDataLayout(const tensorflow::NodeDef& layer);
528 529 530 531 532 533 534 535 536 537 538

    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);


539 540 541 542 543 544
    // 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;
545 546

    std::vector<String> netInputsNames;
547
    std::vector<MatShape> netInputShapes;
548 549 550 551 552 553 554 555 556 557

    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;
558 559

private:
560
    void addPermuteLayer(const int* order, const std::string& permName, Pin& inpId, int orderSize = 4);
561
    void setPadding(LayerParams &layerParams, const tensorflow::NodeDef &layer, std::string& inputName, float value = 0.);
R
rogday 已提交
562

563
    friend class TFLayerHandler;
R
rogday 已提交
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
    typedef void (TFImporter::*TFImporterNodeParser)(tensorflow::GraphDef&, const tensorflow::NodeDef&, LayerParams&);
    typedef std::map<std::string, TFImporterNodeParser> DispatchMap;

    const DispatchMap dispatch;
    static const DispatchMap buildDispatchMap();

    void parseConvolution        (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseBias               (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseMatMul             (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseReshape            (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseFlatten            (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseTranspose          (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseConstant           (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseLrn                (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseConcat             (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseMaxPool            (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseAvgPool            (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseMaxPoolGrad        (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parsePlaceholder        (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseSplit              (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseSlice              (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseStridedSlice       (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseMul                (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseFusedBatchNorm     (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseConv2DBackpropInput(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseBlockLSTM          (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseResize             (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseL2Normalize        (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parsePriorBox           (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseSoftmax            (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseCropAndResize      (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseMean               (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parsePack               (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseClipByValue        (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseLeakyRelu          (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
    void parseActivation         (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
600
    void parseExpandDims         (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
R
rogday 已提交
601 602

    void parseCustomLayer        (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
603 604
};

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
void TFImporter::setPadding(LayerParams &layerParams, const tensorflow::NodeDef &layer, std::string& inputName, float value)
{
    setPadMode(layerParams, layer);
    int64_t pads[8];

    if (!getExplicitPadding(layerParams, layer, pads))
    {
        return;
    }

    LayerParams padLp;
    padLp.name = layer.name() + "/pad";
    padLp.type = "Padding";
    padLp.set("paddings", DictValue::arrayInt(pads, sizeof(pads) / sizeof(pads[0])));
    padLp.set("value", value);

    int id = dstNet.addLayer(padLp.name, padLp.type, padLp);
    layer_id[padLp.name] = id;

    connect(layer_id, dstNet, parsePin(inputName), id, 0);
    inputName = padLp.name;

    layerParams.set("pad_mode", "VALID");
}

630
class TFLayerHandler : public detail::LayerHandler
S
Smirnov Egor 已提交
631 632
{
public:
633
    explicit TFLayerHandler(TFImporter* importer_);
S
Smirnov Egor 已提交
634

635 636 637
    void fillRegistry(const tensorflow::GraphDef& net);
    bool handleMissing(const tensorflow::NodeDef& layer);
    void handleFailed(const tensorflow::NodeDef& layer);
S
Smirnov Egor 已提交
638

639
protected:
S
Smirnov Egor 已提交
640 641 642
    TFImporter* importer;
};

R
rogday 已提交
643
const TFImporter::DispatchMap TFImporter::buildDispatchMap()
644
{
R
rogday 已提交
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
    static DispatchMap dispatch;
    dispatch["Conv2D"] = dispatch["SpaceToBatchND"] = dispatch["DepthwiseConv2dNative"] =
            dispatch["Pad"] = dispatch["MirrorPad"] = dispatch["Conv3D"] = &TFImporter::parseConvolution;
    dispatch["BiasAdd"] = dispatch["Add"] = dispatch["AddV2"] = dispatch["Sub"] = dispatch["AddN"] = &TFImporter::parseBias;
    dispatch["MatMul"] = &TFImporter::parseMatMul;
    dispatch["Reshape"] = &TFImporter::parseReshape;
    dispatch["Flatten"] = dispatch["Squeeze"] = &TFImporter::parseFlatten;
    dispatch["Transpose"] = &TFImporter::parseTranspose;
    dispatch["Const"] = &TFImporter::parseConstant;
    dispatch["LRN"] = &TFImporter::parseLrn;
    dispatch["Concat"] = dispatch["ConcatV2"] = &TFImporter::parseConcat;
    dispatch["MaxPool"] = dispatch["MaxPool3D"] = &TFImporter::parseMaxPool;
    dispatch["AvgPool"] = dispatch["AvgPool3D"] = &TFImporter::parseAvgPool;
    dispatch["MaxPoolGrad"] = &TFImporter::parseMaxPoolGrad;
    dispatch["Placeholder"] = &TFImporter::parsePlaceholder;
    dispatch["Split"] = &TFImporter::parseSplit;
    dispatch["Slice"] = &TFImporter::parseSlice;
    dispatch["StridedSlice"] = &TFImporter::parseStridedSlice;
    dispatch["Mul"] = dispatch["RealDiv"] = &TFImporter::parseMul;
    dispatch["FusedBatchNorm"] = dispatch["FusedBatchNormV3"] = &TFImporter::parseFusedBatchNorm;
    dispatch["Conv2DBackpropInput"] = &TFImporter::parseConv2DBackpropInput;
    dispatch["BlockLSTM"] = &TFImporter::parseBlockLSTM;
    dispatch["ResizeNearestNeighbor"] = dispatch["ResizeBilinear"] = dispatch["FusedResizeAndPadConv2D"] = &TFImporter::parseResize;
    dispatch["L2Normalize"] = &TFImporter::parseL2Normalize;
    dispatch["PriorBox"] = &TFImporter::parsePriorBox;
    dispatch["Softmax"] = &TFImporter::parseSoftmax;
    dispatch["CropAndResize"] = &TFImporter::parseCropAndResize;
S
Smirnov Egor 已提交
672
    dispatch["Mean"] = dispatch["Sum"] = dispatch["Max"] = &TFImporter::parseMean;
R
rogday 已提交
673 674 675 676 677
    dispatch["Pack"] = &TFImporter::parsePack;
    dispatch["ClipByValue"] = &TFImporter::parseClipByValue;
    dispatch["LeakyRelu"] = &TFImporter::parseLeakyRelu;
    dispatch["Abs"] = dispatch["Tanh"] = dispatch["Sigmoid"] = dispatch["Relu"] =
            dispatch["Elu"] = dispatch["Exp"] = dispatch["Identity"] = dispatch["Relu6"] = &TFImporter::parseActivation;
678
    dispatch["ExpandDims"] = &TFImporter::parseExpandDims;
R
rogday 已提交
679 680

    return dispatch;
681 682
}

S
Smirnov Egor 已提交
683
// "Conv2D" "SpaceToBatchND" "DepthwiseConv2dNative" "Pad" "MirrorPad" "Conv3D"
R
rogday 已提交
684
void TFImporter::parseConvolution(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer_, LayerParams& layerParams)
685
{
R
rogday 已提交
686 687 688 689 690 691 692 693 694 695 696
    tensorflow::NodeDef layer = layer_;
    std::string name = layer.name();
    std::string type = layer.op();
    int num_inputs = layer.input_size();

    CV_CheckGT(num_inputs, 0, "");
    // The first node of dilated convolution subgraph.
    // Extract input node, dilation rate and paddings.
    std::string input = layer.input(0);
    StrIntVector next_layers;
    if (type == "SpaceToBatchND" || type == "Pad")
697
    {
R
rogday 已提交
698 699 700
        next_layers = getNextLayers(net, name, "Conv2D");
        if (next_layers.empty())
            next_layers = getNextLayers(net, name, "DepthwiseConv2dNative");
701
    }
702

R
rogday 已提交
703
    if (type == "SpaceToBatchND")
704
    {
R
rogday 已提交
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
        // op: "SpaceToBatchND"
        // input: "input"
        // input: "SpaceToBatchND/block_shape"
        // input: "SpaceToBatchND/paddings"
        CV_CheckEQ(num_inputs, 3, "");

        DictValue dilation = parseDims(getConstBlob(layer, value_id, 1));
        CV_Assert(dilation.size() == 2);
        layerParams.set("dilation_h", dilation.get<int>(0));
        layerParams.set("dilation_w", dilation.get<int>(1));

        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);
        layers_to_ignore.insert(next_layers[0].first);

        // FIXIT don't override, rewrite this code
        layer = net.node(next_layers[0].second);
        name = layer.name();
        type = layer.op();
        num_inputs = layer.input_size();
        CV_LOG_DEBUG(NULL, "DNN/TF:     switched to layer " << name << " @ " << type << ") with " << num_inputs << " inputs");
732
    }
R
rogday 已提交
733
    else if (type == "Pad" || type == "MirrorPad")
734
    {
R
rogday 已提交
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
        Mat paddings = getTensorContent(getConstBlob(layer, value_id, 1));
        CV_Assert(paddings.type() == CV_32SC1);
        if (paddings.total() == 8)
        {
            // Perhaps, we have NHWC padding dimensions order.
            //  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
        }
751

R
rogday 已提交
752 753 754 755 756 757 758 759
        if (next_layers.empty() || paddings.total() != 8 ||
            paddings.at<int32_t>(4) != paddings.at<int32_t>(5) ||
            paddings.at<int32_t>(6) != paddings.at<int32_t>(7) || type == "MirrorPad")
        {
            // Just a single padding layer.
            layerParams.set("paddings", DictValue::arrayInt<int*>((int*)paddings.data, paddings.total()));
            if (type == "MirrorPad")
                layerParams.set("type", "reflect");
760

R
rogday 已提交
761 762
            int id = dstNet.addLayer(name, "Padding", layerParams);
            layer_id[name] = id;
763

R
rogday 已提交
764 765 766 767 768 769 770
            connect(layer_id, dstNet, parsePin(input), id, 0);
            return;
        }
        else
        {
            // Merge with subsequent convolutional layer.
            CV_Assert(next_layers.size() == 1);
771

R
rogday 已提交
772 773 774 775 776 777 778 779 780 781 782
            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);

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

R
rogday 已提交
786 787 788 789 790 791
    // 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();
792

R
rogday 已提交
793 794
    layerParams.set("bias_term", false);
    layerParams.blobs.resize(1);
795

R
rogday 已提交
796 797 798 799
    next_layers = getNextLayers(net, name, "BiasAdd");
    if (next_layers.size() == 1) {
        layerParams.set("bias_term", true);
        layerParams.blobs.resize(2);
800

R
rogday 已提交
801
        int weights_layer_index = next_layers[0].second;
802

R
rogday 已提交
803 804 805 806 807 808 809 810 811 812 813 814 815
        blobFromTensor(getConstBlob(net.node(weights_layer_index), value_id), layerParams.blobs[1]);
        ExcludeLayer(net, weights_layer_index, 0, false);
        layers_to_ignore.insert(next_layers[0].first);

        // 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]);
816 817 818 819
            }
        }
    }

R
rogday 已提交
820 821 822 823 824
    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())
825
    {
R
rogday 已提交
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
        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
        }

        // Shuffle output channels from yxYX to xyXY.
        if (locPredTransposed)
        {
            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>());
            }
        }
        sharedWeights[kernelTensorName] = layerParams.blobs[0];
869 870 871
    }
    else
    {
R
rogday 已提交
872
        layerParams.blobs[0] = sharedWeightsIt->second;
873
    }
R
rogday 已提交
874 875
    Mat weights = layerParams.blobs[0];
    layerParams.set("kernel_size",  DictValue::arrayInt(&weights.size[2], weights.dims - 2));
876

R
rogday 已提交
877
    layerParams.set("num_output", layerParams.blobs[0].size[0]);
878

R
rogday 已提交
879 880
    setStrides(layerParams, layer);
    if (!layerParams.has("pad_w") && !layerParams.has("pad_h"))
881
        setPadding(layerParams, layer, input);
882

R
rogday 已提交
883 884 885 886 887 888 889 890
    // 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);
        layers_to_ignore.insert(next_layers[0].first);
    }
891

R
rogday 已提交
892 893
    int id = dstNet.addLayer(name, "Convolution", layerParams);
    layer_id[name] = id;
894

R
rogday 已提交
895 896
    // one input only
    connect(layer_id, dstNet, parsePin(input), id, 0);
897 898


R
rogday 已提交
899 900 901
    if (getDataLayout(name, data_layouts) == DATA_LAYOUT_UNKNOWN)
        data_layouts[name] = DATA_LAYOUT_NHWC;
}
902

S
Smirnov Egor 已提交
903
// "BiasAdd" "Add" "AddV2" "Sub" "AddN"
R
rogday 已提交
904 905 906 907 908
void TFImporter::parseBias(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    const std::string& name = layer.name();
    const std::string& type = layer.op();
    const int num_inputs = layer.input_size();
909

R
rogday 已提交
910 911 912 913 914 915 916 917
    CV_CheckGT(num_inputs, 0, "");
    bool haveConst = false;
    for(int ii = 0; !haveConst && ii < num_inputs; ++ii)
    {
        Pin input = parsePin(layer.input(ii));
        haveConst = value_id.find(input.name) != value_id.end();
    }
    CV_Assert(!haveConst || num_inputs == 2);
918

R
rogday 已提交
919 920 921 922 923 924
    if (haveConst)
    {
        Mat values = getTensorContent(getConstBlob(layer, value_id));
        CV_Assert(values.type() == CV_32FC1);
        if (type == "Sub")
            values *= -1.0f;
925

R
rogday 已提交
926 927 928 929 930
        int id;
        if (values.total() == 1)  // is a scalar.
        {
            layerParams.set("shift", values.at<float>(0));
            id = dstNet.addLayer(name, "Power", layerParams);
D
Dmitry Kurtaev 已提交
931
        }
R
rogday 已提交
932
        else  // is a vector
933
        {
R
rogday 已提交
934 935 936 937 938 939
            layerParams.blobs.resize(1, values);
            id = dstNet.addLayer(name, "Shift", layerParams);
        }
        layer_id[name] = id;

        // one input only
940 941 942 943 944 945
        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);
R
rogday 已提交
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
    }
    else
    {
        layerParams.set("operation", "sum");
        if (type == "Sub")
        {
            static float subCoeffs[] = {1.f, -1.f};
            layerParams.set("coeff", DictValue::arrayReal<float*>(subCoeffs, 2));
        }

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

        for (int ii = 0; ii < num_inputs; ii++)
        {
            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);
            connect(layer_id, dstNet, inp, id, ii);
965 966
        }
    }
967 968
}

R
rogday 已提交
969
void TFImporter::parseMatMul(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
970
{
R
rogday 已提交
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();

    CV_CheckEQ(num_inputs, 2, "");

    // 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();

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

    StrIntVector next_layers = getNextLayers(net, name, "BiasAdd");  // FIXIT Use layers fusion instead
    if (next_layers.empty())
988
    {
R
rogday 已提交
989
        next_layers = getNextLayers(net, name, "Add");
990
    }
R
rogday 已提交
991 992 993
    if (next_layers.size() == 1) {
        layerParams.set("bias_term", true);
        layerParams.blobs.resize(2);
D
Dmitry Kurtaev 已提交
994

R
rogday 已提交
995 996 997 998 999 1000
        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);
        layers_to_ignore.insert(next_layers[0].first);

        if (locPredTransposed)
1001
        {
R
rogday 已提交
1002 1003 1004 1005
            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)
1006
            {
R
rogday 已提交
1007
                std::swap(biasData[i], biasData[i + 1]);
1008 1009 1010
            }
        }
    }
1011

R
rogday 已提交
1012 1013 1014 1015 1016
    int kernel_blob_index = -1;
    const tensorflow::TensorProto& kernelTensor = getConstBlob(layer, value_id, -1, &kernel_blob_index);
    const String kernelTensorName = layer.input(kernel_blob_index);
    std::map<String, Mat>::iterator sharedWeightsIt = sharedWeights.find(kernelTensorName);
    if (sharedWeightsIt == sharedWeights.end())
1017
    {
R
rogday 已提交
1018 1019 1020
        blobFromTensor(kernelTensor, layerParams.blobs[0]);
        releaseTensor(const_cast<tensorflow::TensorProto*>(&kernelTensor));
        sharedWeights[kernelTensorName] = layerParams.blobs[0];
1021
    }
D
Dmitry Kurtaev 已提交
1022 1023
    else
    {
R
rogday 已提交
1024 1025
        layerParams.blobs[0] = sharedWeightsIt->second;
    }
1026

R
rogday 已提交
1027 1028 1029 1030
    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();
    }
1031

R
rogday 已提交
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
    layerParams.set("num_output", layerParams.blobs[0].size[0]);
    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>());
        }
1042
    }
1043

R
rogday 已提交
1044 1045
    int id = dstNet.addLayer(name, "InnerProduct", layerParams);
    layer_id[name] = id;
1046

R
rogday 已提交
1047 1048 1049 1050 1051
    // 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);
    data_layouts[name] = DATA_LAYOUT_PLANAR;
}
1052

R
rogday 已提交
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
void TFImporter::parseReshape(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();

    CV_CheckGT(num_inputs, 0, "");
    Pin inpId = parsePin(layer.input(0));
    DataLayout inpLayout = getDataLayout(layer.input(0), data_layouts);
    // 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())
1064
    {
R
rogday 已提交
1065 1066 1067 1068
        Mat newShape = getTensorContent(getConstBlob(layer, value_id, 1));
        int newShapeSize = newShape.total();
        bool hasSwap = false;
        if (newShapeSize == 4 && hasAllOnes(newShape, 0, 2))
1069
        {
R
rogday 已提交
1070 1071 1072 1073 1074 1075 1076 1077
            // 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));
            hasSwap = true;
        }
        if (inpLayout == DATA_LAYOUT_NHWC)
        {
            if (newShapeSize >= 2 || newShape.at<int>(1) == 1)
1078
            {
R
rogday 已提交
1079 1080 1081
                int order[] = {0, 2, 3, 1};  // From OpenCV's NCHW to NHWC.
                addPermuteLayer(order, name + "/nhwc", inpId);
                if (newShapeSize < 4)
1082
                {
R
rogday 已提交
1083
                    inpLayout = DATA_LAYOUT_NCHW;
1084
                }
1085 1086
                else
                {
R
rogday 已提交
1087
                    inpLayout = DATA_LAYOUT_NHWC;
1088 1089 1090
                }
            }
        }
R
rogday 已提交
1091
        layerParams.set("dim", DictValue::arrayInt<int*>(newShape.ptr<int>(), newShapeSize));
1092

R
rogday 已提交
1093 1094
        int id = dstNet.addLayer(name, "Reshape", layerParams);
        layer_id[name] = id;
1095

R
rogday 已提交
1096 1097 1098
        // one input only
        connect(layer_id, dstNet, inpId, id, 0);
        inpId = Pin(name);
1099

R
rogday 已提交
1100 1101 1102 1103 1104 1105 1106
        if ((inpLayout == DATA_LAYOUT_NHWC || inpLayout == DATA_LAYOUT_UNKNOWN || inpLayout == DATA_LAYOUT_PLANAR) &&
            newShapeSize == 4 && !hasSwap)
        {
            int order[] = {0, 3, 1, 2};  // Transform back to OpenCV's NCHW.
            addPermuteLayer(order, name + "/nchw", inpId);
            inpLayout = DATA_LAYOUT_NCHW;
        }
1107

R
rogday 已提交
1108
        data_layouts[name] = newShapeSize == 2 ? DATA_LAYOUT_PLANAR : inpLayout;
1109
    }
R
rogday 已提交
1110
    else
1111
    {
R
rogday 已提交
1112 1113 1114 1115 1116
        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;
1117 1118 1119
    }
}

1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
void TFImporter::parseExpandDims(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();

    CV_Assert(!netInputShapes.empty());

    CV_CheckGT(num_inputs, 0, "");
    Pin inpId = parsePin(layer.input(0));
    DataLayout inpLayout = getDataLayout(layer.input(0), data_layouts);

    // Get input shape
    std::vector<MatShape> inShape_, outShape_;
    int inpIdindex = layer_id.find(inpId.name)->second;

    dstNet.getLayerShapes(netInputShapes, inpIdindex, inShape_, outShape_);
    MatShape inpShape = outShape_[0];
    std::vector<int> outShape = inpShape;

    int outShapeSize = outShape.size();

    CV_Assert(inpShape.size() >= 1);
    // 2nd blob is dims tensor
    int axis = getConstBlob(layer, value_id, 1).int_val().Get(0);

    // Convert negative numbers to positive numbers, axis can be in range [-(D+1), D].
    if(axis < 0)
    {
        axis = inpShape.size() + axis + 1;
    }

    CV_Assert(0 <= axis && axis <= inpShape.size());

    // After ExpendDims, 3-dim data will become 4-dim data, and OpenCV retains 4-dim data as NCHW data layout.
    // Convert OpenCV's NHC to NCH first.
    if(outShapeSize == 3)
    {
1157
        // If axis equal to outShapeSize, that mean we expand in Channel dimension, and do not add permuteLayer.
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
        if(axis != outShapeSize)
        {
            int order[] = {0, 2, 1};  // From OpenCV's NHC to NCH.
            addPermuteLayer(order, name + "/nch", inpId, 3);

            std::swap(outShape[1], outShape[2]);
        }
        axis = (axis != 0)?(axis % outShapeSize + 1):2;
    }

    if(inpShape.size() == 4)
    {
        if(axis == inpShape.size())
        {
            int order[] = {0, 2, 3, 1};  // From OpenCV's NCHW to NHWC.
            addPermuteLayer(order, name + "/nhwc", inpId);

            // Convert shape From OpenCV's NCHW to NHWC.
            if(inpLayout == DATA_LAYOUT_NHWC)
            {
                std::swap(outShape[1], outShape[2]);
                std::swap(outShape[2], outShape[3]);
            }
        }
        if(inpLayout == DATA_LAYOUT_NHWC || inpLayout == DATA_LAYOUT_NCHW)
        {
            // toNCHW
            axis = (axis != 0)?(axis % outShapeSize + 1):0;
        }
    }

    // After ExpendDims, 5-dim data will become 6-dim data, and OpenCV retains 6-dim data as original data layout.
    // Convert OpenCV's NCDHW to NDHWC first.
    if (inpShape.size() == 5 && (inpLayout == DATA_LAYOUT_NDHWC || inpLayout == DATA_LAYOUT_UNKNOWN))
    {
        int order[] = {0, 2, 3, 4, 1};  // From OpenCV's NCDHW to NDHWC.
        addPermuteLayer(order, name + "/ndhwc", inpId, 5);

        // Convert shape From OpenCV's NCDHW to NDHWC.
        if(inpLayout == DATA_LAYOUT_NDHWC)
        {
            std::swap(outShape[1], outShape[2]);
            std::swap(outShape[2], outShape[3]);
            std::swap(outShape[3], outShape[4]);
        }
    }

    outShape.insert(outShape.begin() + axis, 1);
    outShapeSize += 1;

    // From OpenCV's NCDHW to NDHWC.
    if((inpLayout != DATA_LAYOUT_NHWC && inpLayout != DATA_LAYOUT_NCHW) && outShapeSize == 5)
    {
        for(int i = 1; i < outShapeSize - 1; i++)
        {
            std::swap(outShape[outShapeSize - i - 1], outShape[outShapeSize - i]);
        }
    }

    layerParams.set("dim", DictValue::arrayInt(&outShape[0], outShape.size()));
    int id = dstNet.addLayer(name, "Reshape", layerParams);
    layer_id[name] = id;

    connect(layer_id, dstNet, inpId, id, 0);

    if(outShapeSize == 5)
    {
        data_layouts[name] = DATA_LAYOUT_NDHWC;
    }
    else if(outShapeSize == 4)
    {
        data_layouts[name] = DATA_LAYOUT_NCHW;
    }
    else
    {
        data_layouts[name] = inpLayout;
    }
}

S
Smirnov Egor 已提交
1237
// "Flatten" "Squeeze"
R
rogday 已提交
1238
void TFImporter::parseFlatten(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
1239
{
R
rogday 已提交
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
    const std::string& name = layer.name();
    const std::string& type = layer.op();
    const int num_inputs = layer.input_size();

    CV_CheckGT(num_inputs, 0, "");
    Pin inpId = parsePin(layer.input(0));
    int inpLayout = getDataLayout(layer.input(0), data_layouts);
    if (type == "Squeeze")
    {
        CV_Assert(hasLayerAttr(layer, "squeeze_dims"));
        const tensorflow::AttrValue& dims = getLayerAttr(layer, "squeeze_dims");
        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)
        {
            if (dimsVector[i] != dimsVector[i - 1] + 1)
                CV_Error(Error::StsNotImplemented, "Unsupported squeeze configuration");
        }
        int start = dimsVector.front() - 1, end = dimsVector.back();
        if (start == -1 && end == 0)  // squeeze 0th dimension
        {
            start = 0;
            end = 1;
        }
        layerParams.set("axis", start);
        layerParams.set("end_axis", end);
    }
    if (inpLayout == DATA_LAYOUT_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, inpId, permId, 0);
        inpId = Pin(permName);
    }
    int id = dstNet.addLayer(name, "Flatten", layerParams);
    layer_id[name] = id;
    connect(layer_id, dstNet, inpId, id, 0);
    data_layouts[name] = DATA_LAYOUT_PLANAR;
1288 1289
}

R
rogday 已提交
1290
void TFImporter::parseTranspose(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
1291
{
R
rogday 已提交
1292 1293 1294 1295 1296 1297 1298 1299
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();

    CV_CheckGT(num_inputs, 0, "");
    Mat perm = getTensorContent(getConstBlob(layer, value_id, 1));
    CV_Assert(perm.type() == CV_32SC1);
    int* permData = (int*)perm.data;
    if (perm.total() == 4)
1300
    {
R
rogday 已提交
1301 1302 1303 1304 1305
        // Only NHWC <-> NCHW permutations are allowed. OpenCV is always
        // keep NCHW layout this way.
        int inpLayout = getDataLayout(layer.input(0), data_layouts);
        std::string type = "Identity";
        if (inpLayout == DATA_LAYOUT_NHWC)
1306
        {
R
rogday 已提交
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
            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;
            }
            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";
            }
            else
                CV_Error(Error::StsParseError, "Only NHWC <-> NCHW permutations are allowed.");
1330
        }
R
rogday 已提交
1331
        else if (inpLayout == DATA_LAYOUT_NCHW)
1332
        {
R
rogday 已提交
1333
            if (permData[0] == 0 && permData[1] == 2 && permData[2] == 3 && permData[3] == 1)
1334
            {
R
rogday 已提交
1335 1336 1337
                // in TensorFlow: NCHW->NHWC
                // in OpenCV: NCHW->NCHW
                data_layouts[name] = DATA_LAYOUT_NHWC;
1338
            }
R
rogday 已提交
1339
            else if (permData[0] == 0 && permData[1] == 1 && permData[2] == 2 && permData[3] == 3)
1340
            {
R
rogday 已提交
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
                // in TensorFlow: NCHW->NCHW
                // in OpenCV: NCHW->NCHW
                data_layouts[name] = DATA_LAYOUT_NCHW;
            }
            else
                CV_Error(Error::StsParseError, "Only NHWC <-> NCHW permutations are allowed.");
        }
        int id = dstNet.addLayer(name, type, layerParams);
        layer_id[name] = id;
        connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
    }
    else
    {
        layerParams.set("order", DictValue::arrayInt<int*>(permData, perm.total()));
1355

R
rogday 已提交
1356 1357
        int id = dstNet.addLayer(name, "Permute", layerParams);
        layer_id[name] = id;
1358

R
rogday 已提交
1359 1360 1361 1362 1363
        // one input only
        connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
        data_layouts[name] = DATA_LAYOUT_UNKNOWN;
    }
}
1364

R
rogday 已提交
1365 1366 1367
void TFImporter::parseConstant(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
}
1368

R
rogday 已提交
1369 1370 1371 1372
void TFImporter::parseLrn(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();
1373

R
rogday 已提交
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
    CV_CheckGT(num_inputs, 0, "");
    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);
1389

R
rogday 已提交
1390 1391
    int id = dstNet.addLayer(name, "LRN", layerParams);
    layer_id[name] = id;
1392

R
rogday 已提交
1393 1394
    connectToAllBlobs(layer_id, dstNet, parsePin(layer.input(0)), id, num_inputs);
}
1395

S
Smirnov Egor 已提交
1396
// "Concat" "ConcatV2"
R
rogday 已提交
1397 1398 1399 1400 1401
void TFImporter::parseConcat(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    const std::string& name = layer.name();
    const std::string& type = layer.op();
    const int num_inputs = layer.input_size();
1402

R
rogday 已提交
1403 1404 1405
    CV_CheckGT(num_inputs, 0, "");
    int axisId = (type == "Concat" ? 0 : num_inputs - 1);
    int axis = getConstBlob(layer, value_id, axisId).int_val().Get(0);
1406

R
rogday 已提交
1407 1408 1409 1410 1411
    if (getDataLayout(name, data_layouts) == DATA_LAYOUT_NHWC)
        axis = toNCHW(axis);
    else if (getDataLayout(name, data_layouts) == DATA_LAYOUT_NDHWC)
        axis = toNCDHW(axis);
    layerParams.set("axis", axis);
1412

R
rogday 已提交
1413 1414 1415
    // input(0) or input(n-1) is concat_dim
    int from = (type == "Concat" ? 1 : 0);
    int to = (type == "Concat" ? num_inputs : num_inputs - 1);
1416

R
rogday 已提交
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
    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;
        }
    }
1434

R
rogday 已提交
1435 1436
    int id = dstNet.addLayer(name, "Concat", layerParams);
    layer_id[name] = id;
1437

R
rogday 已提交
1438 1439 1440 1441 1442 1443 1444 1445
    for (int ii = from; ii < to; ii++)
    {
        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);
        connect(layer_id, dstNet, inp, id, ii - from);
    }
}
1446

S
Smirnov Egor 已提交
1447
// "MaxPool" "MaxPool3D"
R
rogday 已提交
1448 1449 1450 1451
void TFImporter::parseMaxPool(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();
1452
    std::string inputName = layer.input(0);
1453

R
rogday 已提交
1454 1455
    CV_CheckGT(num_inputs, 0, "");
    layerParams.set("pool", "max");
1456

R
rogday 已提交
1457 1458
    setKSize(layerParams, layer);
    setStrides(layerParams, layer);
1459
    setPadding(layerParams, layer, inputName, -std::numeric_limits<float>::infinity());
R
rogday 已提交
1460 1461
    // Test_TensorFlow_nets.EAST_text_detection/1, NGRAPH/CPU
    layerParams.set("ceil_mode", false);
1462

R
rogday 已提交
1463 1464
    int id = dstNet.addLayer(name, "Pooling", layerParams);
    layer_id[name] = id;
1465

1466
    connectToAllBlobs(layer_id, dstNet, parsePin(inputName), id, num_inputs);
R
rogday 已提交
1467
}
1468

S
Smirnov Egor 已提交
1469
// "AvgPool" "AvgPool3D"
R
rogday 已提交
1470 1471 1472 1473
void TFImporter::parseAvgPool(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();
1474

R
rogday 已提交
1475 1476 1477 1478 1479
    CV_CheckGT(num_inputs, 0, "");
    layerParams.set("pool", "ave");
    layerParams.set("ave_pool_padded_area", false);
    setKSize(layerParams, layer);
    setStrides(layerParams, layer);
1480
    setPadMode(layerParams, layer);
1481

R
rogday 已提交
1482 1483
    int id = dstNet.addLayer(name, "Pooling", layerParams);
    layer_id[name] = id;
1484

R
rogday 已提交
1485 1486
    connectToAllBlobs(layer_id, dstNet, parsePin(layer.input(0)), id, num_inputs);
}
1487

R
rogday 已提交
1488 1489 1490 1491
void TFImporter::parseMaxPoolGrad(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();
1492

R
rogday 已提交
1493
    CV_CheckEQ(num_inputs, 3, "");
D
Dmitry Kurtaev 已提交
1494

R
rogday 已提交
1495 1496 1497 1498 1499 1500
    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);
1501

R
rogday 已提交
1502 1503
    int id = dstNet.addLayer(name, "MaxUnpool", layerParams);
    layer_id[name] = id;
1504

R
rogday 已提交
1505 1506 1507 1508
    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);
}
1509

R
rogday 已提交
1510 1511 1512
void TFImporter::parsePlaceholder(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    const std::string& name = layer.name();
1513

R
rogday 已提交
1514
    DataLayout predictedLayout = data_layouts[name];
D
dkurt 已提交
1515

R
rogday 已提交
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
    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;
    }
    tensorflow::TensorShapeProto shape;
    if (hasLayerAttr(layer, "shape"))
        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())
    {
        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;
1542
        }
1543 1544 1545 1546 1547 1548 1549 1550 1551

        if (dims.size() == 5 && predictedLayout == DATA_LAYOUT_NDHWC)
        {
            std::swap(dims[3], dims[4]);  // NDHWC->NDHCW
            std::swap(dims[2], dims[3]);  // NDHCW->NDCHW
            std::swap(dims[1], dims[2]);  // NDCHW->NCDHW
            if (dims[0] == -1)  // It's OK to have undetermined batch size
                dims[0] = 1;
        }
R
rogday 已提交
1552 1553
        bool hasNeg = false;
        for (int i = 0; i < dims.size() && !hasNeg; ++i)
1554
        {
R
rogday 已提交
1555 1556 1557 1558 1559 1560
            hasNeg = dims[i] < 0;
        }
        if (!hasNeg)
            netInputShapes.push_back(dims);
    }
}
1561

R
rogday 已提交
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
void TFImporter::parseSplit(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    // TODO: determining axis index remapping by input dimensions order of input blob
    // TODO: slicing input may be Const op
    // TODO: slicing kernels for convolutions - in current implementation it is impossible
    // TODO: add parsing num of slices parameter
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();

    CV_CheckEQ(num_inputs, 2, "");
    // num_split
    // 1st blob is dims tensor
    int axis = getConstBlob(layer, value_id, 0).int_val().Get(0);
    if (getDataLayout(name, data_layouts) == DATA_LAYOUT_NHWC)
        axis = toNCHW(axis);
    layerParams.set("axis", axis);

    if (hasLayerAttr(layer, "num_split"))
        layerParams.set("num_split", getLayerAttr(layer, "num_split").i());

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

    // one input only
    connect(layer_id, dstNet, parsePin(layer.input(1)), id, 0);
}
1588

R
rogday 已提交
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
void TFImporter::parseSlice(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    // op: "Slice"
    // input: "input_node"
    // input: "Slice/begin"
    // input: "Slice/size"
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();

    CV_CheckEQ(num_inputs, 3, "");
    Mat begins = getTensorContent(getConstBlob(layer, value_id, 1));
    Mat sizes = getTensorContent(getConstBlob(layer, value_id, 2));
    CV_Assert_N(!begins.empty(), !sizes.empty());
    CV_CheckTypeEQ(begins.type(), CV_32SC1, "");
    CV_CheckTypeEQ(sizes.type(), CV_32SC1, "");

    if (begins.total() == 4 && getDataLayout(name, data_layouts) == DATA_LAYOUT_NHWC)
    {
        // Swap NHWC parameters' order to NCHW.
        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()));
1615

R
rogday 已提交
1616 1617
    int id = dstNet.addLayer(name, "Slice", layerParams);
    layer_id[name] = id;
1618

R
rogday 已提交
1619 1620
    connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
}
1621

R
rogday 已提交
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
void TFImporter::parseStridedSlice(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();

    CV_CheckEQ(num_inputs, 4, "");
    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)
    {
        if (ends.at<int>(i) < 0)
            ends.at<int>(i) -= 1;
        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()));
1658

R
rogday 已提交
1659 1660
    int id = dstNet.addLayer(name, "Slice", layerParams);
    layer_id[name] = id;
1661

R
rogday 已提交
1662 1663
    connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
}
1664

S
Smirnov Egor 已提交
1665
// "Mul" "RealDiv"
R
rogday 已提交
1666 1667 1668 1669 1670
void TFImporter::parseMul(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    const std::string& name = layer.name();
    const std::string& type = layer.op();
    const int num_inputs = layer.input_size();
1671

R
rogday 已提交
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
    CV_CheckGT(num_inputs, 0, "");
    int constId = -1;
    for(int ii = 0; ii < num_inputs; ++ii)
    {
        Pin input = parsePin(layer.input(ii));
        if (value_id.find(input.name) != value_id.end())
        {
            constId = ii;
            break;
        }
    }
    CV_Assert((constId != -1) || (num_inputs == 2));
1684

R
rogday 已提交
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695
    if (constId != -1)
    {
        // Multiplication by constant.
        CV_CheckEQ(num_inputs, 2, "");
        Mat scaleMat = getTensorContent(getConstBlob(layer, value_id));
        CV_Assert(scaleMat.type() == CV_32FC1);
        if (type == "RealDiv")
        {
            if (constId == 0)
                CV_Error(Error::StsNotImplemented, "Division of constant over variable");
            scaleMat = 1.0f / scaleMat;
1696
        }
R
rogday 已提交
1697 1698 1699

        int id;
        if (scaleMat.total() == 1)  // is a scalar.
1700
        {
R
rogday 已提交
1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
            // 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())
1716
            {
R
rogday 已提交
1717
                int maximumLayerIdx = next_layers[0].second;
1718

R
rogday 已提交
1719
                CV_Assert(net.node(maximumLayerIdx).input_size() == 2);
1720

R
rogday 已提交
1721 1722
                // The input from the Mul layer can also be at index 1.
                int mulInputIdx = (net.node(maximumLayerIdx).input(0) == name) ? 0 : 1;
1723

R
rogday 已提交
1724 1725
                ExcludeLayer(net, maximumLayerIdx, mulInputIdx, false);
                layers_to_ignore.insert(next_layers[0].first);
1726

R
rogday 已提交
1727 1728
                layerParams.set("negative_slope", scaleMat.at<float>(0));
                id = dstNet.addLayer(name, "ReLU", layerParams);
1729
            }
1730
            else
D
Dmitry Kurtaev 已提交
1731
            {
R
rogday 已提交
1732 1733 1734
                // Just a multiplication.
                layerParams.set("scale", scaleMat.at<float>(0));
                id = dstNet.addLayer(name, "Power", layerParams);
D
Dmitry Kurtaev 已提交
1735
            }
1736
        }
R
rogday 已提交
1737
        else  // is a vector
1738
        {
R
rogday 已提交
1739 1740 1741 1742
            layerParams.blobs.resize(1, scaleMat);

            StrIntVector next_layers = getNextLayers(net, name, "Add");
            if (!next_layers.empty())
1743
            {
R
rogday 已提交
1744 1745
                layerParams.set("bias_term", true);
                layerParams.blobs.resize(2);
1746

R
rogday 已提交
1747 1748 1749 1750
                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);
1751
            }
R
rogday 已提交
1752 1753 1754 1755 1756

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

            id = dstNet.addLayer(name, "Scale", layerParams);
1757
        }
R
rogday 已提交
1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
        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
    {
        // Check if all the inputs have the same shape.
        bool equalInpShapes = true;
        bool isShapeOnes = false;
        MatShape outShape0;
        for (int ii = 0; ii < num_inputs && !netInputShapes.empty(); ii++)
1774
        {
R
rogday 已提交
1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
            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)
1786
            {
R
rogday 已提交
1787
                outShape0 = outShape;
1788
            }
R
rogday 已提交
1789
            else if (outShape != outShape0)
1790
            {
R
rogday 已提交
1791 1792 1793 1794
                equalInpShapes = false;
                isShapeOnes = isAllOnes(outShape, 2, outShape.size()) ||
                              isAllOnes(outShape0, 2, outShape0.size());
                break;
1795
            }
1796
        }
R
rogday 已提交
1797 1798 1799

        int id;
        if (equalInpShapes || netInputShapes.empty() || (!equalInpShapes && isShapeOnes))
1800
        {
R
rogday 已提交
1801 1802
            layerParams.set("operation", type == "RealDiv" ? "div" : "prod");
            id = dstNet.addLayer(name, "Eltwise", layerParams);
1803
        }
R
rogday 已提交
1804
        else
1805
        {
R
rogday 已提交
1806 1807 1808 1809
            if (type == "RealDiv")
                CV_Error(Error::StsNotImplemented, "Division of non equal tensors");
            id = dstNet.addLayer(name, "Scale", layerParams);
        }
1810

R
rogday 已提交
1811
        layer_id[name] = id;
1812

R
rogday 已提交
1813
        for (int ii = 0; ii < num_inputs; ii++)
1814
        {
R
rogday 已提交
1815 1816 1817 1818 1819 1820 1821
            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);
            connect(layer_id, dstNet, inp, id, ii);
        }
    }
}
1822

S
Smirnov Egor 已提交
1823
// "FusedBatchNorm" "FusedBatchNormV3"
R
rogday 已提交
1824 1825 1826 1827 1828 1829 1830 1831
void TFImporter::parseFusedBatchNorm(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    // op: "FusedBatchNorm"
    // input: "input"
    // input: "BatchNorm/gamma"
    // input: "BatchNorm/beta"
    // input: "BatchNorm/moving_mean"
    // input: "BatchNorm/moving_variance"
1832

R
rogday 已提交
1833 1834
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();
D
dkurt 已提交
1835

R
rogday 已提交
1836 1837
    CV_CheckEQ(num_inputs, 5, "Expected gamma, beta, mean and std");
    Pin inpId = parsePin(layer.input(0));
1838

R
rogday 已提交
1839
    bool isTraining = hasLayerAttr(layer, "is_training") && getLayerAttr(layer, "is_training").b();
1840

R
rogday 已提交
1841
    layerParams.blobs.resize(2);
1842

R
rogday 已提交
1843 1844 1845 1846 1847 1848 1849 1850 1851
    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);
1852

R
rogday 已提交
1853 1854 1855 1856 1857 1858 1859 1860 1861
    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);
1862

R
rogday 已提交
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
    Mat mean, std;
    if (isTraining)
    {
        if (layerParams.blobs.size() == 2)
            CV_Error(Error::StsNotImplemented, "Cannot determine number "
                                               "of parameters for batch normalization layer.");
        mean = Mat::zeros(1, layerParams.blobs[2].total(), CV_32F);
        std = Mat::ones(1, layerParams.blobs[2].total(), CV_32F);

        // 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;
1888

R
rogday 已提交
1889 1890
    if (hasLayerAttr(layer, "epsilon"))
        layerParams.set("eps", getLayerAttr(layer, "epsilon").f());
1891

R
rogday 已提交
1892 1893
    int id = dstNet.addLayer(name, "BatchNorm", layerParams);
    layer_id[name] = id;
G
gal0is 已提交
1894

R
rogday 已提交
1895 1896 1897
    // one input only
    connect(layer_id, dstNet, inpId, id, 0);
}
G
gal0is 已提交
1898

R
rogday 已提交
1899 1900 1901 1902 1903 1904
void TFImporter::parseConv2DBackpropInput(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    // op: "Conv2DBackpropInput"
    // input: "conv2d_transpose/output_shape"
    // input: "weights"
    // input: "input"
G
gal0is 已提交
1905

1906
    std::string name = layer.name();
R
rogday 已提交
1907
    const int num_inputs = layer.input_size();
1908

R
rogday 已提交
1909
    CV_CheckEQ(num_inputs, 3, "Expected output shape, weights and input nodes");
1910

R
rogday 已提交
1911 1912
    layerParams.set("bias_term", false);
    layerParams.blobs.resize(1);
D
Dmitry Kurtaev 已提交
1913

R
rogday 已提交
1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936
    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);
        layers_to_ignore.insert(next_layers[0].first);
    }

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

    const int* kshape = layerParams.blobs[0].size.p;
    const int kernelH = kshape[2];
    const int kernelW = kshape[3];
    layerParams.set("kernel_h", kernelH);
    layerParams.set("kernel_w", kernelW);
    layerParams.set("num_output", kshape[1]);

    setStrides(layerParams, layer);
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
    setPadMode(layerParams, layer);
    int64_t pads[8];
    bool explicit_pads = getExplicitPadding(layerParams, layer, pads);
    int64_t begs[4] = {};
    int64_t ends[4] = {-1, -1, -1, -1};
    if (explicit_pads)
    {
        name += "/deconv";
        layerParams.set("pad_mode", "VALID");
        for (int i = 2; i < 4; ++i) // begins=[0, 0, a, b], ends=[-1, -1, c, d]
        {
            begs[i] = pads[2*i];
            ends[i] = -1 - pads[2*i + 1];
        }
    }
R
rogday 已提交
1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967

    // 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));
1968 1969 1970
    int shift = (getDataLayout(layer) == DATA_LAYOUT_NCHW);
    const int outH = outShape.at<int>(1 + shift) + begs[2] - 1 - ends[2];
    const int outW = outShape.at<int>(2 + shift) + begs[3] - 1 - ends[3];
R
rogday 已提交
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
    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);
    }
    int id = dstNet.addLayer(name, "Deconvolution", layerParams);
    layer_id[name] = id;

    // one input only
    connect(layer_id, dstNet, parsePin(layer.input(2)), id, 0);
1986 1987 1988 1989 1990 1991 1992 1993 1994 1995
    if (explicit_pads) // If we have explicit paddings, remove extra data
    {
        layerParams.set("begin", DictValue::arrayInt(begs, sizeof(begs) / sizeof(begs[0])));
        layerParams.set("end", DictValue::arrayInt(ends, sizeof(ends) / sizeof(ends[0])));

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

        connect(layer_id, dstNet, parsePin(name), id, 0);
    }
R
rogday 已提交
1996 1997 1998 1999 2000 2001 2002
}

void TFImporter::parseBlockLSTM(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    // op: "BlockLSTM"
    // input: "lstm_block_wrapper/ToInt64/x"  (ignore, number of time stamps)
    // input: "input"
2003 2004
    // input: "lstm_block_wrapper/zeros"
    // input: "lstm_block_wrapper/zeros"
R
rogday 已提交
2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023
    // 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"

    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();

    CV_CheckEQ(num_inputs, 9, "Unexpected number of input nodes");

    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)
D
Dmitry Kurtaev 已提交
2024
        {
R
rogday 已提交
2025 2026 2027 2028
            layerParams.set("use_cell_clip", true);
            layerParams.set("cell_clip", cellClip);
        }
    }
D
Dmitry Kurtaev 已提交
2029

2030
    Mat W, Wh, Wx, b, cs_prev, h_prev;
R
rogday 已提交
2031 2032
    blobFromTensor(getConstBlob(layer, value_id, 4), W);
    blobFromTensor(getConstBlob(layer, value_id, 8), b);
2033 2034
    blobFromTensor(getConstBlob(layer, value_id, 2), cs_prev);
    blobFromTensor(getConstBlob(layer, value_id, 3), h_prev);
R
rogday 已提交
2035
    const int outSize = W.cols / 4;
2036

R
rogday 已提交
2037 2038 2039 2040 2041 2042 2043 2044 2045
    // 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]);
2046
        }
R
rogday 已提交
2047 2048 2049
    Wx = W.rowRange(0, W.rows - outSize).t();
    Wh = W.rowRange(W.rows - outSize, W.rows).t();

2050
    layerParams.blobs.resize(5);
R
rogday 已提交
2051 2052 2053
    layerParams.blobs[0] = Wh;
    layerParams.blobs[1] = Wx;
    layerParams.blobs[2] = b;
2054 2055
    layerParams.blobs[3] = h_prev;
    layerParams.blobs[4] = cs_prev;
R
rogday 已提交
2056 2057 2058 2059 2060

    if (hasLayerAttr(layer, "use_peephole"))
    {
        bool usePeephole = getLayerAttr(layer, "use_peephole").b();
        if (usePeephole)
D
dkurt 已提交
2061
        {
R
rogday 已提交
2062
            layerParams.set("use_peephole", true);
2063
            layerParams.blobs.resize(8);
R
rogday 已提交
2064
            for (int i = 0; i < 3; ++i)
D
dkurt 已提交
2065
            {
R
rogday 已提交
2066 2067 2068 2069
                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.
2070
                layerParams.blobs[5 + i] = w;
D
dkurt 已提交
2071
            }
R
rogday 已提交
2072 2073
        }
    }
D
dkurt 已提交
2074

R
rogday 已提交
2075 2076
    int id = dstNet.addLayer(name, "LSTM", layerParams);
    layer_id[name] = id;
D
dkurt 已提交
2077

R
rogday 已提交
2078 2079 2080 2081
    // one input only
    connect(layer_id, dstNet, parsePin(layer.input(1)), id, 0);
    data_layouts[name] = DATA_LAYOUT_UNKNOWN;
}
2082

S
Smirnov Egor 已提交
2083
// "ResizeNearestNeighbor" "ResizeBilinear" "FusedResizeAndPadConv2D"
R
rogday 已提交
2084 2085 2086 2087 2088 2089
void TFImporter::parseResize(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer_, LayerParams& layerParams)
{
    tensorflow::NodeDef layer = layer_;
    std::string name = layer.name();
    const std::string& type = layer.op();
    int num_inputs = layer.input_size();
2090

R
rogday 已提交
2091 2092 2093 2094 2095 2096 2097 2098 2099
    CV_CheckGT(num_inputs, 0, "");
    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"
        CV_CheckEQ(num_inputs, 4, "Number of input for FusedResizeAndPadConv2D");
2100

R
rogday 已提交
2101 2102
        Mat paddings = getTensorContent(getConstBlob(layer, value_id, 2));
        CV_CheckEQ(countNonZero(paddings), 0, "Unsupported mode");
2103

R
rogday 已提交
2104 2105 2106 2107
        convWeights = layer.input(3);
        layer.mutable_input()->DeleteSubrange(2, 2);  // FIXIT do NOT modify input model
        num_inputs = layer.input_size();
        name = name + "/resize";
2108

R
rogday 已提交
2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
        if (hasLayerAttr(layer, "resize_align_corners"))
        {
            // FIXIT do NOT modify input model
            layer.mutable_attr()->insert(
                    ::google::protobuf::MapPair<std::string, tensorflow::AttrValue>("align_corners",
                                                                                    getLayerAttr(layer, "resize_align_corners")));
        }
    }
    if (num_inputs == 2)
    {
        Mat outSize = getTensorContent(getConstBlob(layer, value_id, 1));
        CV_CheckTypeEQ(outSize.type(), CV_32SC1, ""); CV_CheckEQ(outSize.total(), (size_t)2, "");
        layerParams.set("height", outSize.at<int>(0, 0));
        layerParams.set("width", outSize.at<int>(0, 1));
    }
    else if (num_inputs == 3)
    {
        Mat factorHeight = getTensorContent(getConstBlob(layer, value_id, 1));
        Mat factorWidth = getTensorContent(getConstBlob(layer, value_id, 2));
        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));
    }
    else
        CV_Check(num_inputs, num_inputs == 2 || num_inputs == 3, "");
2135

R
rogday 已提交
2136 2137 2138 2139
    if (type == "ResizeNearestNeighbor")
        layerParams.set("interpolation", "nearest");
    else
        layerParams.set("interpolation", "bilinear");
D
dkurt 已提交
2140

R
rogday 已提交
2141 2142
    if (hasLayerAttr(layer, "align_corners"))
        layerParams.set("align_corners", getLayerAttr(layer, "align_corners").b());
2143

R
rogday 已提交
2144 2145
    if (hasLayerAttr(layer, "half_pixel_centers"))
        layerParams.set("half_pixel_centers", getLayerAttr(layer, "half_pixel_centers").b());
2146

R
rogday 已提交
2147 2148
    int id = dstNet.addLayer(name, "Resize", layerParams);
    layer_id[name] = id;
2149

R
rogday 已提交
2150
    connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
2151

R
rogday 已提交
2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162
    // Step back to add convolution
    if (type == "FusedResizeAndPadConv2D")
    {
        tensorflow::NodeDef conv = layer_;
        conv.clear_input();
        conv.add_input(name);
        conv.add_input(convWeights);
        conv.set_op("Conv2D");
        parseNode(conv);
    }
}
D
dkurt 已提交
2163

R
rogday 已提交
2164 2165 2166 2167 2168
void TFImporter::parseL2Normalize(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    // op: "L2Normalize"
    // input: "input"
    // input: "reduction_indices" (axis)
2169

R
rogday 已提交
2170 2171
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();
D
dkurt 已提交
2172

R
rogday 已提交
2173 2174 2175
    CV_CheckEQ(num_inputs, 2, "");
    Mat reductionIndices = getTensorContent(getConstBlob(layer, value_id, 1));
    CV_Assert(reductionIndices.type() == CV_32SC1);
2176

R
rogday 已提交
2177 2178 2179 2180
    const int numAxes = reductionIndices.total();
    if (getDataLayout(name, data_layouts) == DATA_LAYOUT_NHWC)
        for (int i = 0; i < numAxes; ++i)
            reductionIndices.at<int>(i) = toNCHW(reductionIndices.at<int>(i));
D
dkurt 已提交
2181

R
rogday 已提交
2182 2183 2184 2185 2186 2187 2188 2189 2190
    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));
D
dkurt 已提交
2191

R
rogday 已提交
2192 2193 2194 2195
    int id = dstNet.addLayer(name, "Normalize", layerParams);
    layer_id[name] = id;
    connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
}
D
dkurt 已提交
2196

R
rogday 已提交
2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220
void TFImporter::parsePriorBox(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();

    CV_CheckEQ(num_inputs, 2, "");
    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());
    if (hasLayerAttr(layer, "step"))
        layerParams.set("step", getLayerAttr(layer, "step").f());

    const std::string paramNames[] = {"variance", "aspect_ratio", "scales",
                                      "width", "height"};
    for (int i = 0; i < 5; ++i)
    {
        if (hasLayerAttr(layer, paramNames[i]))
2221
        {
R
rogday 已提交
2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232
            Mat values = getTensorContent(getLayerAttr(layer, paramNames[i]).tensor());
            layerParams.set(paramNames[i],
                            DictValue::arrayReal<float*>((float*)values.data, values.total()));
        }
    }
    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);
    data_layouts[name] = DATA_LAYOUT_UNKNOWN;
}
2233

R
rogday 已提交
2234 2235 2236 2237
void TFImporter::parseSoftmax(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();
2238

R
rogday 已提交
2239 2240 2241
    CV_CheckGT(num_inputs, 0, "");
    if (hasLayerAttr(layer, "axis"))
        layerParams.set("axis", getLayerAttr(layer, "axis").i());
2242

R
rogday 已提交
2243 2244 2245 2246
    int id = dstNet.addLayer(name, "Softmax", layerParams);
    layer_id[name] = id;
    connectToAllBlobs(layer_id, dstNet, parsePin(layer.input(0)), id, num_inputs);
}
2247

R
rogday 已提交
2248 2249 2250 2251 2252 2253
void TFImporter::parseCropAndResize(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    // op: "CropAndResize"
    // input: "input"
    // input: "boxes"
    // input: "sizes"
2254

R
rogday 已提交
2255 2256 2257
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();
    CV_CheckEQ(num_inputs, 3, "");
2258

R
rogday 已提交
2259 2260
    Mat cropSize = getTensorContent(getConstBlob(layer, value_id, 2));
    CV_CheckTypeEQ(cropSize.type(), CV_32SC1, ""); CV_CheckEQ(cropSize.total(), (size_t)2, "");
2261

R
rogday 已提交
2262 2263
    layerParams.set("height", cropSize.at<int>(0));
    layerParams.set("width", cropSize.at<int>(1));
2264

R
rogday 已提交
2265 2266
    int id = dstNet.addLayer(name, "CropAndResize", layerParams);
    layer_id[name] = id;
2267

R
rogday 已提交
2268 2269 2270
    connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
    connect(layer_id, dstNet, parsePin(layer.input(1)), id, 1);
}
2271

S
Smirnov Egor 已提交
2272
// "Mean" "Sum" "Max"
R
rogday 已提交
2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
void TFImporter::parseMean(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    // 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

    const std::string& name = layer.name();
    const std::string& type = layer.op();
    const int num_inputs = layer.input_size();
S
Smirnov Egor 已提交
2291
    std::string pool_type = cv::toLowerCase(type);
2292
    DataLayout layout = getDataLayout(name, data_layouts);
R
rogday 已提交
2293

S
Smirnov Egor 已提交
2294 2295 2296 2297
    if (pool_type == "mean")
    {
        pool_type = "ave";
    }
R
rogday 已提交
2298 2299 2300 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
    CV_CheckGT(num_inputs, 0, "");

    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();

    if (indices.total() == 1 && indices.at<int>(0) == 0)
    {
        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, parsePin(layer.input(0)), flattenId, 0);

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

        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());
S
Smirnov Egor 已提交
2334
        avgLp.set("pool", pool_type);
R
rogday 已提交
2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355
        // pooling kernel H x 1
        avgLp.set("global_pooling_h", true);
        avgLp.set("kernel_w", 1);
        int avgId = dstNet.addLayer(avgName, "Pooling", avgLp);
        layer_id[avgName] = avgId;
        connect(layer_id, dstNet, Pin(reshapeName), avgId, 0);

        LayerParams sliceLp;
        std::string layerShapeName = name + "/slice";
        CV_Assert(layer_id.find(layerShapeName) == layer_id.end());
        sliceLp.set("axis", 0);
        int begin[] = {0};
        int size[] = {1};
        sliceLp.set("begin", DictValue::arrayInt(&begin[0], 1));
        sliceLp.set("size", DictValue::arrayInt(&size[0], 1));
        int sliceId = dstNet.addLayer(layerShapeName, "Slice", sliceLp);
        layer_id[layerShapeName] = sliceId;
        connect(layer_id, dstNet, Pin(layer.input(0)), sliceId, 0);

        if (!keepDims)
        {
2356 2357 2358 2359 2360 2361 2362 2363 2364 2365
            if (layout == DATA_LAYOUT_NHWC)
            {
                LayerParams permLP;
                int order[] = {0, 2, 3, 1};  // From OpenCV's NCHW to NHWC.
                std::string permName = name + "/nhwc";
                Pin inpId = Pin(layerShapeName);
                addPermuteLayer(order, permName, inpId);
                layerShapeName = permName;
            }

R
rogday 已提交
2366 2367 2368 2369 2370 2371 2372 2373 2374 2375
            LayerParams squeezeLp;
            std::string squeezeName = name + "/squeeze";
            CV_Assert(layer_id.find(squeezeName) == layer_id.end());
            squeezeLp.set("axis", 0);
            squeezeLp.set("end_axis", 1);
            int squeezeId = dstNet.addLayer(squeezeName, "Flatten", squeezeLp);
            layer_id[squeezeName] = squeezeId;
            connect(layer_id, dstNet, Pin(layerShapeName), squeezeId, 0);
            layerShapeName = squeezeName;
        }
2376

R
rogday 已提交
2377 2378 2379 2380 2381 2382 2383 2384
        int id = dstNet.addLayer(name, "Reshape", layerParams);
        layer_id[name] = id;
        connect(layer_id, dstNet, Pin(avgName), id, 0);
        connect(layer_id, dstNet, Pin(layerShapeName), id, 1);
    } else if (indices.total() == 1) {
        int axis = toNCHW(indices.at<int>(0));
        if (axis == 2 || axis == 3)
        {
S
Smirnov Egor 已提交
2385
            layerParams.set("pool", pool_type);
R
rogday 已提交
2386 2387
            layerParams.set(axis == 2 ? "kernel_w" : "kernel_h", 1);
            layerParams.set(axis == 2 ? "global_pooling_h" : "global_pooling_w", true);
2388

2389 2390 2391 2392 2393 2394 2395
            if (keepDims)
            {
                int id = dstNet.addLayer(name, "Pooling", layerParams);
                layer_id[name] = id;
                connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
            }
            else
R
rogday 已提交
2396 2397
            {
                // To keep correct order after squeeze dims we first need to change layout from NCHW to NHWC
2398 2399 2400 2401 2402 2403
                std::string poolingName = name + "/Pooling";
                CV_Assert(layer_id.find(poolingName) == layer_id.end());
                int id = dstNet.addLayer(poolingName, "Pooling", layerParams);
                layer_id[poolingName] = id;
                connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);

R
rogday 已提交
2404 2405
                LayerParams permLP;
                int order[] = {0, 2, 3, 1};  // From OpenCV's NCHW to NHWC.
2406 2407
                std::string permName = name + "/nhwc";
                Pin inpId = Pin(poolingName);
R
rogday 已提交
2408 2409 2410
                addPermuteLayer(order, permName, inpId);

                LayerParams squeezeLp;
2411
                const std::string& squeezeName = name;
R
rogday 已提交
2412 2413 2414 2415 2416 2417
                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);
            }
2418
        }
R
rogday 已提交
2419
        else if (axis == 1)
D
Dmitry Kurtaev 已提交
2420
        {
R
rogday 已提交
2421 2422
            int order[] = {0, 2, 3, 1};  // From OpenCV's NCHW to NHWC.
            Pin inpId = parsePin(layer.input(0));
2423 2424
            std::string permName = name + "/nhwc";
            addPermuteLayer(order, permName, inpId);
2425

S
Smirnov Egor 已提交
2426
            layerParams.set("pool", pool_type);
R
rogday 已提交
2427 2428
            layerParams.set("kernel_h", 1);
            layerParams.set("global_pooling_w", true);
2429 2430 2431 2432 2433
            std::string poolingName = name + "/Pooling";
            CV_Assert(layer_id.find(poolingName) == layer_id.end());
            int id = dstNet.addLayer(poolingName, "Pooling", layerParams);
            layer_id[poolingName] = id;
            connect(layer_id, dstNet, Pin(permName), id, 0);
2434

R
rogday 已提交
2435
            if (!keepDims)
D
David 已提交
2436
            {
R
rogday 已提交
2437
                LayerParams squeezeLp;
2438
                const std::string& squeezeName = name;
R
rogday 已提交
2439 2440 2441 2442 2443
                int channel_id = 3; // TF NHWC layout
                squeezeLp.set("axis", channel_id - 1);
                squeezeLp.set("end_axis", channel_id);
                int squeezeId = dstNet.addLayer(squeezeName, "Flatten", squeezeLp);
                layer_id[squeezeName] = squeezeId;
2444
                connect(layer_id, dstNet, Pin(poolingName), squeezeId, 0);
D
David 已提交
2445 2446
            }
            else
2447
            {
R
rogday 已提交
2448
                int order[] = {0, 3, 1, 2};  // From NHWC to OpenCV's NCHW.
2449 2450
                Pin inpId = parsePin(poolingName);
                addPermuteLayer(order, name, inpId);
2451
            }
D
Dmitry Kurtaev 已提交
2452
        }
R
rogday 已提交
2453 2454 2455
    } else {
        if (indices.total() != 2 || indices.at<int>(0) != 1 || indices.at<int>(1) != 2)
            CV_Error(Error::StsNotImplemented, "Unsupported mode of reduce_mean or reduce_sum operation.");
D
Dmitry Kurtaev 已提交
2456

S
Smirnov Egor 已提交
2457
        layerParams.set("pool", pool_type);
R
rogday 已提交
2458 2459
        layerParams.set("global_pooling", true);

2460
        if (keepDims)
2461
        {
2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472
            int id = dstNet.addLayer(name, "Pooling", layerParams);
            layer_id[name] = id;
            connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
        }
        else
        {
            std::string poolingName = name + "/Pooling";
            CV_Assert(layer_id.find(poolingName) == layer_id.end());
            int id = dstNet.addLayer(poolingName, "Pooling", layerParams);
            layer_id[poolingName] = id;
            connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
R
rogday 已提交
2473
            LayerParams flattenLp;
2474
            const std::string& flattenName = name;
R
rogday 已提交
2475 2476
            int flattenId = dstNet.addLayer(flattenName, "Flatten", flattenLp);
            layer_id[flattenName] = flattenId;
2477 2478
            connect(layer_id, dstNet, Pin(poolingName), flattenId, 0);
            data_layouts[name] = DATA_LAYOUT_PLANAR;
2479
        }
R
rogday 已提交
2480 2481
    }
}
2482

R
rogday 已提交
2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519
void TFImporter::parsePack(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    // 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).

    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();

    CV_CheckGT(num_inputs, 0, "");
    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();
    CV_CheckEQ(num_inputs, num, "");
    std::string base_name = name + "/reshape_";
    std::vector<int> reshape_ids;
    for (int i = 0; i < num; i++) {
        std::ostringstream ss;
        ss << i;
        std::string reshape_name = base_name + ss.str();
        LayerParams reshapeLP;
        reshapeLP.set("axis", dim);
        reshapeLP.set("num_axes", 1);
        int outShape[] = {1, -1};
        reshapeLP.set("dim", DictValue::arrayInt(&outShape[0], 2));
        int id = dstNet.addLayer(reshape_name, "Reshape", reshapeLP);
        layer_id[reshape_name] = id;
        reshape_ids.push_back(id);
        connect(layer_id, dstNet, parsePin(layer.input(i)), id, 0);
    }
2520

R
rogday 已提交
2521 2522 2523
    layerParams.set("axis", dim);
    int id = dstNet.addLayer(name, "Concat", layerParams);
    layer_id[name] = id;
2524

R
rogday 已提交
2525 2526 2527
    for (int li = 0; li < num; li++)
        dstNet.connect(reshape_ids[li], 0, id, li);
}
2528

R
rogday 已提交
2529 2530 2531 2532 2533 2534
void TFImporter::parseClipByValue(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    // op: "ClipByValue"
    // input: "input"
    // input: "mix"
    // input: "max"
2535

R
rogday 已提交
2536 2537
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();
L
Liubov Batanina 已提交
2538

R
rogday 已提交
2539
    CV_CheckEQ(num_inputs, 3, "");
L
Liubov Batanina 已提交
2540

R
rogday 已提交
2541 2542 2543 2544
    Mat minValue = getTensorContent(getConstBlob(layer, value_id, 1));
    Mat maxValue = getTensorContent(getConstBlob(layer, value_id, 2));
    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, "");
L
Liubov Batanina 已提交
2545

R
rogday 已提交
2546 2547
    layerParams.set("min_value", minValue.at<float>(0));
    layerParams.set("max_value", maxValue.at<float>(0));
L
Liubov Batanina 已提交
2548

R
rogday 已提交
2549 2550
    int id = dstNet.addLayer(name, "ReLU6", layerParams);
    layer_id[name] = id;
L
Liubov Batanina 已提交
2551

R
rogday 已提交
2552 2553
    connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
}
D
Dmitry Kurtaev 已提交
2554

R
rogday 已提交
2555 2556 2557 2558
void TFImporter::parseLeakyRelu(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();
D
Dmitry Kurtaev 已提交
2559

R
rogday 已提交
2560 2561 2562
    CV_CheckGT(num_inputs, 0, "");
    CV_Assert(hasLayerAttr(layer, "alpha"));
    layerParams.set("negative_slope", getLayerAttr(layer, "alpha").f());
D
Dmitry Kurtaev 已提交
2563

R
rogday 已提交
2564 2565 2566 2567
    int id = dstNet.addLayer(name, "ReLU", layerParams);
    layer_id[name] = id;
    connectToAllBlobs(layer_id, dstNet, parsePin(layer.input(0)), id, num_inputs);
}
D
Dmitry Kurtaev 已提交
2568

S
Smirnov Egor 已提交
2569
// "Abs" "Tanh" "Sigmoid" "Relu" "Elu" "Exp" "Identity" "Relu6"
R
rogday 已提交
2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587
void TFImporter::parseActivation(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    const std::string& name = layer.name();
    const std::string& type = layer.op();
    const int num_inputs = layer.input_size();

    CV_CheckGT(num_inputs, 0, "");
    std::string dnnType = type;
    if (type == "Abs") dnnType = "AbsVal";
    else if (type == "Tanh") dnnType = "TanH";
    else if (type == "Relu") dnnType = "ReLU";
    else if (type == "Relu6") dnnType = "ReLU6";
    else if (type == "Elu") dnnType = "ELU";

    int id = dstNet.addLayer(name, dnnType, layerParams);
    layer_id[name] = id;
    connectToAllBlobs(layer_id, dstNet, parsePin(layer.input(0)), id, num_inputs);
}
2588

R
rogday 已提交
2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618
void TFImporter::parseCustomLayer(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    // 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.

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

    // 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;
    for (int i = 0; i < num_inputs; ++i)
    {
        // Check if input is a Const node.
        if (value_id.find(layer.input(i)) != value_id.end())
D
dkurt 已提交
2619
        {
R
rogday 已提交
2620 2621
            Mat blob = getTensorContent(getConstBlob(layer, value_id, i));
            layerParams.blobs.push_back(blob);
D
dkurt 已提交
2622
        }
2623
        else
R
rogday 已提交
2624 2625 2626 2627
            inputsNames.push_back(layer.input(i));
    }
    int id = dstNet.addLayer(name, type, layerParams);
    layer_id[name] = id;
2628

R
rogday 已提交
2629 2630 2631 2632 2633
    for (int i = 0; i < inputsNames.size(); ++i)
    {
        connect(layer_id, dstNet, parsePin(inputsNames[i]), id, i);
    }
}
2634

R
rogday 已提交
2635
TFImporter::TFImporter(Net& net, const char *model, const char *config)
2636 2637
    : layerHandler(DNN_DIAGNOSTICS_RUN ?  new TFLayerHandler(this) : nullptr),
        dstNet(net), dispatch(buildDispatchMap())
R
rogday 已提交
2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648
{
    if (model && model[0])
    {
        CV_LOG_DEBUG(NULL, "DNN/TF: processing TensorFlow model from file: " << model);
        ReadTFNetParamsFromBinaryFileOrDie(model, &netBin);
    }
    if (config && config[0])
    {
        CV_LOG_DEBUG(NULL, "DNN/TF: processing TensorFlow config from file: " << config);
        ReadTFNetParamsFromTextFileOrDie(config, &netTxt);
    }
2649

R
rogday 已提交
2650 2651 2652 2653 2654 2655 2656 2657
    populateNet();
}

TFImporter::TFImporter(
        Net& net,
        const char *dataModel, size_t lenModel,
        const char *dataConfig, size_t lenConfig
)
2658 2659
    :  layerHandler(DNN_DIAGNOSTICS_RUN ?  new TFLayerHandler(this) : nullptr),
       dstNet(net), dispatch(buildDispatchMap())
R
rogday 已提交
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704
{
    if (dataModel != NULL && lenModel > 0)
    {
        CV_LOG_DEBUG(NULL, "DNN/TF: processing TensorFlow model from memory (" << lenModel << " bytes)");
        ReadTFNetParamsFromBinaryBufferOrDie(dataModel, lenModel, &netBin);
    }
    if (dataConfig != NULL && lenConfig > 0)
    {
        CV_LOG_DEBUG(NULL, "DNN/TF: processing TensorFlow config from memory (" << lenConfig << " bytes)");
        ReadTFNetParamsFromTextBufferOrDie(dataConfig, lenConfig, &netTxt);
    }
    populateNet();
}

void TFImporter::kernelFromTensor(const tensorflow::TensorProto &tensor, Mat &dstBlob)
{
    MatShape shape;
    blobShapeFromTensor(tensor, shape);
    int dims = (int)shape.size();

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

    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];

    dstBlob.create(shape, CV_32F);
2705
    CV_Assert(dstBlob.isContinuous());
R
rogday 已提交
2706 2707

    Mat tensorContent = getTensorContent(tensor, /*no copy*/false);
2708
    CV_Assert(tensorContent.isContinuous());
R
rogday 已提交
2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919
    int size = tensorContent.total();
    CV_Assert(size == (int)dstBlob.total());

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

    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];
                   }
                }
            }
        }
    }
}

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);

    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);
}

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())
        CV_Error(Error::StsError, "Input [" + layer.input(input_blob_index) +
                                  "] for node [" + layer.name() + "] not found");
    if (kernel_inp.blobIndex != 0)
        CV_Error(Error::StsError, "Unsupported kernel input");

    if(actual_inp_blob_idx) {
        *actual_inp_blob_idx = input_blob_index;
    }

    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
    {
        CV_Assert_N(nodeIdx < netTxt.node_size(),
                    netTxt.node(nodeIdx).name() == kernel_inp.name);
        return netTxt.node(nodeIdx).attr().at("value").tensor();
    }
}

static void addConstNodes(tensorflow::GraphDef& net, std::map<String, int>& const_layers,
                          std::set<String>& layers_to_ignore)
{
    CV_LOG_DEBUG(NULL, "DNN/TF: addConstNodes(): handling " << net.node_size() << " nodes...");
    for (int li = 0; li < net.node_size(); li++)
    {
        const tensorflow::NodeDef &layer = net.node(li);
        String name = layer.name();
        String type = layer.op();

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

        try
        {
            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);
            }
            layers_to_ignore.insert(name);
        }
        catch (const std::exception& e)
        {
            CV_LOG_ERROR(NULL, "DNN/TF: Can't handle node='" << name << "'. Exception: " << e.what());
            throw;
        }
    }
    CV_LOG_DEBUG(NULL, "DNN/TF: layers_to_ignore.size() = " << layers_to_ignore.size());
}

// 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.
DataLayout TFImporter::predictOutputDataLayout(const tensorflow::NodeDef& layer)
{
    DataLayout layout = getDataLayout(layer);
    if (layout != DATA_LAYOUT_UNKNOWN)
    {
        CV_LOG_DEBUG(NULL, "DNN/TF: predictOutputDataLayout(" << layer.name() << " @ " << layer.op() << ") => " << (int)layout << " (from attrs)");
        return layout;
    }

    // Determine layout by layer's inputs
    for (int i = 0, n = layer.input_size(); i < n; ++i)
    {
        std::map<String, DataLayout>::const_iterator it = data_layouts.find(getNodeName(layer.input(i)));
        if (it != data_layouts.end())
        {
            if (layout != DATA_LAYOUT_UNKNOWN)
            {
                if (it->second != layout && it->second != DATA_LAYOUT_UNKNOWN)
                    return DATA_LAYOUT_UNKNOWN;
            }
            else
                layout = it->second;
        }
    }

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

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

void TFImporter::populateNet()
{
2920 2921 2922 2923 2924 2925 2926 2927
#if GOOGLE_PROTOBUF_VERSION < 3005000
    size_t netBinSize = saturate_cast<size_t>(netBin.ByteSize());
    size_t netTxtSize = saturate_cast<size_t>(netTxt.ByteSize());
#else
    size_t netBinSize = netBin.ByteSizeLong();
    size_t netTxtSize = netTxt.ByteSizeLong();
#endif
    CV_Assert(netBinSize || netTxtSize);
R
rogday 已提交
2928 2929 2930 2931 2932 2933

    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()
    );

2934
    if (netTxtSize)
R
rogday 已提交
2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962
    {
        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");
    }
    else
    {
        removePhaseSwitches(netBin);
        CV_LOG_DEBUG(NULL, "DNN/TF: removePhaseSwitches(model) => " << netBin.node_size() << " nodes");

        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");
    }

2963
    tensorflow::GraphDef& net = netTxtSize != 0 ? netTxt : netBin;
R
rogday 已提交
2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026

    int layersSize = net.node_size();

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

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

        try
        {
            DataLayout layout = getDataLayout(layer);
            std::map<String, DataLayout>::iterator 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;
                        layout = DATA_LAYOUT_UNKNOWN;
                    }
                }
                else
                    layout = it->second;
            }
            else
                data_layouts[name] = layout;

            // 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;
        }
    }

    addConstNodes(netBin, value_id, layers_to_ignore);
    addConstNodes(netTxt, value_id, layers_to_ignore);

3027 3028 3029 3030 3031
    if (DNN_DIAGNOSTICS_RUN) {
        CV_LOG_INFO(NULL, "DNN/TF: start diagnostic run!");
        layerHandler->fillRegistry(net);
    }

R
rogday 已提交
3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049
    for (int li = 0; li < layersSize; li++)
    {
        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);
3050
    CV_LOG_DEBUG(NULL, (DNN_DIAGNOSTICS_RUN? "DNN/TF: diagnostic run completed!" : "DNN/TF: import completed!"));
R
rogday 已提交
3051 3052
}

3053
void TFImporter::addPermuteLayer(const int* order, const std::string& permName, Pin& inpId, int orderSize)
R
rogday 已提交
3054 3055
{
    LayerParams permLP;
3056
    permLP.set("order", DictValue::arrayInt<const int*>(order, orderSize));
R
rogday 已提交
3057 3058 3059 3060 3061 3062 3063 3064 3065
    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);
}

void TFImporter::parseNode(const tensorflow::NodeDef& layer)
{
3066 3067 3068 3069 3070 3071
#if GOOGLE_PROTOBUF_VERSION < 3005000
    size_t netTxtSize = saturate_cast<size_t>(netTxt.ByteSize());
#else
    size_t netTxtSize = netTxt.ByteSizeLong();
#endif
    tensorflow::GraphDef& net = netTxtSize != 0 ? netTxt : netBin;
R
rogday 已提交
3072 3073 3074 3075

    const std::string& name = layer.name();
    const std::string& type = layer.op();

3076
    LayerParams layerParams;
R
rogday 已提交
3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091
    try
    {

        if (layers_to_ignore.find(name) != layers_to_ignore.end())
        {
            CV_LOG_DEBUG(NULL, "DNN/TF:     ignored");
            return;
        }

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

        DispatchMap::const_iterator iter = dispatch.find(type);
        if (iter != dispatch.end())
        {
3092
            CALL_MEMBER_FN(*this, iter->second)(net, layer, layerParams);
R
rogday 已提交
3093
        }
S
Smirnov Egor 已提交
3094
        else if (!DNN_DIAGNOSTICS_RUN || !layerHandler->handleMissing(layer))
R
rogday 已提交
3095 3096
        {
            parseCustomLayer(net, layer, layerParams);
3097 3098
        }
    }
3099 3100
    catch (const std::exception& e)
    {
S
Smirnov Egor 已提交
3101 3102 3103 3104
        CV_LOG_ERROR(NULL, "DNN/TF: Can't parse layer for node='" << name << "' of type='" << type
                                                                  << "'. Exception: " << e.what());

        if (DNN_DIAGNOSTICS_RUN)
3105
        {
S
Smirnov Egor 已提交
3106
            layerHandler->handleFailed(layer);
3107 3108 3109
        }
        else
        {
S
Smirnov Egor 已提交
3110
            throw;
3111
        }
3112
    }
3113 3114
}

3115
TFLayerHandler::TFLayerHandler(TFImporter* importer_) : importer(importer_) {}
S
Smirnov Egor 已提交
3116

3117
void TFLayerHandler::fillRegistry(const tensorflow::GraphDef& net)
S
Smirnov Egor 已提交
3118
{
3119 3120
    for (int li = 0; li < net.node_size(); li++) {
        const tensorflow::NodeDef& layer = net.node(li);
S
Smirnov Egor 已提交
3121

3122 3123 3124 3125 3126 3127
        const std::string& name = layer.name();
        const std::string& type = layer.op();
        if (importer->dispatch.find(type) == importer->dispatch.end())
        {
            addMissing(name, type);
        }
S
Smirnov Egor 已提交
3128
    }
3129 3130
    printMissing();
};
S
Smirnov Egor 已提交
3131

3132
bool TFLayerHandler::handleMissing(const tensorflow::NodeDef& layer)
S
Smirnov Egor 已提交
3133
{
3134
    bool unsupported = contains(layer.op());
S
Smirnov Egor 已提交
3135

3136
    if (unsupported)
S
Smirnov Egor 已提交
3137
    {
3138
        handleFailed(layer);
S
Smirnov Egor 已提交
3139 3140
    }

3141 3142
    return unsupported;
}
S
Smirnov Egor 已提交
3143

3144 3145 3146 3147 3148 3149 3150 3151 3152 3153
void TFLayerHandler::handleFailed(const tensorflow::NodeDef& layer)
{
    LayerParams lp = getNotImplementedParams(layer.name(), layer.op());

    // the layer will be created or its params and type will be replaced
    int id = importer->dstNet.addLayer(lp.name, lp.type, lp);
    if (id != -1) // internal layer failure before the call to addLayer()
    {
        importer->layer_id[lp.name] = id;
    }
S
Smirnov Egor 已提交
3154 3155
}

3156 3157 3158 3159
} // namespace

#endif //HAVE_PROTOBUF

3160
Net readNetFromTensorflow(const String &model, const String &config)
3161
{
3162
    return detail::readNetDiagnostic<TFImporter>(model.c_str(), config.c_str());
3163
}
3164

3165 3166 3167
Net readNetFromTensorflow(const char* bufferModel, size_t lenModel,
                          const char* bufferConfig, size_t lenConfig)
{
3168
    return detail::readNetDiagnostic<TFImporter>(bufferModel, lenModel, bufferConfig, lenConfig);
3169 3170
}

3171
Net readNetFromTensorflow(const std::vector<uchar>& bufferModel, const std::vector<uchar>& bufferConfig)
3172
{
3173 3174 3175 3176 3177
    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());
3178 3179
}

3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208
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();
}

3209
CV__DNN_INLINE_NS_END
3210
}} // namespace