tf_importer.cpp 110.8 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 33 34 35
#endif

namespace cv {
namespace dnn {
CV__DNN_EXPERIMENTAL_NS_BEGIN

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

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

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

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

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

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

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

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

    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:
162
        case tensorflow::DT_HALF:
163 164 165 166 167 168 169 170 171 172 173
            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;
    }
}

174
#if 0
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
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())
    {
201
    case tensorflow::DT_FLOAT:
202 203 204 205 206 207 208 209 210
        {
            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;
        }
211
    case tensorflow::DT_INT32:
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
        {
            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;
    }
}
254
#endif
255 256 257 258 259 260 261 262 263 264 265 266

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

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

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

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

299 300 301 302 303 304 305 306 307 308
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 已提交
309
        if (inputs.at<int>(i) != 1 && inputs.at<int>(i) != -1)
310 311 312 313 314
            return false;
    }
    return true;
}

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

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

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

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

        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)));
        }
399 400 401 402 403 404 405 406
    }
    else
    {
        layerParams.set("kernel_h", 1);
        layerParams.set("kernel_w", 1);
    }
}

407
void setPadMode(LayerParams &layerParams, const tensorflow::NodeDef &layer)
408 409 410 411 412
{
    if (hasLayerAttr(layer, "padding"))
        layerParams.set("pad_mode", getLayerAttr(layer, "padding").s());
}

413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
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;
}

454 455 456 457
Pin parsePin(const std::string &name)
{
    Pin pin(name);

458
    size_t delimiter_pos = name.find_first_of(':');
459 460 461 462 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
    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);
}

508 509
class TFImporter
{
510
public:
511 512
    TFImporter(Net& net, const char *model, const char *config = NULL);
    TFImporter(Net& net, const char *dataModel, size_t lenModel,
513
               const char *dataConfig = NULL, size_t lenConfig = 0);
514 515 516
protected:
    Net& dstNet;
    void populateNet();
517

518 519 520
    void parseNode(const tensorflow::NodeDef& layer);

    DataLayout predictOutputDataLayout(const tensorflow::NodeDef& layer);
521 522 523 524 525 526 527 528 529 530 531

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


532 533 534 535 536 537
    // 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;
538 539

    std::vector<String> netInputsNames;
540
    std::vector<MatShape> netInputShapes;
541 542 543 544 545 546 547 548 549 550

    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;
551 552 553

private:
    void addPermuteLayer(const int* order, const std::string& permName, Pin& inpId);
554
    void setPadding(LayerParams &layerParams, const tensorflow::NodeDef &layer, std::string& inputName, float value = 0.);
R
rogday 已提交
555 556 557 558 559 560 561 562 563 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

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

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

596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
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");
}

R
rogday 已提交
621
const TFImporter::DispatchMap TFImporter::buildDispatchMap()
622
{
R
rogday 已提交
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
    static DispatchMap dispatch;
    dispatch["Conv2D"] = dispatch["SpaceToBatchND"] = dispatch["DepthwiseConv2dNative"] =
            dispatch["Pad"] = dispatch["MirrorPad"] = dispatch["Conv3D"] = &TFImporter::parseConvolution;
    dispatch["BiasAdd"] = dispatch["Add"] = dispatch["AddV2"] = dispatch["Sub"] = dispatch["AddN"] = &TFImporter::parseBias;
    dispatch["MatMul"] = &TFImporter::parseMatMul;
    dispatch["Reshape"] = &TFImporter::parseReshape;
    dispatch["Flatten"] = dispatch["Squeeze"] = &TFImporter::parseFlatten;
    dispatch["Transpose"] = &TFImporter::parseTranspose;
    dispatch["Const"] = &TFImporter::parseConstant;
    dispatch["LRN"] = &TFImporter::parseLrn;
    dispatch["Concat"] = dispatch["ConcatV2"] = &TFImporter::parseConcat;
    dispatch["MaxPool"] = dispatch["MaxPool3D"] = &TFImporter::parseMaxPool;
    dispatch["AvgPool"] = dispatch["AvgPool3D"] = &TFImporter::parseAvgPool;
    dispatch["MaxPoolGrad"] = &TFImporter::parseMaxPoolGrad;
    dispatch["Placeholder"] = &TFImporter::parsePlaceholder;
    dispatch["Split"] = &TFImporter::parseSplit;
    dispatch["Slice"] = &TFImporter::parseSlice;
    dispatch["StridedSlice"] = &TFImporter::parseStridedSlice;
    dispatch["Mul"] = dispatch["RealDiv"] = &TFImporter::parseMul;
    dispatch["FusedBatchNorm"] = dispatch["FusedBatchNormV3"] = &TFImporter::parseFusedBatchNorm;
    dispatch["Conv2DBackpropInput"] = &TFImporter::parseConv2DBackpropInput;
    dispatch["BlockLSTM"] = &TFImporter::parseBlockLSTM;
    dispatch["ResizeNearestNeighbor"] = dispatch["ResizeBilinear"] = dispatch["FusedResizeAndPadConv2D"] = &TFImporter::parseResize;
    dispatch["L2Normalize"] = &TFImporter::parseL2Normalize;
    dispatch["PriorBox"] = &TFImporter::parsePriorBox;
    dispatch["Softmax"] = &TFImporter::parseSoftmax;
    dispatch["CropAndResize"] = &TFImporter::parseCropAndResize;
S
Smirnov Egor 已提交
650
    dispatch["Mean"] = dispatch["Sum"] = dispatch["Max"] = &TFImporter::parseMean;
R
rogday 已提交
651 652 653 654 655 656 657
    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;

    return dispatch;
658 659
}

