tf_importer.cpp 121.1 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);
C
cqn2219076254 已提交
601
    void parseSquare             (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
602 603
    void parseArg                (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);

R
rogday 已提交
604
    void parseCustomLayer        (tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams);
605 606
};

607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
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");
}

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

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

641
protected:
S
Smirnov Egor 已提交
642 643 644
    TFImporter* importer;
};

R
rogday 已提交
645
const TFImporter::DispatchMap TFImporter::buildDispatchMap()
646
{
R
rogday 已提交
647 648 649 650
    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;
651
    dispatch["MatMul"] = dispatch["BatchMatMul"] = &TFImporter::parseMatMul;
R
rogday 已提交
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
    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 已提交
674
    dispatch["Mean"] = dispatch["Sum"] = dispatch["Max"] = &TFImporter::parseMean;
R
rogday 已提交
675 676 677 678 679
    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;
680
    dispatch["ExpandDims"] = &TFImporter::parseExpandDims;
C
cqn2219076254 已提交
681
    dispatch["Square"] = &TFImporter::parseSquare;
682
    dispatch["ArgMax"] = dispatch["ArgMin"] = &TFImporter::parseArg;
R
rogday 已提交
683 684

    return dispatch;
685 686
}

S
Smirnov Egor 已提交
687
// "Conv2D" "SpaceToBatchND" "DepthwiseConv2dNative" "Pad" "MirrorPad" "Conv3D"
R
rogday 已提交
688
void TFImporter::parseConvolution(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer_, LayerParams& layerParams)
689
{
R
rogday 已提交
690 691 692 693 694 695 696 697 698 699 700
    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")
701
    {
R
rogday 已提交
702 703 704
        next_layers = getNextLayers(net, name, "Conv2D");
        if (next_layers.empty())
            next_layers = getNextLayers(net, name, "DepthwiseConv2dNative");
705
    }
706

R
rogday 已提交
707
    if (type == "SpaceToBatchND")
708
    {
R
rogday 已提交
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
        // 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");
736
    }
R
rogday 已提交
737
    else if (type == "Pad" || type == "MirrorPad")
738
    {
R
rogday 已提交
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
        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
        }
755

R
rogday 已提交
756 757 758 759 760 761 762 763
        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");
764

R
rogday 已提交
765 766
            int id = dstNet.addLayer(name, "Padding", layerParams);
            layer_id[name] = id;
767

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

R
rogday 已提交
776 777 778 779 780 781 782 783 784 785 786
            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");
787 788 789
        }
    }

R
rogday 已提交
790 791 792 793 794 795
    // 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();
796

R
rogday 已提交
797 798
    layerParams.set("bias_term", false);
    layerParams.blobs.resize(1);
799

R
rogday 已提交
800 801 802 803
    next_layers = getNextLayers(net, name, "BiasAdd");
    if (next_layers.size() == 1) {
        layerParams.set("bias_term", true);
        layerParams.blobs.resize(2);
804

R
rogday 已提交
805
        int weights_layer_index = next_layers[0].second;
806

R
rogday 已提交
807 808 809 810 811 812 813 814 815 816 817 818 819
        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]);
820 821 822 823
            }
        }
    }

R
rogday 已提交
824 825 826 827 828
    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())
829
    {
R
rogday 已提交
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 869 870 871 872
        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];
873 874 875
    }
    else
    {
R
rogday 已提交
876
        layerParams.blobs[0] = sharedWeightsIt->second;
877
    }
R
rogday 已提交
878 879
    Mat weights = layerParams.blobs[0];
    layerParams.set("kernel_size",  DictValue::arrayInt(&weights.size[2], weights.dims - 2));
880

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

R
rogday 已提交
883 884
    setStrides(layerParams, layer);
    if (!layerParams.has("pad_w") && !layerParams.has("pad_h"))
885
        setPadding(layerParams, layer, input);
886

R
rogday 已提交
887 888 889 890 891 892 893 894
    // 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);
    }
895

R
rogday 已提交
896 897
    int id = dstNet.addLayer(name, "Convolution", layerParams);
    layer_id[name] = id;
898

R
rogday 已提交
899 900
    // one input only
    connect(layer_id, dstNet, parsePin(input), id, 0);
901 902


R
rogday 已提交
903 904 905
    if (getDataLayout(name, data_layouts) == DATA_LAYOUT_UNKNOWN)
        data_layouts[name] = DATA_LAYOUT_NHWC;
}
906

S
Smirnov Egor 已提交
907
// "BiasAdd" "Add" "AddV2" "Sub" "AddN"
R
rogday 已提交
908 909 910 911 912
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();
913

R
rogday 已提交
914 915 916 917 918 919 920 921
    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);
922

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

R
rogday 已提交
930 931 932 933 934
        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 已提交
935
        }
R
rogday 已提交
936
        else  // is a vector
937
        {
R
rogday 已提交
938 939 940 941 942 943
            layerParams.blobs.resize(1, values);
            id = dstNet.addLayer(name, "Shift", layerParams);
        }
        layer_id[name] = id;

        // one input only
944 945 946 947 948 949
        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 已提交
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
    }
    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);
969 970
        }
    }
971 972
}

