tf_importer.cpp 49.7 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"

A
Alexander Alekhin 已提交
14
#ifdef HAVE_PROTOBUF
15 16 17 18 19 20 21 22 23 24
#include "graph.pb.h"

#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include <google/protobuf/message.h>
#include <google/protobuf/text_format.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include "tf_io.hpp"
25 26 27 28 29 30 31
#endif

namespace cv {
namespace dnn {
CV__DNN_EXPERIMENTAL_NS_BEGIN

#if HAVE_PROTOBUF
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65

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
{

static int toNCHW[] = {0, 2, 3, 1};

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();
66 67 68
        if (n)
        {
            shape.resize(n);
69

70 71 72 73 74
            for (i = 0; i < n; i++)
                shape[i] = (int)_shape.dim(i).size();
        }
        else
            shape.resize(1, 1);  // Scalar.
75 76 77 78 79 80 81
    }
    else
    {
        CV_Error(Error::StsError, "Unknown shape of input tensor");
    }
}

82 83 84 85 86 87
static Mat getTensorContent(const tensorflow::TensorProto &tensor)
{
    std::string content = tensor.tensor_content();
    switch (tensor.dtype())
    {
        case tensorflow::DT_FLOAT:
88 89 90 91 92 93 94 95 96 97
        {
            if (!content.empty())
                return Mat(1, content.size() / sizeof(float), CV_32FC1, (void*)content.c_str()).clone();
            else
            {
                const RepeatedField<float>& field = tensor.float_val();
                CV_Assert(!field.empty());
                return Mat(1, field.size(), CV_32FC1, (void*)field.data()).clone();
            }
        }
98
        case tensorflow::DT_DOUBLE:
99 100 101 102 103 104 105 106 107 108
        {
            if (!content.empty())
                return Mat(1, content.size() / sizeof(double), CV_64FC1, (void*)content.c_str()).clone();
            else
            {
                const RepeatedField<double>& field = tensor.double_val();
                CV_Assert(!field.empty());
                return Mat(1, field.size(), CV_64FC1, (void*)field.data()).clone();
            }
        }
109
        case tensorflow::DT_INT32:
110 111 112 113 114 115 116 117 118 119
        {
            if (!content.empty())
                return Mat(1, content.size() / sizeof(int32_t), CV_32SC1, (void*)content.c_str()).clone();
            else
            {
                const RepeatedField<int32_t>& field = tensor.int_val();
                CV_Assert(!field.empty());
                return Mat(1, field.size(), CV_32SC1, (void*)field.data()).clone();
            }
        }
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
        case tensorflow::DT_HALF:
        {
            Mat halfs;
            if (!content.empty())
            {
                static const int kHalfSize = 2;
                halfs = Mat(1, content.size() / kHalfSize, CV_16UC1, (void*)content.c_str());
            }
            else
            {
                const RepeatedField<int32_t>& field = tensor.half_val();
                CV_Assert(!field.empty());
                Mat ints(1, field.size(), CV_32SC1, (void*)field.data());
                ints.convertTo(halfs, CV_16UC1);
            }
            // Reinterpret as a signed shorts just for a convertFp16 call.
            Mat halfsSigned(halfs.size(), CV_16SC1, halfs.data);
            Mat floats(halfs.size(), CV_32FC1);
            convertFp16(halfsSigned, floats);
            return floats;
        }
        default:
            CV_Error(Error::StsError, "Tensor's data type is not supported");
            break;
    }
    return Mat();
}

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
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);

164 165
    Mat tensorContent = getTensorContent(tensor);
    int size = tensorContent.total();
166 167 168
    CV_Assert(size == (int)dstBlob.total());

    float *dstData = dstBlob.ptr<float>();
169
    const T *data = reinterpret_cast<const T*>(tensorContent.data);
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199

    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:
200
        case tensorflow::DT_HALF:
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
            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;
    }
}

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())
    {
238
    case tensorflow::DT_FLOAT:
239 240 241 242 243 244 245 246 247
        {
            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;
        }
248
    case tensorflow::DT_INT32:
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
        {
            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;
    }
}

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