S
Smirnov Egor 已提交
660
// "Conv2D" "SpaceToBatchND" "DepthwiseConv2dNative" "Pad" "MirrorPad" "Conv3D"
R
rogday 已提交
661
void TFImporter::parseConvolution(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer_, LayerParams& layerParams)
662
{
R
rogday 已提交
663 664 665 666 667 668 669 670 671 672 673
    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")
674
    {
R
rogday 已提交
675 676 677
        next_layers = getNextLayers(net, name, "Conv2D");
        if (next_layers.empty())
            next_layers = getNextLayers(net, name, "DepthwiseConv2dNative");
678
    }
679

R
rogday 已提交
680
    if (type == "SpaceToBatchND")
681
    {
R
rogday 已提交
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
        // 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");
709
    }
R
rogday 已提交
710
    else if (type == "Pad" || type == "MirrorPad")
711
    {
R
rogday 已提交
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
        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
        }
728

R
rogday 已提交
729 730 731 732 733 734 735 736
        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");
737

R
rogday 已提交
738 739
            int id = dstNet.addLayer(name, "Padding", layerParams);
            layer_id[name] = id;
740

R
rogday 已提交
741 742 743 744 745 746 747
            connect(layer_id, dstNet, parsePin(input), id, 0);
            return;
        }
        else
        {
            // Merge with subsequent convolutional layer.
            CV_Assert(next_layers.size() == 1);
748

R
rogday 已提交
749 750 751 752 753 754 755 756 757 758 759
            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");
760 761 762
        }
    }

R
rogday 已提交
763 764 765 766 767 768
    // 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();
769

R
rogday 已提交
770 771
    layerParams.set("bias_term", false);
    layerParams.blobs.resize(1);
772

R
rogday 已提交
773 774 775 776
    next_layers = getNextLayers(net, name, "BiasAdd");
    if (next_layers.size() == 1) {
        layerParams.set("bias_term", true);
        layerParams.blobs.resize(2);
777

R
rogday 已提交
778
        int weights_layer_index = next_layers[0].second;
779

R
rogday 已提交
780 781 782 783 784 785 786 787 788 789 790 791 792
        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]);
793 794 795 796
            }
        }
    }

R
rogday 已提交
797 798 799 800 801
    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())
802
    {
R
rogday 已提交
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
        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];
846 847 848
    }
    else
    {
R
rogday 已提交
849
        layerParams.blobs[0] = sharedWeightsIt->second;
850
    }
R
rogday 已提交
851 852
    Mat weights = layerParams.blobs[0];
    layerParams.set("kernel_size",  DictValue::arrayInt(&weights.size[2], weights.dims - 2));
853

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

R
rogday 已提交
856 857
    setStrides(layerParams, layer);
    if (!layerParams.has("pad_w") && !layerParams.has("pad_h"))
858
        setPadding(layerParams, layer, input);
859

R
rogday 已提交
860 861 862 863 864 865 866 867
    // 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);
    }
868

R
rogday 已提交
869 870
    int id = dstNet.addLayer(name, "Convolution", layerParams);
    layer_id[name] = id;
871

R
rogday 已提交
872 873
    // one input only
    connect(layer_id, dstNet, parsePin(input), id, 0);
874 875


R
rogday 已提交
876 877 878
    if (getDataLayout(name, data_layouts) == DATA_LAYOUT_UNKNOWN)
        data_layouts[name] = DATA_LAYOUT_NHWC;
}
879

S
Smirnov Egor 已提交
880
// "BiasAdd" "Add" "AddV2" "Sub" "AddN"
R
rogday 已提交
881 882 883 884 885
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();
886

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

R
rogday 已提交
896 897 898 899 900 901
    if (haveConst)
    {
        Mat values = getTensorContent(getConstBlob(layer, value_id));
        CV_Assert(values.type() == CV_32FC1);
        if (type == "Sub")
            values *= -1.0f;
902

R
rogday 已提交
903 904 905 906 907
        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 已提交
908
        }
R
rogday 已提交
909
        else  // is a vector
910
        {
R
rogday 已提交
911 912 913 914 915 916
            layerParams.blobs.resize(1, values);
            id = dstNet.addLayer(name, "Shift", layerParams);
        }
        layer_id[name] = id;

        // one input only
917 918 919 920 921 922
        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 已提交
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
    }
    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);
942 943
        }
    }
944 945
}

R
rogday 已提交
946
void TFImporter::parseMatMul(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
947
{
R
rogday 已提交
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();

    CV_CheckEQ(num_inputs, 2, "");

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

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

    StrIntVector next_layers = getNextLayers(net, name, "BiasAdd");  // FIXIT Use layers fusion instead
    if (next_layers.empty())
965
    {
R
rogday 已提交
966
        next_layers = getNextLayers(net, name, "Add");
967
    }
R
rogday 已提交
968 969 970
    if (next_layers.size() == 1) {
        layerParams.set("bias_term", true);
        layerParams.blobs.resize(2);
D
Dmitry Kurtaev 已提交
971

R
rogday 已提交
972 973 974 975 976 977
        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)
978
        {
R
rogday 已提交
979 980 981 982
            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)
983
            {
R
rogday 已提交
984
                std::swap(biasData[i], biasData[i + 1]);
985 986 987
            }
        }
    }