R
rogday 已提交
973
void TFImporter::parseMatMul(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
974
{
R
rogday 已提交
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
    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);

990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
    bool hasConstBlob = false;
    for(int i = 0; i < layer.input_size(); i++) {
        if (value_id.find(layer.input(i)) != value_id.end())
            hasConstBlob = true;
    }
    if (!hasConstBlob)
    {
        layerParams.blobs.clear();
        int id = dstNet.addLayer(name, "InnerProduct", layerParams);
        layer_id[name] = id;

        // two inputs
        for(int ii=0; ii<layer.input_size(); ii++){
            connect(layer_id, dstNet, parsePin(layer.input(ii)), id, ii);
        }
        return;
    }

R
rogday 已提交
1008 1009
    StrIntVector next_layers = getNextLayers(net, name, "BiasAdd");  // FIXIT Use layers fusion instead
    if (next_layers.empty())
1010
    {
R
rogday 已提交
1011
        next_layers = getNextLayers(net, name, "Add");
1012
    }
R
rogday 已提交
1013 1014 1015
    if (next_layers.size() == 1) {
        layerParams.set("bias_term", true);
        layerParams.blobs.resize(2);
D
Dmitry Kurtaev 已提交
1016

R
rogday 已提交
1017 1018 1019 1020 1021 1022
        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)
1023
        {
R
rogday 已提交
1024 1025 1026 1027
            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)
1028
            {
R
rogday 已提交
1029
                std::swap(biasData[i], biasData[i + 1]);
1030 1031 1032
            }
        }
    }
1033

R
rogday 已提交
1034 1035 1036 1037 1038
    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())
1039
    {
R
rogday 已提交
1040 1041 1042
        blobFromTensor(kernelTensor, layerParams.blobs[0]);
        releaseTensor(const_cast<tensorflow::TensorProto*>(&kernelTensor));
        sharedWeights[kernelTensorName] = layerParams.blobs[0];
1043
    }
D
Dmitry Kurtaev 已提交
1044 1045
    else
    {
R
rogday 已提交
1046 1047
        layerParams.blobs[0] = sharedWeightsIt->second;
    }
1048

R
rogday 已提交
1049 1050 1051 1052
    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();
    }
1053

R
rogday 已提交
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
    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>());
        }
1064
    }
1065

R
rogday 已提交
1066 1067
    int id = dstNet.addLayer(name, "InnerProduct", layerParams);
    layer_id[name] = id;
1068

R
rogday 已提交
1069 1070 1071 1072 1073
    // 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;
}
1074

R
rogday 已提交
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
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())
1086
    {
R
rogday 已提交
1087 1088 1089 1090
        Mat newShape = getTensorContent(getConstBlob(layer, value_id, 1));
        int newShapeSize = newShape.total();
        bool hasSwap = false;
        if (newShapeSize == 4 && hasAllOnes(newShape, 0, 2))
1091
        {
R
rogday 已提交
1092 1093 1094 1095 1096 1097 1098 1099
            // 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)
1100
            {
R
rogday 已提交
1101 1102 1103
                int order[] = {0, 2, 3, 1};  // From OpenCV's NCHW to NHWC.
                addPermuteLayer(order, name + "/nhwc", inpId);
                if (newShapeSize < 4)
1104
                {
R
rogday 已提交
1105
                    inpLayout = DATA_LAYOUT_NCHW;
1106
                }
1107 1108
                else
                {
R
rogday 已提交
1109
                    inpLayout = DATA_LAYOUT_NHWC;
1110 1111 1112
                }
            }
        }
R
rogday 已提交
1113
        layerParams.set("dim", DictValue::arrayInt<int*>(newShape.ptr<int>(), newShapeSize));
1114

R
rogday 已提交
1115 1116
        int id = dstNet.addLayer(name, "Reshape", layerParams);
        layer_id[name] = id;
1117

R
rogday 已提交
1118 1119 1120
        // one input only
        connect(layer_id, dstNet, inpId, id, 0);
        inpId = Pin(name);
1121

R
rogday 已提交
1122 1123 1124 1125 1126 1127 1128
        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;
        }
1129

R
rogday 已提交
1130
        data_layouts[name] = newShapeSize == 2 ? DATA_LAYOUT_PLANAR : inpLayout;
1131
    }
R
rogday 已提交
1132
    else
1133
    {
R
rogday 已提交
1134 1135 1136 1137 1138
        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;
1139 1140 1141
    }
}

1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
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)
    {
1179
        // If axis equal to outShapeSize, that mean we expand in Channel dimension, and do not add permuteLayer.
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 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
        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;
    }
}

C
cqn2219076254 已提交
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
// "Square"
void TFImporter::parseSquare(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, 1, "");

    int id;
    layerParams.set("operation", "prod");
    id = dstNet.addLayer(name, "Eltwise", layerParams);

    layer_id[name] = id;

    Pin inp = parsePin(layer.input(0));
    connect(layer_id, dstNet, inp, id, 0);
    connect(layer_id, dstNet, inp, id, 1);
}