void setStrides(LayerParams &layerParams, const tensorflow::NodeDef &layer)
{
    if (hasLayerAttr(layer, "strides"))
    {
        const tensorflow::AttrValue& val = getLayerAttr(layer, "strides");
        if (val.list().i_size() != 4 ||
            val.list().i(0) != 1 || val.list().i(3) != 1)
            CV_Error(Error::StsError, "Unsupported strides");
        layerParams.set("stride_h", static_cast<int>(val.list().i(1)));
        layerParams.set("stride_w", static_cast<int>(val.list().i(2)));
    }
}

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

324 325
    Mat values = getTensorContent(tensor);
    CV_Assert(values.type() == CV_32SC1);
326
    // TODO: add reordering shape if dims == 4
327
    return DictValue::arrayInt((int*)values.data, values.total());
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
}

void setKSize(LayerParams &layerParams, const tensorflow::NodeDef &layer)
{
    if (hasLayerAttr(layer, "ksize"))
    {
        const tensorflow::AttrValue& val = getLayerAttr(layer, "ksize");
        if (val.list().i_size() != 4 ||
            val.list().i(0) != 1 || val.list().i(3) != 1)
            CV_Error(Error::StsError, "Unsupported ksize");
        layerParams.set("kernel_h", static_cast<int>(val.list().i(1)));
        layerParams.set("kernel_w", static_cast<int>(val.list().i(2)));
    }
    else
    {
        layerParams.set("kernel_h", 1);
        layerParams.set("kernel_w", 1);
    }
}

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

void RemoveIdentityOps(tensorflow::GraphDef& net) {
    typedef std::map<String, String>  IdentityOpsMap;
    IdentityOpsMap identity_ops;

    std::vector<int> identity_ops_idx;

    int layersCount = net.node_size();
    for (int li = 0; li < layersCount; li++)
    {
        const tensorflow::NodeDef &layer = net.node(li);
        String type = layer.op();

366
        if (type == "Identity" || type == "Dropout") {
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
            identity_ops_idx.push_back(li);
            identity_ops[layer.name()] = layer.input(0);
        }
    }

    for (int li = 0; li < layersCount; li++)
    {
        tensorflow::NodeDef* layer = net.mutable_node(li);
        for (int input_id = 0; input_id < layer->input_size(); input_id++) {
            String input_op_name = layer->input(input_id);
            IdentityOpsMap::iterator it = identity_ops.find(input_op_name);

            if (it != identity_ops.end()) {
                layer->set_input(input_id, it->second);
            }
        }
    }

    std::sort(identity_ops_idx.begin(), identity_ops_idx.end());

    int removed_nodes = 0;
    for(size_t i = 0; i < identity_ops_idx.size(); i++) {
        int start_id = identity_ops_idx[i] - removed_nodes;
        net.mutable_node()->DeleteSubrange(start_id, 1);
        removed_nodes++;
    }
}

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

    size_t delimiter_pos = name.find_first_of(":");
    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);
}

D
Dmitry Kurtaev 已提交
449
class TFImporter {
450
public:
451
    TFImporter(const char *model, const char *config = NULL);
452 453 454
    TFImporter(const char *dataModel, size_t lenModel,
               const char *dataConfig = NULL, size_t lenConfig = 0);

455 456 457 458 459 460 461 462 463 464 465 466 467
    void populateNet(Net dstNet);

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


468 469 470 471 472 473
    // 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;
474 475
};

476
TFImporter::TFImporter(const char *model, const char *config)
477 478
{
    if (model && model[0])
479 480 481
        ReadTFNetParamsFromBinaryFileOrDie(model, &netBin);
    if (config && config[0])
        ReadTFNetParamsFromTextFileOrDie(config, &netTxt);
482 483
}