988

R
rogday 已提交
989 990 991 992 993
    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())
994
    {
R
rogday 已提交
995 996 997
        blobFromTensor(kernelTensor, layerParams.blobs[0]);
        releaseTensor(const_cast<tensorflow::TensorProto*>(&kernelTensor));
        sharedWeights[kernelTensorName] = layerParams.blobs[0];
998
    }
D
Dmitry Kurtaev 已提交
999 1000
    else
    {
R
rogday 已提交
1001 1002
        layerParams.blobs[0] = sharedWeightsIt->second;
    }
1003

R
rogday 已提交
1004 1005 1006 1007
    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();
    }
1008

R
rogday 已提交
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
    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>());
        }
1019
    }
1020

R
rogday 已提交
1021 1022
    int id = dstNet.addLayer(name, "InnerProduct", layerParams);
    layer_id[name] = id;
1023

R
rogday 已提交
1024 1025 1026 1027 1028
    // 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;
}
1029

R
rogday 已提交
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
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())
1041
    {
R
rogday 已提交
1042 1043 1044 1045
        Mat newShape = getTensorContent(getConstBlob(layer, value_id, 1));
        int newShapeSize = newShape.total();
        bool hasSwap = false;
        if (newShapeSize == 4 && hasAllOnes(newShape, 0, 2))
1046
        {
R
rogday 已提交
1047 1048 1049 1050 1051 1052 1053 1054
            // 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)
1055
            {
R
rogday 已提交
1056 1057 1058
                int order[] = {0, 2, 3, 1};  // From OpenCV's NCHW to NHWC.
                addPermuteLayer(order, name + "/nhwc", inpId);
                if (newShapeSize < 4)
1059
                {
R
rogday 已提交
1060
                    inpLayout = DATA_LAYOUT_NCHW;
1061
                }
1062 1063
                else
                {
R
rogday 已提交
1064
                    inpLayout = DATA_LAYOUT_NHWC;
1065 1066 1067
                }
            }
        }
R
rogday 已提交
1068
        layerParams.set("dim", DictValue::arrayInt<int*>(newShape.ptr<int>(), newShapeSize));
1069

R
rogday 已提交
1070 1071
        int id = dstNet.addLayer(name, "Reshape", layerParams);
        layer_id[name] = id;
1072

R
rogday 已提交
1073 1074 1075
        // one input only
        connect(layer_id, dstNet, inpId, id, 0);
        inpId = Pin(name);
1076

R
rogday 已提交
1077 1078 1079 1080 1081 1082 1083
        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;
        }
1084

R
rogday 已提交
1085
        data_layouts[name] = newShapeSize == 2 ? DATA_LAYOUT_PLANAR : inpLayout;
1086
    }
R
rogday 已提交
1087
    else
1088
    {
R
rogday 已提交
1089 1090 1091 1092 1093
        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;
1094 1095 1096
    }
}

S
Smirnov Egor 已提交
1097
// "Flatten" "Squeeze"
R
rogday 已提交
1098
void TFImporter::parseFlatten(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
1099
{
R
rogday 已提交
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
    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;
1148 1149
}

R
rogday 已提交
1150
void TFImporter::parseTranspose(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
1151
{
R
rogday 已提交
1152 1153 1154 1155 1156 1157 1158 1159
    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)
1160
    {
R
rogday 已提交
1161 1162 1163 1164 1165
        // 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)
1166
        {
R
rogday 已提交
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
            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.");
1190
        }
R
rogday 已提交
1191
        else if (inpLayout == DATA_LAYOUT_NCHW)
1192
        {
R
rogday 已提交
1193
            if (permData[0] == 0 && permData[1] == 2 && permData[2] == 3 && permData[3] == 1)
1194
            {
R
rogday 已提交
1195 1196 1197
                // in TensorFlow: NCHW->NHWC
                // in OpenCV: NCHW->NCHW
                data_layouts[name] = DATA_LAYOUT_NHWC;
1198
            }
R
rogday 已提交
1199
            else if (permData[0] == 0 && permData[1] == 1 && permData[2] == 2 && permData[3] == 3)
1200
            {
R
rogday 已提交
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
                // 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()));
1215

R
rogday 已提交
1216 1217
        int id = dstNet.addLayer(name, "Permute", layerParams);
        layer_id[name] = id;
1218

R
rogday 已提交
1219 1220 1221 1222 1223
        // one input only
        connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
        data_layouts[name] = DATA_LAYOUT_UNKNOWN;
    }
}
1224

R
rogday 已提交
1225 1226 1227
void TFImporter::parseConstant(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
}
1228

R
rogday 已提交
1229 1230 1231 1232
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();
1233

R
rogday 已提交
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
    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);
1249

R
rogday 已提交
1250 1251
    int id = dstNet.addLayer(name, "LRN", layerParams);
    layer_id[name] = id;
1252

R
rogday 已提交
1253 1254
    connectToAllBlobs(layer_id, dstNet, parsePin(layer.input(0)), id, num_inputs);
}
1255

S
Smirnov Egor 已提交
1256
// "Concat" "ConcatV2"
R
rogday 已提交
1257 1258 1259 1260 1261
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();
1262

R
rogday 已提交
1263 1264 1265
    CV_CheckGT(num_inputs, 0, "");
    int axisId = (type == "Concat" ? 0 : num_inputs - 1);
    int axis = getConstBlob(layer, value_id, axisId).int_val().Get(0);
1266

R
rogday 已提交
1267 1268 1269 1270 1271
    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);