S
Smirnov Egor 已提交
1278
// "Flatten" "Squeeze"
R
rogday 已提交
1279
void TFImporter::parseFlatten(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
1280
{
R
rogday 已提交
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
    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;
1329 1330
}

R
rogday 已提交
1331
void TFImporter::parseTranspose(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
1332
{
R
rogday 已提交
1333 1334 1335 1336 1337 1338 1339 1340
    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)
1341
    {
R
rogday 已提交
1342 1343 1344 1345 1346
        // 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)
1347
        {
R
rogday 已提交
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
            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.");
1371
        }
R
rogday 已提交
1372
        else if (inpLayout == DATA_LAYOUT_NCHW)
1373
        {
R
rogday 已提交
1374
            if (permData[0] == 0 && permData[1] == 2 && permData[2] == 3 && permData[3] == 1)
1375
            {
R
rogday 已提交
1376 1377 1378
                // in TensorFlow: NCHW->NHWC
                // in OpenCV: NCHW->NCHW
                data_layouts[name] = DATA_LAYOUT_NHWC;
1379
            }
R
rogday 已提交
1380
            else if (permData[0] == 0 && permData[1] == 1 && permData[2] == 2 && permData[3] == 3)
1381
            {
R
rogday 已提交
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
                // 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()));
1396

R
rogday 已提交
1397 1398
        int id = dstNet.addLayer(name, "Permute", layerParams);
        layer_id[name] = id;
1399

R
rogday 已提交
1400 1401 1402 1403 1404
        // one input only
        connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
        data_layouts[name] = DATA_LAYOUT_UNKNOWN;
    }
}
1405

R
rogday 已提交
1406 1407 1408
void TFImporter::parseConstant(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
}
1409

R
rogday 已提交
1410 1411 1412 1413
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();
1414

R
rogday 已提交
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
    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);
1430

R
rogday 已提交
1431 1432
    int id = dstNet.addLayer(name, "LRN", layerParams);
    layer_id[name] = id;
1433

R
rogday 已提交
1434 1435
    connectToAllBlobs(layer_id, dstNet, parsePin(layer.input(0)), id, num_inputs);
}
1436

S
Smirnov Egor 已提交
1437
// "Concat" "ConcatV2"
R
rogday 已提交
1438 1439 1440 1441 1442
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();
1443

R
rogday 已提交
1444 1445 1446
    CV_CheckGT(num_inputs, 0, "");
    int axisId = (type == "Concat" ? 0 : num_inputs - 1);
    int axis = getConstBlob(layer, value_id, axisId).int_val().Get(0);
1447

R
rogday 已提交
1448 1449 1450 1451 1452
    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);
1453

R
rogday 已提交
1454 1455 1456
    // input(0) or input(n-1) is concat_dim
    int from = (type == "Concat" ? 1 : 0);
    int to = (type == "Concat" ? num_inputs : num_inputs - 1);
1457

R
rogday 已提交
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
    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;
        }
    }
1475

R
rogday 已提交
1476 1477
    int id = dstNet.addLayer(name, "Concat", layerParams);
    layer_id[name] = id;
1478

R
rogday 已提交
1479 1480 1481 1482 1483 1484 1485 1486
    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);
    }
}
1487

S
Smirnov Egor 已提交
1488
// "MaxPool" "MaxPool3D"
R
rogday 已提交
1489 1490 1491 1492
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();
1493
    std::string inputName = layer.input(0);
1494

R
rogday 已提交
1495 1496
    CV_CheckGT(num_inputs, 0, "");
    layerParams.set("pool", "max");
1497

R
rogday 已提交
1498 1499
    setKSize(layerParams, layer);
    setStrides(layerParams, layer);
1500
    setPadding(layerParams, layer, inputName, -std::numeric_limits<float>::infinity());
R
rogday 已提交
1501 1502
    // Test_TensorFlow_nets.EAST_text_detection/1, NGRAPH/CPU
    layerParams.set("ceil_mode", false);
1503

R
rogday 已提交
1504 1505
    int id = dstNet.addLayer(name, "Pooling", layerParams);
    layer_id[name] = id;
1506

1507
    connectToAllBlobs(layer_id, dstNet, parsePin(inputName), id, num_inputs);
R
rogday 已提交
1508
}
1509

S
Smirnov Egor 已提交
1510
// "AvgPool" "AvgPool3D"
R
rogday 已提交
1511 1512 1513 1514
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();
1515

R
rogday 已提交
1516 1517 1518 1519 1520
    CV_CheckGT(num_inputs, 0, "");
    layerParams.set("pool", "ave");
    layerParams.set("ave_pool_padded_area", false);
    setKSize(layerParams, layer);
    setStrides(layerParams, layer);
1521
    setPadMode(layerParams, layer);
1522

R
rogday 已提交
1523 1524
    int id = dstNet.addLayer(name, "Pooling", layerParams);
    layer_id[name] = id;
1525

R
rogday 已提交
1526 1527
    connectToAllBlobs(layer_id, dstNet, parsePin(layer.input(0)), id, num_inputs);
}
1528

R
rogday 已提交
1529 1530 1531 1532
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();
1533

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

R
rogday 已提交
1536 1537 1538 1539 1540 1541
    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);
1542

R
rogday 已提交
1543 1544
    int id = dstNet.addLayer(name, "MaxUnpool", layerParams);
    layer_id[name] = id;
1545

R
rogday 已提交
1546 1547 1548 1549
    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);
}
1550