484 485 486 487 488 489 490 491 492
TFImporter::TFImporter(const char *dataModel, size_t lenModel,
                       const char *dataConfig, size_t lenConfig)
{
    if (dataModel != NULL && lenModel > 0)
        ReadTFNetParamsFromBinaryBufferOrDie(dataModel, lenModel, &netBin);
    if (dataConfig != NULL && lenConfig > 0)
        ReadTFNetParamsFromTextBufferOrDie(dataConfig, lenConfig, &netTxt);
}

493 494 495 496 497 498 499
void TFImporter::kernelFromTensor(const tensorflow::TensorProto &tensor, Mat &dstBlob)
{
    MatShape shape;
    blobShapeFromTensor(tensor, shape);
    int dims = (int)shape.size();

    // TODO: other blob types
500 501
    CV_Assert(tensor.dtype() == tensorflow::DT_FLOAT ||
              tensor.dtype() == tensorflow::DT_HALF);
502 503 504 505 506 507 508 509 510
    CV_Assert(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

    dstBlob.create(shape, CV_32F);

511 512
    Mat tensorContent = getTensorContent(tensor);
    int size = tensorContent.total();
513 514 515
    CV_Assert(size == (int)dstBlob.total());

    float *dstData = dstBlob.ptr<float>();
516
    const float *data = reinterpret_cast<const float*>(tensorContent.data);
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577

    int out_c = shape[0], input_c = shape[1], height = shape[2], width = shape[3];
    int total = out_c*input_c*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_h = 0; i_h < height; i_h++) {
                for(int i_w = 0; i_w < width; i_w++) {
                    int dst_i = input_c*height*width*i_oc + height*width*i_ic + width*i_h + i_w;
                    int src_i = 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);
    network.connect(it->second, outPin.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, "Const kernel input 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;
    }

578 579 580 581 582 583 584 585 586 587 588
    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(nodeIdx < netTxt.node_size(),
                  netTxt.node(nodeIdx).name() == kernel_inp.name);
        return netTxt.node(nodeIdx).attr().at("value").tensor();
    }
589 590
}

591 592
static void addConstNodes(const tensorflow::GraphDef& net, std::map<String, int>& const_layers,
                          std::set<String>& layers_to_ignore)
593
{
594
    for (int li = 0; li < net.node_size(); li++)
595 596 597 598 599 600 601 602 603 604
    {
        const tensorflow::NodeDef &layer = net.node(li);
        String name = layer.name();
        String type = layer.op();

        if (type != "Const")
            continue;  // only Const parameters are supported

        if (layer.attr().find("value") != layer.attr().end())
        {
605
            CV_Assert(const_layers.insert(std::make_pair(name, li)).second);
606
        }
607
        layers_to_ignore.insert(name);
608
    }
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
}

void TFImporter::populateNet(Net dstNet)
{
    RemoveIdentityOps(netBin);
    RemoveIdentityOps(netTxt);

    std::set<String> layers_to_ignore;

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

    int layersSize = net.node_size();

    // find all Const layers for params
    std::map<String, int> value_id;
    addConstNodes(netBin, value_id, layers_to_ignore);
    addConstNodes(netTxt, value_id, layers_to_ignore);
626 627 628 629 630

    std::map<String, int> layer_id;

    for (int li = 0; li < layersSize; li++)
    {
631
        tensorflow::NodeDef layer = net.node(li);
632 633 634 635
        String name = layer.name();
        String type = layer.op();
        LayerParams layerParams;

636
        if(layers_to_ignore.find(name) != layers_to_ignore.end())
637 638
            continue;

639
        if (type == "Conv2D" || type == "SpaceToBatchND" || type == "DepthwiseConv2dNative")
640
        {
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
            // The first node of dilated convolution subgraph.
            // Extract input node, dilation rate and paddings.
            std::string input = layer.input(0);
            if (type == "SpaceToBatchND")
            {
                // op: "SpaceToBatchND"
                // input: "input"
                // input: "SpaceToBatchND/block_shape"
                // input: "SpaceToBatchND/paddings"
                CV_Assert(layer.input_size() == 3);

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

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

                StrIntVector next_layers = getNextLayers(net, name, "Conv2D");
                CV_Assert(next_layers.size() == 1);
                layer = net.node(next_layers[0].second);
666
                layers_to_ignore.insert(next_layers[0].first);
667 668 669 670
                name = layer.name();
                type = layer.op();
            }

671 672 673 674 675 676 677 678 679 680 681 682
            layerParams.set("bias_term", false);
            layerParams.blobs.resize(1);

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

                int weights_layer_index = next_layers[0].second;

                blobFromTensor(getConstBlob(net.node(weights_layer_index), value_id), layerParams.blobs[1]);
                ExcludeLayer(net, weights_layer_index, 0, false);
683
                layers_to_ignore.insert(next_layers[0].first);
684 685 686
            }

            kernelFromTensor(getConstBlob(layer, value_id), layerParams.blobs[0]);
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
            int* kshape = layerParams.blobs[0].size.p;
            if (type == "DepthwiseConv2dNative")
            {
                const int chMultiplier = kshape[0];
                const int inCh = kshape[1];
                const int height = kshape[2];
                const int width = kshape[3];

                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];
                            }
706
                // TODO Use reshape instead
707 708
                kshape[0] = inCh * chMultiplier;
                kshape[1] = 1;
709 710
                size_t* kstep = layerParams.blobs[0].step.p;
                kstep[0] = kstep[1]; // fix steps too
711
            }