1272

R
rogday 已提交
1273 1274 1275
    // input(0) or input(n-1) is concat_dim
    int from = (type == "Concat" ? 1 : 0);
    int to = (type == "Concat" ? num_inputs : num_inputs - 1);
1276

R
rogday 已提交
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
    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;
        }
    }
1294

R
rogday 已提交
1295 1296
    int id = dstNet.addLayer(name, "Concat", layerParams);
    layer_id[name] = id;
1297

R
rogday 已提交
1298 1299 1300 1301 1302 1303 1304 1305
    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);
    }
}
1306

S
Smirnov Egor 已提交
1307
// "MaxPool" "MaxPool3D"
R
rogday 已提交
1308 1309 1310 1311
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();
1312
    std::string inputName = layer.input(0);
1313

R
rogday 已提交
1314 1315
    CV_CheckGT(num_inputs, 0, "");
    layerParams.set("pool", "max");
1316

R
rogday 已提交
1317 1318
    setKSize(layerParams, layer);
    setStrides(layerParams, layer);
1319
    setPadding(layerParams, layer, inputName, -std::numeric_limits<float>::infinity());
R
rogday 已提交
1320 1321
    // Test_TensorFlow_nets.EAST_text_detection/1, NGRAPH/CPU
    layerParams.set("ceil_mode", false);
1322

R
rogday 已提交
1323 1324
    int id = dstNet.addLayer(name, "Pooling", layerParams);
    layer_id[name] = id;
1325

1326
    connectToAllBlobs(layer_id, dstNet, parsePin(inputName), id, num_inputs);
R
rogday 已提交
1327
}
1328

S
Smirnov Egor 已提交
1329
// "AvgPool" "AvgPool3D"
R
rogday 已提交
1330 1331 1332 1333
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();
1334

R
rogday 已提交
1335 1336 1337 1338 1339
    CV_CheckGT(num_inputs, 0, "");
    layerParams.set("pool", "ave");
    layerParams.set("ave_pool_padded_area", false);
    setKSize(layerParams, layer);
    setStrides(layerParams, layer);
1340
    setPadMode(layerParams, layer);
1341

R
rogday 已提交
1342 1343
    int id = dstNet.addLayer(name, "Pooling", layerParams);
    layer_id[name] = id;
1344

R
rogday 已提交
1345 1346
    connectToAllBlobs(layer_id, dstNet, parsePin(layer.input(0)), id, num_inputs);
}
1347

R
rogday 已提交
1348 1349 1350 1351
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();
1352

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

R
rogday 已提交
1355 1356 1357 1358 1359 1360
    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);
1361

R
rogday 已提交
1362 1363
    int id = dstNet.addLayer(name, "MaxUnpool", layerParams);
    layer_id[name] = id;
1364

R
rogday 已提交
1365 1366 1367 1368
    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);
}
1369

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

R
rogday 已提交
1374
    DataLayout predictedLayout = data_layouts[name];
D
dkurt 已提交
1375

R
rogday 已提交
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
    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;
1402
        }
R
rogday 已提交
1403 1404
        bool hasNeg = false;
        for (int i = 0; i < dims.size() && !hasNeg; ++i)
1405
        {
R
rogday 已提交
1406 1407 1408 1409 1410 1411
            hasNeg = dims[i] < 0;
        }
        if (!hasNeg)
            netInputShapes.push_back(dims);
    }
}
1412

R
rogday 已提交
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
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);
}
1439

R
rogday 已提交
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
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()));
1466

R
rogday 已提交
1467 1468
    int id = dstNet.addLayer(name, "Slice", layerParams);
    layer_id[name] = id;
1469

R
rogday 已提交
1470 1471
    connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
}
1472

R
rogday 已提交
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
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()));
1509

R
rogday 已提交
1510 1511
    int id = dstNet.addLayer(name, "Slice", layerParams);
    layer_id[name] = id;
1512

R
rogday 已提交
1513 1514
    connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
}
1515

S
Smirnov Egor 已提交
1516
// "Mul" "RealDiv"
R
rogday 已提交
1517 1518 1519 1520 1521
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();
1522

R
rogday 已提交
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
    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));
1535

R
rogday 已提交
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
    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;
1547
        }
R
rogday 已提交
1548 1549 1550

        int id;
        if (scaleMat.total() == 1)  // is a scalar.