R
rogday 已提交
1551 1552 1553
void TFImporter::parsePlaceholder(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    const std::string& name = layer.name();
1554

R
rogday 已提交
1555
    DataLayout predictedLayout = data_layouts[name];
D
dkurt 已提交
1556

R
rogday 已提交
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
    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;
1583
        }
1584 1585 1586 1587 1588 1589 1590 1591 1592

        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 已提交
1593 1594
        bool hasNeg = false;
        for (int i = 0; i < dims.size() && !hasNeg; ++i)
1595
        {
R
rogday 已提交
1596 1597 1598 1599 1600 1601
            hasNeg = dims[i] < 0;
        }
        if (!hasNeg)
            netInputShapes.push_back(dims);
    }
}
1602

R
rogday 已提交
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628
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);
}
1629

R
rogday 已提交
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
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()));
1656

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

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

R
rogday 已提交
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
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()));
1699

R
rogday 已提交
1700 1701
    int id = dstNet.addLayer(name, "Slice", layerParams);
    layer_id[name] = id;
1702

R
rogday 已提交
1703 1704
    connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
}
1705

S
Smirnov Egor 已提交
1706
// "Mul" "RealDiv"
R
rogday 已提交
1707 1708 1709 1710 1711
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();
1712

R
rogday 已提交
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724
    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));
1725

R
rogday 已提交
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
    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;
1737
        }
R
rogday 已提交
1738 1739 1740

        int id;
        if (scaleMat.total() == 1)  // is a scalar.
1741
        {
R
rogday 已提交
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
            // 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())
1757
            {
R
rogday 已提交
1758
                int maximumLayerIdx = next_layers[0].second;
1759

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

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

R
rogday 已提交
1765 1766
                ExcludeLayer(net, maximumLayerIdx, mulInputIdx, false);
                layers_to_ignore.insert(next_layers[0].first);
1767

R
rogday 已提交
1768 1769
                layerParams.set("negative_slope", scaleMat.at<float>(0));
                id = dstNet.addLayer(name, "ReLU", layerParams);
1770
            }
1771
            else
D
Dmitry Kurtaev 已提交
1772
            {
R
rogday 已提交
1773 1774 1775
                // Just a multiplication.
                layerParams.set("scale", scaleMat.at<float>(0));
                id = dstNet.addLayer(name, "Power", layerParams);
D
Dmitry Kurtaev 已提交
1776
            }
1777
        }
R
rogday 已提交
1778
        else  // is a vector
1779
        {
R
rogday 已提交
1780 1781 1782 1783
            layerParams.blobs.resize(1, scaleMat);

            StrIntVector next_layers = getNextLayers(net, name, "Add");
            if (!next_layers.empty())
1784
            {
R
rogday 已提交
1785 1786
                layerParams.set("bias_term", true);
                layerParams.blobs.resize(2);
1787

R
rogday 已提交
1788 1789 1790 1791
                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);
1792
            }
R
rogday 已提交
1793 1794 1795 1796 1797

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

            id = dstNet.addLayer(name, "Scale", layerParams);
1798
        }
R
rogday 已提交
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814
        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++)
1815
        {
R
rogday 已提交
1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826
            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)
1827
            {
R
rogday 已提交
1828
                outShape0 = outShape;
1829
            }
R
rogday 已提交
1830
            else if (outShape != outShape0)
1831
            {
R
rogday 已提交
1832 1833 1834 1835
                equalInpShapes = false;
                isShapeOnes = isAllOnes(outShape, 2, outShape.size()) ||
                              isAllOnes(outShape0, 2, outShape0.size());
                break;
1836
            }
1837
        }
R
rogday 已提交
1838 1839 1840

        int id;
        if (equalInpShapes || netInputShapes.empty() || (!equalInpShapes && isShapeOnes))
1841
        {
R
rogday 已提交
1842 1843
            layerParams.set("operation", type == "RealDiv" ? "div" : "prod");
            id = dstNet.addLayer(name, "Eltwise", layerParams);
1844
        }
R
rogday 已提交
1845
        else
1846
        {
R
rogday 已提交
1847 1848 1849 1850
            if (type == "RealDiv")
                CV_Error(Error::StsNotImplemented, "Division of non equal tensors");
            id = dstNet.addLayer(name, "Scale", layerParams);
        }
1851

R
rogday 已提交
1852
        layer_id[name] = id;
1853

R
rogday 已提交
1854
        for (int ii = 0; ii < num_inputs; ii++)
1855
        {
R
rogday 已提交
1856 1857 1858 1859 1860 1861 1862
            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);
        }
    }
}
1863

S
Smirnov Egor 已提交
1864
// "FusedBatchNorm" "FusedBatchNormV3"
R
rogday 已提交
1865 1866 1867 1868 1869 1870 1871 1872
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"
1873

R
rogday 已提交
1874 1875
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();
D
dkurt 已提交
1876

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

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

R
rogday 已提交
1882
    layerParams.blobs.resize(2);
1883

R
rogday 已提交
1884 1885 1886 1887 1888 1889 1890 1891 1892
    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);
1893

R
rogday 已提交
1894 1895 1896 1897 1898 1899 1900 1901 1902
    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);
1903

R
rogday 已提交
1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928
    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;
1929

R
rogday 已提交
1930 1931
    if (hasLayerAttr(layer, "epsilon"))
        layerParams.set("eps", getLayerAttr(layer, "epsilon").f());