712 713 714 715 716 717 718
            layerParams.set("kernel_h", kshape[2]);
            layerParams.set("kernel_w", kshape[3]);
            layerParams.set("num_output", kshape[0]);

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

719 720 721 722 723 724 725
            // The final node of dilated convolution subgraph.
            next_layers = getNextLayers(net, name, "BatchToSpaceND");
            if (!next_layers.empty())
            {
                layerParams.set("pad_mode", "");  // We use padding values.
                CV_Assert(next_layers.size() == 1);
                ExcludeLayer(net, next_layers[0].second, 0, false);
726
                layers_to_ignore.insert(next_layers[0].first);
727 728
            }

729 730 731 732
            int id = dstNet.addLayer(name, "Convolution", layerParams);
            layer_id[name] = id;

            // one input only
733
            connect(layer_id, dstNet, parsePin(input), id, 0);
734 735 736
        }
        else if (type == "BiasAdd" || type == "Add")
        {
D
dkurt 已提交
737 738 739 740 741 742 743
            bool haveConst = false;
            for(int ii = 0; !haveConst && ii < layer.input_size(); ++ii)
            {
                Pin input = parsePin(layer.input(ii));
                haveConst = value_id.find(input.name) != value_id.end();
            }
            CV_Assert(!haveConst || layer.input_size() == 2);
744

D
dkurt 已提交
745 746 747 748
            if (haveConst)
            {
                layerParams.blobs.resize(1);
                blobFromTensor(getConstBlob(layer, value_id), layerParams.blobs[0]);
749

D
dkurt 已提交
750 751
                int id = dstNet.addLayer(name, "Shift", layerParams);
                layer_id[name] = id;
752

D
dkurt 已提交
753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
                // one input only
                connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
            }
            else
            {
                layerParams.set("operation", "sum");
                int id = dstNet.addLayer(name, "Eltwise", layerParams);
                layer_id[name] = id;

                for (int ii = 0; ii < layer.input_size(); 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);
                    dstNet.connect(layer_id.at(inp.name), inp.blobIndex, id, ii);
                }
            }
770 771 772 773 774 775 776 777 778
        }
        else if (type == "MatMul")
        {
            CV_Assert(layer.input_size() == 2);

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

            StrIntVector next_layers = getNextLayers(net, name, "BiasAdd");
779 780 781 782
            if (next_layers.empty())
            {
                next_layers = getNextLayers(net, name, "Add");
            }
783 784 785 786 787 788 789
            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);