1551
        {
R
rogday 已提交
1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
            // 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())
1567
            {
R
rogday 已提交
1568
                int maximumLayerIdx = next_layers[0].second;
1569

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

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

R
rogday 已提交
1575 1576
                ExcludeLayer(net, maximumLayerIdx, mulInputIdx, false);
                layers_to_ignore.insert(next_layers[0].first);
1577

R
rogday 已提交
1578 1579
                layerParams.set("negative_slope", scaleMat.at<float>(0));
                id = dstNet.addLayer(name, "ReLU", layerParams);
1580
            }
1581
            else
D
Dmitry Kurtaev 已提交
1582
            {
R
rogday 已提交
1583 1584 1585
                // Just a multiplication.
                layerParams.set("scale", scaleMat.at<float>(0));
                id = dstNet.addLayer(name, "Power", layerParams);
D
Dmitry Kurtaev 已提交
1586
            }
1587
        }
R
rogday 已提交
1588
        else  // is a vector
1589
        {
R
rogday 已提交
1590 1591 1592 1593
            layerParams.blobs.resize(1, scaleMat);

            StrIntVector next_layers = getNextLayers(net, name, "Add");
            if (!next_layers.empty())
1594
            {
R
rogday 已提交
1595 1596
                layerParams.set("bias_term", true);
                layerParams.blobs.resize(2);
1597

R
rogday 已提交
1598 1599 1600 1601
                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);
1602
            }
R
rogday 已提交
1603 1604 1605 1606 1607

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

            id = dstNet.addLayer(name, "Scale", layerParams);
1608
        }
R
rogday 已提交
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
        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++)
1625
        {
R
rogday 已提交
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
            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)
1637
            {
R
rogday 已提交
1638
                outShape0 = outShape;
1639
            }
R
rogday 已提交
1640
            else if (outShape != outShape0)
1641
            {
R
rogday 已提交
1642 1643 1644 1645
                equalInpShapes = false;
                isShapeOnes = isAllOnes(outShape, 2, outShape.size()) ||
                              isAllOnes(outShape0, 2, outShape0.size());
                break;
1646
            }
1647
        }
R
rogday 已提交
1648 1649 1650

        int id;
        if (equalInpShapes || netInputShapes.empty() || (!equalInpShapes && isShapeOnes))
1651
        {
R
rogday 已提交
1652 1653
            layerParams.set("operation", type == "RealDiv" ? "div" : "prod");
            id = dstNet.addLayer(name, "Eltwise", layerParams);
1654
        }
R
rogday 已提交
1655
        else
1656
        {
R
rogday 已提交
1657 1658 1659 1660
            if (type == "RealDiv")
                CV_Error(Error::StsNotImplemented, "Division of non equal tensors");
            id = dstNet.addLayer(name, "Scale", layerParams);
        }
1661

R
rogday 已提交
1662
        layer_id[name] = id;
1663

R
rogday 已提交
1664
        for (int ii = 0; ii < num_inputs; ii++)
1665
        {
R
rogday 已提交
1666 1667 1668 1669 1670 1671 1672
            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);
        }
    }
}
1673

S
Smirnov Egor 已提交
1674
// "FusedBatchNorm" "FusedBatchNormV3"
R
rogday 已提交
1675 1676 1677 1678 1679 1680 1681 1682
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"
1683

R
rogday 已提交
1684 1685
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();
D
dkurt 已提交
1686

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

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

R
rogday 已提交
1692
    layerParams.blobs.resize(2);
1693

R
rogday 已提交
1694 1695 1696 1697 1698 1699 1700 1701 1702
    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);
1703

R
rogday 已提交
1704 1705 1706 1707 1708 1709 1710 1711 1712
    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);
1713

R
rogday 已提交
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738
    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;
1739

R
rogday 已提交
1740 1741
    if (hasLayerAttr(layer, "epsilon"))
        layerParams.set("eps", getLayerAttr(layer, "epsilon").f());
1742

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

R
rogday 已提交
1746 1747 1748
    // one input only
    connect(layer_id, dstNet, inpId, id, 0);
}
G
gal0is 已提交
1749

R
rogday 已提交
1750 1751 1752 1753 1754 1755
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 已提交
1756

1757
    std::string name = layer.name();
R
rogday 已提交
1758
    const int num_inputs = layer.input_size();
1759

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

R
rogday 已提交
1762 1763
    layerParams.set("bias_term", false);
    layerParams.blobs.resize(1);
D
Dmitry Kurtaev 已提交
1764

R
rogday 已提交
1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787
    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);
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
    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 已提交
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818

    // 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));
1819 1820 1821
    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 已提交
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
    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);
1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
    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 已提交
1847 1848 1849 1850 1851 1852 1853
}

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"
1854 1855
    // input: "lstm_block_wrapper/zeros"
    // input: "lstm_block_wrapper/zeros"
R
rogday 已提交
1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
    // 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 已提交
1875
        {
R
rogday 已提交
1876 1877 1878 1879
            layerParams.set("use_cell_clip", true);
            layerParams.set("cell_clip", cellClip);
        }
    }
D
Dmitry Kurtaev 已提交
1880

1881
    Mat W, Wh, Wx, b, cs_prev, h_prev;
R
rogday 已提交
1882 1883
    blobFromTensor(getConstBlob(layer, value_id, 4), W);
    blobFromTensor(getConstBlob(layer, value_id, 8), b);
1884 1885
    blobFromTensor(getConstBlob(layer, value_id, 2), cs_prev);
    blobFromTensor(getConstBlob(layer, value_id, 3), h_prev);