1932

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

R
rogday 已提交
1936 1937 1938
    // one input only
    connect(layer_id, dstNet, inpId, id, 0);
}
G
gal0is 已提交
1939

R
rogday 已提交
1940 1941 1942 1943 1944 1945
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 已提交
1946

1947
    std::string name = layer.name();
R
rogday 已提交
1948
    const int num_inputs = layer.input_size();
1949

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

R
rogday 已提交
1952 1953
    layerParams.set("bias_term", false);
    layerParams.blobs.resize(1);
D
Dmitry Kurtaev 已提交
1954

R
rogday 已提交
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977
    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);
1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992
    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 已提交
1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008

    // 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));
2009 2010 2011
    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 已提交
2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026
    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);
2027 2028 2029 2030 2031 2032 2033 2034 2035 2036
    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 已提交
2037 2038 2039 2040 2041 2042 2043
}

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"
2044 2045
    // input: "lstm_block_wrapper/zeros"
    // input: "lstm_block_wrapper/zeros"
R
rogday 已提交
2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
    // 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 已提交
2065
        {
R
rogday 已提交
2066 2067 2068 2069
            layerParams.set("use_cell_clip", true);
            layerParams.set("cell_clip", cellClip);
        }
    }
D
Dmitry Kurtaev 已提交
2070

2071
    Mat W, Wh, Wx, b, cs_prev, h_prev;
R
rogday 已提交
2072 2073
    blobFromTensor(getConstBlob(layer, value_id, 4), W);
    blobFromTensor(getConstBlob(layer, value_id, 8), b);
2074 2075
    blobFromTensor(getConstBlob(layer, value_id, 2), cs_prev);
    blobFromTensor(getConstBlob(layer, value_id, 3), h_prev);
R
rogday 已提交
2076
    const int outSize = W.cols / 4;
2077

R
rogday 已提交
2078 2079 2080 2081 2082 2083 2084 2085 2086
    // 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]);
2087
        }
R
rogday 已提交
2088 2089 2090
    Wx = W.rowRange(0, W.rows - outSize).t();
    Wh = W.rowRange(W.rows - outSize, W.rows).t();

2091
    layerParams.blobs.resize(5);
R
rogday 已提交
2092 2093 2094
    layerParams.blobs[0] = Wh;
    layerParams.blobs[1] = Wx;
    layerParams.blobs[2] = b;
2095 2096
    layerParams.blobs[3] = h_prev;
    layerParams.blobs[4] = cs_prev;
R
rogday 已提交
2097 2098 2099 2100 2101

    if (hasLayerAttr(layer, "use_peephole"))
    {
        bool usePeephole = getLayerAttr(layer, "use_peephole").b();
        if (usePeephole)
D
dkurt 已提交
2102
        {
R
rogday 已提交
2103
            layerParams.set("use_peephole", true);
2104
            layerParams.blobs.resize(8);
R
rogday 已提交
2105
            for (int i = 0; i < 3; ++i)
D
dkurt 已提交
2106
            {
R
rogday 已提交
2107 2108 2109 2110
                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.
2111
                layerParams.blobs[5 + i] = w;
D
dkurt 已提交
2112
            }
R
rogday 已提交
2113 2114
        }
    }
D
dkurt 已提交
2115

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

R
rogday 已提交
2119 2120 2121 2122
    // one input only
    connect(layer_id, dstNet, parsePin(layer.input(1)), id, 0);
    data_layouts[name] = DATA_LAYOUT_UNKNOWN;
}
2123

S
Smirnov Egor 已提交
2124
// "ResizeNearestNeighbor" "ResizeBilinear" "FusedResizeAndPadConv2D"
R
rogday 已提交
2125 2126 2127 2128 2129 2130
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();
2131

R
rogday 已提交
2132 2133 2134 2135 2136 2137 2138 2139 2140
    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");
2141

R
rogday 已提交
2142 2143
        Mat paddings = getTensorContent(getConstBlob(layer, value_id, 2));
        CV_CheckEQ(countNonZero(paddings), 0, "Unsupported mode");
2144

R
rogday 已提交
2145 2146 2147 2148
        convWeights = layer.input(3);
        layer.mutable_input()->DeleteSubrange(2, 2);  // FIXIT do NOT modify input model
        num_inputs = layer.input_size();
        name = name + "/resize";
2149

R
rogday 已提交
2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175
        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, "");
2176

R
rogday 已提交
2177 2178 2179 2180
    if (type == "ResizeNearestNeighbor")
        layerParams.set("interpolation", "nearest");
    else
        layerParams.set("interpolation", "bilinear");
D
dkurt 已提交
2181

R
rogday 已提交
2182 2183
    if (hasLayerAttr(layer, "align_corners"))
        layerParams.set("align_corners", getLayerAttr(layer, "align_corners").b());
2184

R
rogday 已提交
2185 2186
    if (hasLayerAttr(layer, "half_pixel_centers"))
        layerParams.set("half_pixel_centers", getLayerAttr(layer, "half_pixel_centers").b());
2187

R
rogday 已提交
2188 2189
    int id = dstNet.addLayer(name, "Resize", layerParams);
    layer_id[name] = id;
2190

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

R
rogday 已提交
2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203
    // 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 已提交