790
                layers_to_ignore.insert(next_layers[0].first);
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
            }

            int kernel_blob_index = -1;
            blobFromTensor(getConstBlob(layer, value_id, -1, &kernel_blob_index), layerParams.blobs[0]);

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

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

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

            // one input only
            int input_blob_index = kernel_blob_index == 0 ? 1 : 0;
            connect(layer_id, dstNet, parsePin(layer.input(input_blob_index)), id, 0);
        }
        else if (type == "Reshape")
        {
            layerParams.set("dim", parseDims(getConstBlob(layer, value_id, 1)));

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

            // one input only
            connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
        }
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
        else if (type == "Flatten")
        {
            int id = dstNet.addLayer(name, "Flatten", layerParams);
            layer_id[name] = id;
            connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
        }
        else if (type == "Transpose")
        {
            Mat perm = getTensorContent(getConstBlob(layer, value_id, 1));
            CV_Assert(perm.type() == CV_32SC1);
            int* permData = (int*)perm.data;
            if (perm.total() == 4)
            {
                for (int i = 0; i < 4; ++i)
                    permData[i] = toNCHW[permData[i]];
            }
            layerParams.set("order", DictValue::arrayInt<int*>(permData, perm.total()));

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

            // one input only
            connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
        }
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
        else if (type == "Const")
        {
        }
        else if (type == "LRN")
        {
            if(hasLayerAttr(layer, "alpha")) {
                layerParams.set("alpha", getLayerAttr(layer, "alpha").f());
            }
            if(hasLayerAttr(layer, "beta")) {
                layerParams.set("beta", getLayerAttr(layer, "beta").f());
            }
            if(hasLayerAttr(layer, "depth_radius")) {
                int radius = (int)getLayerAttr(layer, "depth_radius").i();
                layerParams.set("local_size", 2*radius + 1);
            }
            if(hasLayerAttr(layer, "bias")) {
                layerParams.set("bias", getLayerAttr(layer, "bias").f());
            }
            layerParams.set("norm_by_size", false);

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

            connectToAllBlobs(layer_id, dstNet, parsePin(layer.input(0)), id, layer.input_size());
        }
D
dkurt 已提交
869
        else if (type == "Concat" || type == "ConcatV2")
870
        {
D
dkurt 已提交
871 872
            int axisId = (type == "Concat" ? 0 : layer.input_size() - 1);
            int axis = getConstBlob(layer, value_id, axisId).int_val().Get(0);
873
            layerParams.set("axis", 0 <= axis && axis < 4 ? toNCHW[axis] : axis);
874 875 876 877

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

D
dkurt 已提交
878 879 880 881 882 883

            int from = (type == "Concat" ? 1 : 0);
            int to = (type == "Concat" ? layer.input_size() : layer.input_size() - 1);

            // input(0) or input(n-1) is concat_dim
            for (int ii = from; ii < to; ii++)
884 885 886 887
            {
                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);
D
dkurt 已提交
888
                dstNet.connect(layer_id.at(inp.name), inp.blobIndex, id, ii - from);
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
            }
        }
        else if (type == "MaxPool")
        {
            layerParams.set("pool", "max");

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

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

            connectToAllBlobs(layer_id, dstNet, parsePin(layer.input(0)), id, layer.input_size());
        }
        else if (type == "AvgPool")
        {
            layerParams.set("pool", "ave");

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

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

            connectToAllBlobs(layer_id, dstNet, parsePin(layer.input(0)), id, layer.input_size());
        }
        else if (type == "Placeholder")
        {
            std::vector<String> netInputs(1);
            netInputs[0] = name;
            layer_id[name] = 0;
            dstNet.setInputsNames(netInputs);
        }
        else if (type == "Split") {
            // TODO: determing axis index remapping by input dimensions order of input blob
            // TODO: slicing input may be Const op
            // TODO: slicing kernels for convolutions - in current implenmentation it is impossible
            // TODO: add parsing num of slices parameter
            CV_Assert(layer.input_size() == 2);
            // num_split
            // 1st blob is dims tensor
            int axis = getConstBlob(layer, value_id, 0).int_val().Get(0);
            layerParams.set("axis", toNCHW[axis]);

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

            // one input only
            connect(layer_id, dstNet, parsePin(layer.input(1)), id, 0);
        }
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
        else if (type == "Slice")
        {
            // op: "Slice"
            // input: "input_node"
            // input: "Slice/begin"
            // input: "Slice/size"
            CV_Assert(layer.input_size() == 3);

            const tensorflow::TensorProto begins = getConstBlob(layer, value_id, 1);
            const tensorflow::TensorProto sizes = getConstBlob(layer, value_id, 2);
            std::string beginsData = begins.tensor_content();
            std::string sizesData = sizes.tensor_content();
            CV_Assert(begins.dtype() == tensorflow::DT_INT32);
            CV_Assert(sizes.dtype() == tensorflow::DT_INT32);
            CV_Assert(!beginsData.empty());
            CV_Assert(!sizesData.empty());
            CV_Assert(beginsData.size() == sizesData.size());

            layerParams.set("begin", DictValue::arrayInt((int*)beginsData.c_str(),
                                                         beginsData.size() / 4));
            layerParams.set("size", DictValue::arrayInt((int*)sizesData.c_str(),
                                                        sizesData.size() / 4));

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

            connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
        }