R
rogday 已提交
1886
    const int outSize = W.cols / 4;
1887

R
rogday 已提交
1888 1889 1890 1891 1892 1893 1894 1895 1896
    // 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]);
1897
        }
R
rogday 已提交
1898 1899 1900
    Wx = W.rowRange(0, W.rows - outSize).t();
    Wh = W.rowRange(W.rows - outSize, W.rows).t();

1901
    layerParams.blobs.resize(5);
R
rogday 已提交
1902 1903 1904
    layerParams.blobs[0] = Wh;
    layerParams.blobs[1] = Wx;
    layerParams.blobs[2] = b;
1905 1906
    layerParams.blobs[3] = h_prev;
    layerParams.blobs[4] = cs_prev;
R
rogday 已提交
1907 1908 1909 1910 1911

    if (hasLayerAttr(layer, "use_peephole"))
    {
        bool usePeephole = getLayerAttr(layer, "use_peephole").b();
        if (usePeephole)
D
dkurt 已提交
1912
        {
R
rogday 已提交
1913
            layerParams.set("use_peephole", true);
1914
            layerParams.blobs.resize(8);
R
rogday 已提交
1915
            for (int i = 0; i < 3; ++i)
D
dkurt 已提交
1916
            {
R
rogday 已提交
1917 1918 1919 1920
                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.
1921
                layerParams.blobs[5 + i] = w;
D
dkurt 已提交
1922
            }
R
rogday 已提交
1923 1924
        }
    }
D
dkurt 已提交
1925

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

R
rogday 已提交
1929 1930 1931 1932
    // one input only
    connect(layer_id, dstNet, parsePin(layer.input(1)), id, 0);
    data_layouts[name] = DATA_LAYOUT_UNKNOWN;
}
1933

S
Smirnov Egor 已提交
1934
// "ResizeNearestNeighbor" "ResizeBilinear" "FusedResizeAndPadConv2D"
R
rogday 已提交
1935 1936 1937 1938 1939 1940
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();
1941

R
rogday 已提交
1942 1943 1944 1945 1946 1947 1948 1949 1950
    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");
1951

R
rogday 已提交
1952 1953
        Mat paddings = getTensorContent(getConstBlob(layer, value_id, 2));
        CV_CheckEQ(countNonZero(paddings), 0, "Unsupported mode");
1954

R
rogday 已提交
1955 1956 1957 1958
        convWeights = layer.input(3);
        layer.mutable_input()->DeleteSubrange(2, 2);  // FIXIT do NOT modify input model
        num_inputs = layer.input_size();
        name = name + "/resize";
1959

R
rogday 已提交
1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
        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, "");
1986

R
rogday 已提交
1987 1988 1989 1990
    if (type == "ResizeNearestNeighbor")
        layerParams.set("interpolation", "nearest");
    else
        layerParams.set("interpolation", "bilinear");
D
dkurt 已提交
1991

R
rogday 已提交
1992 1993
    if (hasLayerAttr(layer, "align_corners"))
        layerParams.set("align_corners", getLayerAttr(layer, "align_corners").b());
1994

R
rogday 已提交
1995 1996
    if (hasLayerAttr(layer, "half_pixel_centers"))
        layerParams.set("half_pixel_centers", getLayerAttr(layer, "half_pixel_centers").b());
1997

R
rogday 已提交
1998 1999
    int id = dstNet.addLayer(name, "Resize", layerParams);
    layer_id[name] = id;
2000

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

R
rogday 已提交
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013
    // 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 已提交
2014

R
rogday 已提交
2015 2016 2017 2018 2019
void TFImporter::parseL2Normalize(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    // op: "L2Normalize"
    // input: "input"
    // input: "reduction_indices" (axis)
2020

R
rogday 已提交
2021 2022
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();
D
dkurt 已提交
2023

R
rogday 已提交
2024 2025 2026
    CV_CheckEQ(num_inputs, 2, "");
    Mat reductionIndices = getTensorContent(getConstBlob(layer, value_id, 1));
    CV_Assert(reductionIndices.type() == CV_32SC1);
2027

R
rogday 已提交
2028 2029 2030 2031
    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 已提交
2032

R
rogday 已提交
2033 2034 2035 2036 2037 2038 2039 2040 2041
    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 已提交
2042

R
rogday 已提交
2043 2044 2045 2046
    int id = dstNet.addLayer(name, "Normalize", layerParams);
    layer_id[name] = id;
    connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
}
D
dkurt 已提交
2047

R
rogday 已提交
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
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]))
2072
        {
R
rogday 已提交
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
            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;
}
2084

R
rogday 已提交
2085 2086 2087 2088
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();
2089

R
rogday 已提交
2090 2091 2092
    CV_CheckGT(num_inputs, 0, "");
    if (hasLayerAttr(layer, "axis"))
        layerParams.set("axis", getLayerAttr(layer, "axis").i());
2093

R
rogday 已提交
2094 2095 2096 2097
    int id = dstNet.addLayer(name, "Softmax", layerParams);
    layer_id[name] = id;
    connectToAllBlobs(layer_id, dstNet, parsePin(layer.input(0)), id, num_inputs);
}
2098