2204

R
rogday 已提交
2205 2206 2207 2208 2209
void TFImporter::parseL2Normalize(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    // op: "L2Normalize"
    // input: "input"
    // input: "reduction_indices" (axis)
2210

R
rogday 已提交
2211 2212
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();
D
dkurt 已提交
2213

R
rogday 已提交
2214 2215 2216
    CV_CheckEQ(num_inputs, 2, "");
    Mat reductionIndices = getTensorContent(getConstBlob(layer, value_id, 1));
    CV_Assert(reductionIndices.type() == CV_32SC1);
2217

R
rogday 已提交
2218 2219 2220 2221
    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 已提交
2222

R
rogday 已提交
2223 2224 2225 2226 2227 2228 2229 2230 2231
    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 已提交
2232

R
rogday 已提交
2233 2234 2235 2236
    int id = dstNet.addLayer(name, "Normalize", layerParams);
    layer_id[name] = id;
    connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
}
D
dkurt 已提交
2237

R
rogday 已提交
2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261
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]))
2262
        {
R
rogday 已提交
2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273
            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;
}
2274

R
rogday 已提交
2275 2276 2277 2278
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();
2279

R
rogday 已提交
2280 2281 2282
    CV_CheckGT(num_inputs, 0, "");
    if (hasLayerAttr(layer, "axis"))
        layerParams.set("axis", getLayerAttr(layer, "axis").i());
2283

R
rogday 已提交
2284 2285 2286 2287
    int id = dstNet.addLayer(name, "Softmax", layerParams);
    layer_id[name] = id;
    connectToAllBlobs(layer_id, dstNet, parsePin(layer.input(0)), id, num_inputs);
}
2288

R
rogday 已提交
2289 2290 2291 2292 2293 2294
void TFImporter::parseCropAndResize(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    // op: "CropAndResize"
    // input: "input"
    // input: "boxes"
    // input: "sizes"
2295

R
rogday 已提交
2296 2297 2298
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();
    CV_CheckEQ(num_inputs, 3, "");
2299

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

R
rogday 已提交
2303 2304
    layerParams.set("height", cropSize.at<int>(0));
    layerParams.set("width", cropSize.at<int>(1));
2305

R
rogday 已提交
2306 2307
    int id = dstNet.addLayer(name, "CropAndResize", layerParams);
    layer_id[name] = id;
2308

R
rogday 已提交
2309 2310 2311
    connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
    connect(layer_id, dstNet, parsePin(layer.input(1)), id, 1);
}
2312

S
Smirnov Egor 已提交
2313
// "Mean" "Sum" "Max"
R
rogday 已提交
2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331
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 已提交
2332
    std::string pool_type = cv::toLowerCase(type);
2333
    DataLayout layout = getDataLayout(name, data_layouts);
R
rogday 已提交
2334

S
Smirnov Egor 已提交
2335 2336 2337 2338
    if (pool_type == "mean")
    {
        pool_type = "ave";
    }
R
rogday 已提交
2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374
    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 已提交
2375
        avgLp.set("pool", pool_type);
R
rogday 已提交
2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396
        // 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)
        {
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406
            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 已提交
2407 2408 2409 2410 2411 2412 2413 2414 2415 2416
            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;
        }
2417

R
rogday 已提交
2418 2419 2420 2421 2422 2423 2424 2425
        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 已提交
2426
            layerParams.set("pool", pool_type);
R
rogday 已提交
2427 2428
            layerParams.set(axis == 2 ? "kernel_w" : "kernel_h", 1);
            layerParams.set(axis == 2 ? "global_pooling_h" : "global_pooling_w", true);
2429

2430 2431 2432 2433 2434 2435 2436
            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 已提交
2437 2438
            {
                // To keep correct order after squeeze dims we first need to change layout from NCHW to NHWC
2439 2440 2441 2442 2443 2444
                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 已提交
2445 2446
                LayerParams permLP;
                int order[] = {0, 2, 3, 1};  // From OpenCV's NCHW to NHWC.
2447 2448
                std::string permName = name + "/nhwc";
                Pin inpId = Pin(poolingName);
R
rogday 已提交
2449 2450 2451
                addPermuteLayer(order, permName, inpId);

                LayerParams squeezeLp;
2452
                const std::string& squeezeName = name;
R
rogday 已提交
2453 2454 2455 2456 2457 2458
                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);
            }
2459
        }
R
rogday 已提交
2460
        else if (axis == 1)
D
Dmitry Kurtaev 已提交
2461
        {
R
rogday 已提交
2462 2463
            int order[] = {0, 2, 3, 1};  // From OpenCV's NCHW to NHWC.
            Pin inpId = parsePin(layer.input(0));
2464 2465
            std::string permName = name + "/nhwc";
            addPermuteLayer(order, permName, inpId);
2466

S
Smirnov Egor 已提交
2467
            layerParams.set("pool", pool_type);
R
rogday 已提交
2468 2469
            layerParams.set("kernel_h", 1);
            layerParams.set("global_pooling_w", true);
2470 2471 2472 2473 2474
            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);
2475

R
rogday 已提交
2476
            if (!keepDims)