D
dkurt 已提交
969 970 971 972 973 974 975 976 977 978 979 980 981 982
        else if (type == "Mul")
        {
            bool haveConst = false;
            for(int ii = 0; !haveConst && ii < layer.input_size(); ++ii)
            {
                Pin input = parsePin(layer.input(ii));
                haveConst = value_id.find(input.name) != value_id.end();
            }
            CV_Assert(!haveConst || layer.input_size() == 2);

            if (haveConst)
            {
                // Multiplication by constant.
                CV_Assert(layer.input_size() == 2);
983 984
                Mat scaleMat = getTensorContent(getConstBlob(layer, value_id));
                CV_Assert(scaleMat.type() == CV_32FC1);
D
dkurt 已提交
985

986 987
                int id;
                if (scaleMat.total() == 1)  // is a scalar.
988
                {
989 990 991 992 993 994
                    layerParams.set("scale", scaleMat.at<float>(0));
                    id = dstNet.addLayer(name, "Power", layerParams);
                }
                else  // is a vector
                {
                    layerParams.blobs.resize(1, scaleMat);
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007

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

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

1008
                    id = dstNet.addLayer(name, "Scale", layerParams);
1009
                }
D
dkurt 已提交
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
                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
            {
                layerParams.set("operation", "prod");
                int id = dstNet.addLayer(name, "Eltwise", layerParams);
                layer_id[name] = id;

                for (int ii = 0; ii < layer.input_size(); 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);
                    dstNet.connect(layer_id.at(inp.name), inp.blobIndex, id, ii);
                }
            }
        }
        else if (type == "Pad")
        {
D
Dmitry Kurtaev 已提交
1036 1037 1038
            Mat paddings = getTensorContent(getConstBlob(layer, value_id, 1));
            CV_Assert(paddings.type() == CV_32SC1);
            if (paddings.total() == 8)
D
dkurt 已提交
1039
            {
D
Dmitry Kurtaev 已提交
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
                // Perhabs, we have NHWC padding dimensions order.
                //  N    H    W    C
                // 0 1  2 3  4 5  6 7
                std::swap(*paddings.ptr<int32_t>(0, 2), *paddings.ptr<int32_t>(0, 6));
                std::swap(*paddings.ptr<int32_t>(0, 3), *paddings.ptr<int32_t>(0, 7));
                //  N    C    W    H
                // 0 1  2 3  4 5  6 7
                std::swap(*paddings.ptr<int32_t>(0, 4), *paddings.ptr<int32_t>(0, 6));
                std::swap(*paddings.ptr<int32_t>(0, 5), *paddings.ptr<int32_t>(0, 7));
                //  N    C    H    W
                // 0 1  2 3  4 5  6 7
D
dkurt 已提交
1051
            }
D
Dmitry Kurtaev 已提交
1052 1053 1054 1055 1056 1057
            layerParams.set("paddings", DictValue::arrayInt<int*>((int*)paddings.data, paddings.total()));

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

            connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
D
dkurt 已提交
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
        }
        else if (type == "FusedBatchNorm")
        {
            // op: "FusedBatchNorm"
            // input: "input"
            // input: "BatchNorm/gamma"
            // input: "BatchNorm/beta"
            // input: "BatchNorm/moving_mean"
            // input: "BatchNorm/moving_variance"
            if (layer.input_size() != 5)
                CV_Error(Error::StsNotImplemented,
                         "Expected gamma, beta, mean and std");

            layerParams.blobs.resize(4);
            // gamma
            blobFromTensor(getConstBlob(layer, value_id, 1), layerParams.blobs[2]);
            // beta
            blobFromTensor(getConstBlob(layer, value_id, 2), layerParams.blobs[3]);
            // mean
            blobFromTensor(getConstBlob(layer, value_id, 3), layerParams.blobs[0]);
            // std
            blobFromTensor(getConstBlob(layer, value_id, 4), layerParams.blobs[1]);

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

            layerParams.set("has_weight", true);
            layerParams.set("has_bias", true);

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

            // one input only
            connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
        }
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
        else if (type == "Conv2DBackpropInput")
        {
            // op: "Conv2DBackpropInput"
            // input: "conv2d_transpose/output_shape"
            // input: "weights"
            // input: "input"
            if (layer.input_size() != 3)
                CV_Error(Error::StsNotImplemented,
                         "Expected output shape, weights and input nodes");

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

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

                int weights_layer_index = next_layers[0].second;

                blobFromTensor(getConstBlob(net.node(weights_layer_index), value_id), layerParams.blobs[1]);
                ExcludeLayer(net, weights_layer_index, 0, false);
1116
                layers_to_ignore.insert(next_layers[0].first);
1117 1118 1119 1120 1121 1122 1123
            }

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

            const int* kshape = layerParams.blobs[0].size.p;
            layerParams.set("kernel_h", kshape[2]);
            layerParams.set("kernel_w", kshape[3]);