R
rogday 已提交
2099 2100 2101 2102 2103 2104
void TFImporter::parseCropAndResize(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    // op: "CropAndResize"
    // input: "input"
    // input: "boxes"
    // input: "sizes"
2105

R
rogday 已提交
2106 2107 2108
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();
    CV_CheckEQ(num_inputs, 3, "");
2109

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

R
rogday 已提交
2113 2114
    layerParams.set("height", cropSize.at<int>(0));
    layerParams.set("width", cropSize.at<int>(1));
2115

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

R
rogday 已提交
2119 2120 2121
    connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
    connect(layer_id, dstNet, parsePin(layer.input(1)), id, 1);
}
2122

S
Smirnov Egor 已提交
2123
// "Mean" "Sum" "Max"
R
rogday 已提交
2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141
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 已提交
2142
    std::string pool_type = cv::toLowerCase(type);
R
rogday 已提交
2143

S
Smirnov Egor 已提交
2144 2145 2146 2147
    if (pool_type == "mean")
    {
        pool_type = "ave";
    }
R
rogday 已提交
2148 2149 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 2176 2177 2178 2179 2180 2181 2182 2183
    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 已提交
2184
        avgLp.set("pool", pool_type);
R
rogday 已提交
2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215
        // 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)
        {
            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;
        }
2216

R
rogday 已提交
2217 2218 2219 2220 2221 2222 2223 2224
        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 已提交
2225
            layerParams.set("pool", pool_type);
R
rogday 已提交
2226 2227 2228
            layerParams.set(axis == 2 ? "kernel_w" : "kernel_h", 1);
            layerParams.set(axis == 2 ? "global_pooling_h" : "global_pooling_w", true);
            int id = dstNet.addLayer(name, "Pooling", layerParams);
2229
            layer_id[name] = id;
R
rogday 已提交
2230
            connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
2231

R
rogday 已提交
2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249
            if (!keepDims)
            {
                // To keep correct order after squeeze dims we first need to change layout from NCHW to NHWC
                LayerParams permLP;
                int order[] = {0, 2, 3, 1};  // From OpenCV's NCHW to NHWC.
                std::string permName = name + "/nchw";
                Pin inpId = Pin(name);
                addPermuteLayer(order, permName, inpId);

                LayerParams squeezeLp;
                std::string squeezeName = name + "/squeeze";
                CV_Assert(layer_id.find(squeezeName) == layer_id.end());
                squeezeLp.set("axis", indices.at<int>(0));
                squeezeLp.set("end_axis", indices.at<int>(0) + 1);
                int squeezeId = dstNet.addLayer(squeezeName, "Flatten", squeezeLp);
                layer_id[squeezeName] = squeezeId;
                connect(layer_id, dstNet, Pin(permName), squeezeId, 0);
            }
2250
        }
R
rogday 已提交
2251
        else if (axis == 1)
D
Dmitry Kurtaev 已提交
2252
        {
R
rogday 已提交
2253 2254 2255
            int order[] = {0, 2, 3, 1};  // From OpenCV's NCHW to NHWC.
            Pin inpId = parsePin(layer.input(0));
            addPermuteLayer(order, name + "/nhwc", inpId);
2256

S
Smirnov Egor 已提交
2257
            layerParams.set("pool", pool_type);
R
rogday 已提交
2258 2259 2260 2261 2262
            layerParams.set("kernel_h", 1);
            layerParams.set("global_pooling_w", true);
            int id = dstNet.addLayer(name, "Pooling", layerParams);
            layer_id[name] = id;
            connect(layer_id, dstNet, inpId, id, 0);
2263

R
rogday 已提交
2264
            if (!keepDims)
D
David 已提交
2265
            {
R
rogday 已提交
2266 2267 2268 2269 2270 2271 2272 2273 2274
                LayerParams squeezeLp;
                std::string squeezeName = name + "/squeeze";
                CV_Assert(layer_id.find(squeezeName) == layer_id.end());
                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;
                connect(layer_id, dstNet, Pin(name), squeezeId, 0);
D
David 已提交
2275 2276
            }
            else
2277
            {
R
rogday 已提交
2278 2279 2280
                int order[] = {0, 3, 1, 2};  // From NHWC to OpenCV's NCHW.
                Pin inpId = parsePin(name);
                addPermuteLayer(order, name + "/nchw", inpId);
2281
            }
D
Dmitry Kurtaev 已提交
2282
        }
R
rogday 已提交
2283 2284 2285
    } 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 已提交
2286

S
Smirnov Egor 已提交
2287
        layerParams.set("pool", pool_type);
R
rogday 已提交
2288 2289 2290 2291 2292 2293
        layerParams.set("global_pooling", true);
        int id = dstNet.addLayer(name, "Pooling", layerParams);
        layer_id[name] = id;
        connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);

        if (!keepDims)
2294
        {
R
rogday 已提交
2295 2296 2297 2298 2299 2300
            LayerParams flattenLp;
            std::string flattenName = name + "/flatten";
            CV_Assert(layer_id.find(flattenName) == layer_id.end());
            int flattenId = dstNet.addLayer(flattenName, "Flatten", flattenLp);
            layer_id[flattenName] = flattenId;
            connect(layer_id, dstNet, Pin(name), flattenId, 0);
2301
        }
R
rogday 已提交
2302 2303
    }
}
2304