D
David 已提交
2477
            {
R
rogday 已提交
2478
                LayerParams squeezeLp;
2479
                const std::string& squeezeName = name;
R
rogday 已提交
2480 2481 2482 2483 2484
                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;
2485
                connect(layer_id, dstNet, Pin(poolingName), squeezeId, 0);
D
David 已提交
2486 2487
            }
            else
2488
            {
R
rogday 已提交
2489
                int order[] = {0, 3, 1, 2};  // From NHWC to OpenCV's NCHW.
2490 2491
                Pin inpId = parsePin(poolingName);
                addPermuteLayer(order, name, inpId);
2492
            }
D
Dmitry Kurtaev 已提交
2493
        }
R
rogday 已提交
2494 2495 2496
    } 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 已提交
2497

S
Smirnov Egor 已提交
2498
        layerParams.set("pool", pool_type);
R
rogday 已提交
2499 2500
        layerParams.set("global_pooling", true);

2501
        if (keepDims)
2502
        {
2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513
            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 已提交
2514
            LayerParams flattenLp;
2515
            const std::string& flattenName = name;
R
rogday 已提交
2516 2517
            int flattenId = dstNet.addLayer(flattenName, "Flatten", flattenLp);
            layer_id[flattenName] = flattenId;
2518 2519
            connect(layer_id, dstNet, Pin(poolingName), flattenId, 0);
            data_layouts[name] = DATA_LAYOUT_PLANAR;
2520
        }
R
rogday 已提交
2521 2522
    }
}
2523

R
rogday 已提交
2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560
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);
    }
2561

R
rogday 已提交
2562 2563 2564
    layerParams.set("axis", dim);
    int id = dstNet.addLayer(name, "Concat", layerParams);
    layer_id[name] = id;
2565

R
rogday 已提交
2566 2567 2568
    for (int li = 0; li < num; li++)
        dstNet.connect(reshape_ids[li], 0, id, li);
}
2569

R
rogday 已提交
2570 2571 2572 2573 2574 2575
void TFImporter::parseClipByValue(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    // op: "ClipByValue"
    // input: "input"
    // input: "mix"
    // input: "max"
2576

R
rogday 已提交
2577 2578
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();
L
Liubov Batanina 已提交
2579

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

R
rogday 已提交
2582 2583 2584 2585
    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 已提交
2586

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

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

R
rogday 已提交
2593 2594
    connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
}
D
Dmitry Kurtaev 已提交
2595

R
rogday 已提交
2596 2597 2598 2599
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 已提交
2600

R
rogday 已提交
2601 2602 2603
    CV_CheckGT(num_inputs, 0, "");
    CV_Assert(hasLayerAttr(layer, "alpha"));
    layerParams.set("negative_slope", getLayerAttr(layer, "alpha").f());
D
Dmitry Kurtaev 已提交
2604

R
rogday 已提交
2605 2606 2607 2608
    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 已提交
2609

S
Smirnov Egor 已提交
2610
// "Abs" "Tanh" "Sigmoid" "Relu" "Elu" "Exp" "Identity" "Relu6"
R
rogday 已提交
2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628
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);
}
2629

2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645
void TFImporter::parseArg(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    const std::string& name = layer.name();
    const std::string& type = layer.op();

    Mat dimension = getTensorContent(getConstBlob(layer, value_id, 1));
    CV_Assert(dimension.total() == 1 && dimension.type() == CV_32SC1);
    layerParams.set("axis", *dimension.ptr<int>());
    layerParams.set("op", type == "ArgMax" ? "max" : "min");
    layerParams.set("keepdims", false); //tensorflow doesn't have this atrr, the output's dims minus one(default);

    int id = dstNet.addLayer(name, "Arg", layerParams);
    layer_id[name] = id;
    connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
}

R
rogday 已提交
2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675
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 已提交
2676
        {
R
rogday 已提交
2677 2678
            Mat blob = getTensorContent(getConstBlob(layer, value_id, i));
            layerParams.blobs.push_back(blob);
D
dkurt 已提交
2679
        }
2680
        else
R
rogday 已提交
2681 2682 2683 2684
            inputsNames.push_back(layer.input(i));
    }
    int id = dstNet.addLayer(name, type, layerParams);
    layer_id[name] = id;
2685

R
rogday 已提交
2686 2687 2688 2689 2690
    for (int i = 0; i < inputsNames.size(); ++i)
    {
        connect(layer_id, dstNet, parsePin(inputsNames[i]), id, i);
    }
}
2691

R
rogday 已提交
2692
TFImporter::TFImporter(Net& net, const char *model, const char *config)
2693 2694
    : layerHandler(DNN_DIAGNOSTICS_RUN ?  new TFLayerHandler(this) : nullptr),
        dstNet(net), dispatch(buildDispatchMap())
R
rogday 已提交
2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705
{
    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);
    }
2706

R
rogday 已提交
2707 2708 2709 2710 2711 2712 2713 2714
    populateNet();
}

TFImporter::TFImporter(
        Net& net,
        const char *dataModel, size_t lenModel,
        const char *dataConfig, size_t lenConfig
)
2715 2716
    :  layerHandler(DNN_DIAGNOSTICS_RUN ?  new TFLayerHandler(this) : nullptr),
       dstNet(net), dispatch(buildDispatchMap())
R
rogday 已提交
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
{
    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);
2762
    CV_Assert(dstBlob.isContinuous());