1124
            layerParams.set("num_output", kshape[1]);
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134

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

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

            // one input only
            connect(layer_id, dstNet, parsePin(layer.input(2)), id, 0);
        }
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
        else if (type == "BlockLSTM")
        {
            // op: "BlockLSTM"
            // input: "lstm_block_wrapper/ToInt64/x"  (ignore, number of time stamps)
            // input: "input"
            // input: "lstm_block_wrapper/zeros"      (ignore)
            // input: "lstm_block_wrapper/zeros"      (ignore)
            // input: "lstm_block_wrapper/kernel"
            // input: "lstm_block_wrapper/w_i_diag"
            // input: "lstm_block_wrapper/w_f_diag"
            // input: "lstm_block_wrapper/w_o_diag"
            // input: "lstm_block_wrapper/bias"
            if (layer.input_size() != 9)
                CV_Error(Error::StsNotImplemented, "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)
                {
                    layerParams.set("use_cell_clip", true);
                    layerParams.set("cell_clip", cellClip);
                }
            }

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

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

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

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

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

            // one input only
            connect(layer_id, dstNet, parsePin(layer.input(1)), id, 0);
        }
D
Dmitry Kurtaev 已提交
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
        else if (type == "ResizeNearestNeighbor")
        {
            Mat outSize = getTensorContent(getConstBlob(layer, value_id, 1));
            CV_Assert(outSize.type() == CV_32SC1, outSize.total() == 2);

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

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

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

            connect(layer_id, dstNet, parsePin(layer.input(0)), id, 0);
        }
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
        else if (type == "PriorBox")
        {
            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, "variance"))
            {
                Mat variance = getTensorContent(getLayerAttr(layer, "variance").tensor());
                layerParams.set("variance",
                                DictValue::arrayReal<float*>((float*)variance.data, variance.total()));
            }
            if (hasLayerAttr(layer, "aspect_ratio"))
            {
                Mat aspectRatios = getTensorContent(getLayerAttr(layer, "aspect_ratio").tensor());
                layerParams.set("aspect_ratio",
                               DictValue::arrayReal<float*>((float*)aspectRatios.data, aspectRatios.total()));
            }
            if (hasLayerAttr(layer, "scales"))
            {
                Mat scales = getTensorContent(getLayerAttr(layer, "scales").tensor());
                layerParams.set("scales",
                               DictValue::arrayReal<float*>((float*)scales.data, scales.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);
        }
        else if (type == "DetectionOutput")
        {
            // op: "DetectionOutput"
            // input_0: "locations"
            // input_1: "classifications"
            // input_2: "prior_boxes"
            if (hasLayerAttr(layer, "num_classes"))
                layerParams.set("num_classes", getLayerAttr(layer, "num_classes").i());
            if (hasLayerAttr(layer, "share_location"))
                layerParams.set("share_location", getLayerAttr(layer, "share_location").b());
            if (hasLayerAttr(layer, "background_label_id"))
                layerParams.set("background_label_id", getLayerAttr(layer, "background_label_id").i());
            if (hasLayerAttr(layer, "nms_threshold"))
                layerParams.set("nms_threshold", getLayerAttr(layer, "nms_threshold").f());
            if (hasLayerAttr(layer, "top_k"))
                layerParams.set("top_k", getLayerAttr(layer, "top_k").i());
            if (hasLayerAttr(layer, "code_type"))
                layerParams.set("code_type", getLayerAttr(layer, "code_type").s());
            if (hasLayerAttr(layer, "keep_top_k"))
                layerParams.set("keep_top_k", getLayerAttr(layer, "keep_top_k").i());
            if (hasLayerAttr(layer, "confidence_threshold"))
                layerParams.set("confidence_threshold", getLayerAttr(layer, "confidence_threshold").f());
            if (hasLayerAttr(layer, "loc_pred_transposed"))
                layerParams.set("loc_pred_transposed", getLayerAttr(layer, "loc_pred_transposed").b());

            int id = dstNet.addLayer(name, "DetectionOutput", layerParams);
            layer_id[name] = id;
            for (int i = 0; i < 3; ++i)
                connect(layer_id, dstNet, parsePin(layer.input(i)), id, i);
        }
D
dkurt 已提交
1292 1293
        else if (type == "Abs" || type == "Tanh" || type == "Sigmoid" ||
                 type == "Relu" || type == "Elu" || type == "Softmax" ||
1294
                 type == "Identity" || type == "Relu6")
D
dkurt 已提交
1295 1296 1297 1298 1299
        {
            std::string dnnType = type;
            if (type == "Abs") dnnType = "AbsVal";
            else if (type == "Tanh") dnnType = "TanH";
            else if (type == "Relu") dnnType = "ReLU";
1300
            else if (type == "Relu6") dnnType = "ReLU6";
D
dkurt 已提交
1301 1302 1303 1304 1305 1306
            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, layer.input_size());
        }
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
        else
        {
            printLayerAttr(layer);
            CV_Error_(Error::StsError, ("Unknown layer type %s in op %s", type.c_str(), name.c_str()));
        }
    }
}

} // namespace

#endif //HAVE_PROTOBUF

1319
Net readNetFromTensorflow(const String &model, const String &config)
1320
{
1321
    TFImporter importer(model.c_str(), config.c_str());
1322
    Net net;
1323
    importer.populateNet(net);
1324 1325
    return net;
}
1326

1327 1328 1329 1330 1331 1332 1333 1334 1335
Net readNetFromTensorflow(const char* bufferModel, size_t lenModel,
                          const char* bufferConfig, size_t lenConfig)
{
    TFImporter importer(bufferModel, lenModel, bufferConfig, lenConfig);
    Net net;
    importer.populateNet(net);
    return net;
}

1336 1337
CV__DNN_EXPERIMENTAL_NS_END
}} // namespace