R
rogday 已提交
2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
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);
    }
2342

R
rogday 已提交
2343 2344 2345
    layerParams.set("axis", dim);
    int id = dstNet.addLayer(name, "Concat", layerParams);
    layer_id[name] = id;
2346

R
rogday 已提交
2347 2348 2349
    for (int li = 0; li < num; li++)
        dstNet.connect(reshape_ids[li], 0, id, li);
}
2350

R
rogday 已提交
2351 2352 2353 2354 2355 2356
void TFImporter::parseClipByValue(tensorflow::GraphDef& net, const tensorflow::NodeDef& layer, LayerParams& layerParams)
{
    // op: "ClipByValue"
    // input: "input"
    // input: "mix"
    // input: "max"
2357

R
rogday 已提交
2358 2359
    const std::string& name = layer.name();
    const int num_inputs = layer.input_size();
L
Liubov Batanina 已提交
2360

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

R
rogday 已提交
2363 2364 2365 2366
    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 已提交
2367

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

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

R
rogday 已提交
2374 2375
    connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
}
D
Dmitry Kurtaev 已提交
2376

R
rogday 已提交
2377 2378 2379 2380
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 已提交
2381

R
rogday 已提交
2382 2383 2384
    CV_CheckGT(num_inputs, 0, "");
    CV_Assert(hasLayerAttr(layer, "alpha"));
    layerParams.set("negative_slope", getLayerAttr(layer, "alpha").f());
D
Dmitry Kurtaev 已提交
2385

R
rogday 已提交
2386 2387 2388 2389
    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 已提交
2390

S
Smirnov Egor 已提交
2391
// "Abs" "Tanh" "Sigmoid" "Relu" "Elu" "Exp" "Identity" "Relu6"
R
rogday 已提交
2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409
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);
}
2410

R
rogday 已提交
2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440
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 已提交
2441
        {
R
rogday 已提交
2442 2443
            Mat blob = getTensorContent(getConstBlob(layer, value_id, i));
            layerParams.blobs.push_back(blob);
D
dkurt 已提交
2444
        }
2445
        else
R
rogday 已提交
2446 2447 2448 2449
            inputsNames.push_back(layer.input(i));
    }
    int id = dstNet.addLayer(name, type, layerParams);
    layer_id[name] = id;
2450

R
rogday 已提交
2451 2452 2453 2454 2455
    for (int i = 0; i < inputsNames.size(); ++i)
    {
        connect(layer_id, dstNet, parsePin(inputsNames[i]), id, i);
    }
}
2456

R
rogday 已提交
2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469
TFImporter::TFImporter(Net& net, const char *model, const char *config)
    : dstNet(net), dispatch(buildDispatchMap())
{
    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);
    }
2470

R
rogday 已提交
2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 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 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 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 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892
    populateNet();
}

TFImporter::TFImporter(
        Net& net,
        const char *dataModel, size_t lenModel,
        const char *dataConfig, size_t lenConfig
)
    : dstNet(net), dispatch(buildDispatchMap())
{
    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);

    Mat tensorContent = getTensorContent(tensor, /*no copy*/false);
    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()
{
    CV_Assert(netBin.ByteSize() || netTxt.ByteSize());

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

    if (netTxt.ByteSize())
    {
        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");
    }

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

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

    for (int li = 0; li < layersSize; li++)
    {
        const tensorflow::NodeDef& layer = net.node(li);

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

        parseNode(layer);
    }

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

void TFImporter::addPermuteLayer(const int* order, const std::string& permName, Pin& inpId)
{
    LayerParams permLP;
    permLP.set("order", DictValue::arrayInt<const int*>(order, 4));
    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)
{
    tensorflow::GraphDef& net = netTxt.ByteSize() != 0 ? netTxt : netBin;

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

    try
    {
        LayerParams layerParams;

        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())
        {
2893
            CALL_MEMBER_FN(*this, iter->second)(net, layer, layerParams);
R
rogday 已提交
2894 2895 2896 2897
        }
        else
        {
            parseCustomLayer(net, layer, layerParams);
2898 2899
        }
    }
2900 2901 2902 2903 2904
    catch (const std::exception& e)
    {
        CV_LOG_ERROR(NULL, "DNN/TF: Can't parse layer for node='" << name << "'. Exception: " << e.what());
        throw;
    }
2905 2906 2907 2908 2909 2910
}

} // namespace

#endif //HAVE_PROTOBUF

2911
Net readNetFromTensorflow(const String &model, const String &config)
2912 2913
{
    Net net;
2914
    TFImporter importer(net, model.c_str(), config.c_str());
2915 2916
    return net;
}
2917

2918 2919 2920 2921
Net readNetFromTensorflow(const char* bufferModel, size_t lenModel,
                          const char* bufferConfig, size_t lenConfig)
{
    Net net;
2922
    TFImporter importer(net, bufferModel, lenModel, bufferConfig, lenConfig);
2923 2924 2925
    return net;
}

2926
Net readNetFromTensorflow(const std::vector<uchar>& bufferModel, const std::vector<uchar>& bufferConfig)
2927
{
2928 2929 2930 2931 2932
    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());
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
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();
}

2964 2965
CV__DNN_EXPERIMENTAL_NS_END
}} // namespace