R
rogday 已提交
2763 2764

    Mat tensorContent = getTensorContent(tensor, /*no copy*/false);
2765
    CV_Assert(tensorContent.isContinuous());
R
rogday 已提交
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 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 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 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976
    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()
{
2977 2978 2979 2980 2981 2982 2983 2984
#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 已提交
2985 2986 2987 2988 2989 2990

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

2991
    if (netTxtSize)
R
rogday 已提交
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
    {
        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");
    }

3020
    tensorflow::GraphDef& net = netTxtSize != 0 ? netTxt : netBin;
R
rogday 已提交
3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083

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

3084 3085 3086 3087 3088
    if (DNN_DIAGNOSTICS_RUN) {
        CV_LOG_INFO(NULL, "DNN/TF: start diagnostic run!");
        layerHandler->fillRegistry(net);
    }

R
rogday 已提交
3089 3090 3091 3092
    for (int li = 0; li < layersSize; li++)
    {
        const tensorflow::NodeDef& layer = net.node(li);

R
rogday 已提交
3093 3094
        CV_LOG_DEBUG(NULL, "DNN/TF: processing node (" << li << "/" << layersSize << ") with " << layer.input_size() << " inputs: "
                                                           << cv::format("[%s]:(%s)", layer.op().c_str(), layer.name().c_str()));
R
rogday 已提交
3095 3096 3097 3098 3099 3100 3101 3102 3103 3104

        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);
3105
    CV_LOG_DEBUG(NULL, (DNN_DIAGNOSTICS_RUN? "DNN/TF: diagnostic run completed!" : "DNN/TF: import completed!"));
R
rogday 已提交
3106 3107
}

3108
void TFImporter::addPermuteLayer(const int* order, const std::string& permName, Pin& inpId, int orderSize)
R
rogday 已提交
3109 3110
{
    LayerParams permLP;
3111
    permLP.set("order", DictValue::arrayInt<const int*>(order, orderSize));
R
rogday 已提交
3112 3113 3114 3115 3116 3117 3118 3119 3120
    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)
{
3121 3122 3123 3124 3125 3126
#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 已提交
3127 3128 3129 3130

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

3131
    LayerParams layerParams;
R
rogday 已提交
3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146
    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())
        {
3147
            CALL_MEMBER_FN(*this, iter->second)(net, layer, layerParams);
R
rogday 已提交
3148
        }
S
Smirnov Egor 已提交
3149
        else if (!DNN_DIAGNOSTICS_RUN || !layerHandler->handleMissing(layer))
R
rogday 已提交
3150 3151
        {
            parseCustomLayer(net, layer, layerParams);
3152 3153
        }
    }
3154 3155
    catch (const std::exception& e)
    {
S
Smirnov Egor 已提交
3156 3157 3158 3159
        CV_LOG_ERROR(NULL, "DNN/TF: Can't parse layer for node='" << name << "' of type='" << type
                                                                  << "'. Exception: " << e.what());

        if (DNN_DIAGNOSTICS_RUN)
3160
        {
S
Smirnov Egor 已提交
3161
            layerHandler->handleFailed(layer);
3162 3163 3164
        }
        else
        {
S
Smirnov Egor 已提交
3165
            throw;
3166
        }
3167
    }
3168 3169
}

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

3172
void TFLayerHandler::fillRegistry(const tensorflow::GraphDef& net)
S
Smirnov Egor 已提交
3173
{
3174 3175
    for (int li = 0; li < net.node_size(); li++) {
        const tensorflow::NodeDef& layer = net.node(li);
S
Smirnov Egor 已提交
3176

3177 3178 3179 3180 3181 3182
        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 已提交
3183
    }
3184 3185
    printMissing();
};
S
Smirnov Egor 已提交
3186

3187
bool TFLayerHandler::handleMissing(const tensorflow::NodeDef& layer)
S
Smirnov Egor 已提交
3188
{
3189
    bool unsupported = contains(layer.op());
S
Smirnov Egor 已提交
3190

3191
    if (unsupported)
S
Smirnov Egor 已提交
3192
    {
3193
        handleFailed(layer);
S
Smirnov Egor 已提交
3194 3195
    }

3196 3197
    return unsupported;
}
S
Smirnov Egor 已提交
3198

3199 3200 3201 3202 3203 3204 3205 3206 3207 3208
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 已提交
3209 3210
}

3211 3212 3213 3214
} // namespace

#endif //HAVE_PROTOBUF

3215
Net readNetFromTensorflow(const String &model, const String &config)
3216
{
3217
    return detail::readNetDiagnostic<TFImporter>(model.c_str(), config.c_str());
3218
}
3219

3220 3221 3222
Net readNetFromTensorflow(const char* bufferModel, size_t lenModel,
                          const char* bufferConfig, size_t lenConfig)
{
3223
    return detail::readNetDiagnostic<TFImporter>(bufferModel, lenModel, bufferConfig, lenConfig);
3224 3225
}

3226
Net readNetFromTensorflow(const std::vector<uchar>& bufferModel, const std::vector<uchar>& bufferConfig)
3227
{
3228 3229 3230 3231 3232
    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());
3233 3234
}

3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263
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();
}

3264
CV__DNN_INLINE_NS_END
3265
}} // namespace