Merge pull request #21372 from zihaomu:dnn_quantize_per_tensor
[platform/upstream/opencv.git] / modules / dnn / src / onnx / onnx_importer.cpp
1 // This file is part of OpenCV project.
2 // It is subject to the license terms in the LICENSE file found in the top-level directory
3 // of this distribution and at http://opencv.org/license.html.
4
5 // Copyright (C) 2018, Intel Corporation, all rights reserved.
6 // Third party copyrights are property of their respective owners.
7
8 #include "../precomp.hpp"
9 #include <opencv2/dnn/shape_utils.hpp>
10
11 #include <opencv2/dnn/layer_reg.private.hpp>
12
13 #include <opencv2/core/utils/fp_control_utils.hpp>
14
15 #include <opencv2/core/utils/logger.defines.hpp>
16 #undef CV_LOG_STRIP_LEVEL
17 #define CV_LOG_STRIP_LEVEL CV_LOG_LEVEL_VERBOSE + 1
18 #include <opencv2/core/utils/logger.hpp>
19
20 #include <opencv2/core/utils/configuration.private.hpp>
21
22
23 #ifdef HAVE_PROTOBUF
24
25 #include <iostream>
26 #include <fstream>
27 #include <string>
28 #include <limits>
29 #include <algorithm>
30
31 #if defined _MSC_VER && _MSC_VER < 1910/*MSVS 2017*/
32 #pragma warning(push)
33 #pragma warning(disable: 4503)  // decorated name length exceeded, name was truncated
34 #endif
35
36 #if defined(__GNUC__) && __GNUC__ >= 5
37 #pragma GCC diagnostic push
38 #pragma GCC diagnostic ignored "-Wsuggest-override"
39 #endif
40 #include "opencv-onnx.pb.h"
41 #if defined(__GNUC__) && __GNUC__ >= 5
42 #pragma GCC diagnostic pop
43 #endif
44
45 #include "onnx_graph_simplifier.hpp"
46
47 namespace cv {
48 namespace dnn {
49 CV__DNN_INLINE_NS_BEGIN
50
51 extern bool DNN_DIAGNOSTICS_RUN;
52
53 class ONNXLayerHandler;
54
55 class ONNXImporter
56 {
57     FPDenormalsIgnoreHintScope fp_denormals_ignore_scope;
58
59     opencv_onnx::ModelProto model_proto;
60     struct LayerInfo {
61         int layerId;
62         int outputId;
63         LayerInfo(int _layerId = 0, int _outputId = 0) : layerId(_layerId), outputId(_outputId) {}
64     };
65
66     std::map<std::string, Mat> getGraphTensors(
67                                     const opencv_onnx::GraphProto& graph_proto);
68     Mat getBlob(const opencv_onnx::NodeProto& node_proto, int index);
69     Mat getBlob(const std::string& input_name);
70
71     LayerParams getLayerParams(const opencv_onnx::NodeProto& node_proto);
72
73     void addConstant(const std::string& name, const Mat& blob);
74     void addLayer(LayerParams& layerParams,
75                   const opencv_onnx::NodeProto& node_proto);
76     void handleQuantizedNode(LayerParams& layerParams,
77                              const opencv_onnx::NodeProto& node_proto);
78
79     void expandMid(const std::string& prefix, opencv_onnx::NodeProto& node_proto,
80                    const std::string& input, size_t n);
81     void addNegation(const LayerParams& layerParams, opencv_onnx::NodeProto& node_proto, int input_id);
82     void lstm_extractConsts(LayerParams& layerParams, const opencv_onnx::NodeProto& lstm_proto, size_t idx, int* blobShape_, int size);
83     void lstm_add_reshape(const std::string& input_name, const std::string& output_name, int* layerShape, size_t n);
84     std::string lstm_add_slice(int index, const std::string& input_name, int* begin, int* end, size_t n);
85     std::string lstm_fix_dims(LayerParams& layerParams, const opencv_onnx::NodeProto& lstm_proto,
86                               int batch_size, int num_directions, int hidden_size, bool need_y, const std::string& y_name,
87                               const int index);
88     void lstm_add_transform(int num_directions, int batch_size, int hidden_size,
89                             int index, const std::string& input_name, const std::string& output_name);
90 public:
91     ONNXImporter(Net& net, const char *onnxFile);
92     ONNXImporter(Net& net, const char* buffer, size_t sizeBuffer);
93
94     void populateNet();
95
96 protected:
97     std::unique_ptr<ONNXLayerHandler> layerHandler;
98     Net& dstNet;
99
100     opencv_onnx::GraphProto graph_proto;
101     std::string framework_name;
102
103     std::map<std::string, Mat> constBlobs;
104
105     std::map<std::string, MatShape> outShapes;  // List of internal blobs shapes.
106     bool hasDynamicShapes;  // Whether the model has inputs with dynamic shapes
107     typedef std::map<std::string, MatShape>::iterator IterShape_t;
108
109     std::map<std::string, LayerInfo> layer_id;
110     typedef std::map<std::string, LayerInfo>::iterator IterLayerId_t;
111     typedef std::map<std::string, LayerInfo>::const_iterator ConstIterLayerId_t;
112
113     void handleNode(const opencv_onnx::NodeProto& node_proto);
114
115 private:
116     friend class ONNXLayerHandler;
117     typedef void (ONNXImporter::*ONNXImporterNodeParser)(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
118     typedef std::map<std::string, ONNXImporterNodeParser> DispatchMap;
119     typedef std::map<std::string, DispatchMap> DomainDispatchMap;
120
121     DomainDispatchMap domain_dispatch_map;
122     std::string getLayerTypeDomain(const opencv_onnx::NodeProto& node_proto);
123     const DispatchMap& getDispatchMap(const opencv_onnx::NodeProto& node_proto);
124     void buildDispatchMap_ONNX_AI(int opset_version);
125     void buildDispatchMap_COM_MICROSOFT(int opset_version);
126
127     // Domain: 'ai.onnx' (default)
128     // URL: https://github.com/onnx/onnx/blob/master/docs/Operators.md
129     void parseArg                  (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
130     void parseMaxUnpool            (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
131     void parseMaxPool              (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
132     void parseAveragePool          (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
133     void parseGlobalPool           (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
134     void parseReduce               (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
135     void parseSlice                (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
136     void parseSplit                (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
137     void parseBias                 (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
138     void parsePow                  (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
139     void parseMinMax               (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
140     void parseNeg                  (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
141     void parseConstant             (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
142     void parseLSTM                 (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
143     void parseGRU                  (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
144     void parseImageScaler          (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
145     void parseClip                 (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
146     void parseLeakyRelu            (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
147     void parseRelu                 (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
148     void parseElu                  (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
149     void parseTanh                 (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
150     void parseAbs                  (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
151     void parseCompare              (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
152     void parsePRelu                (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
153     void parseLRN                  (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
154     void parseInstanceNormalization(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
155     void parseBatchNormalization   (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
156     void parseGemm                 (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
157     void parseMatMul               (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
158     void parseMul                  (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
159     void parseConv                 (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
160     void parseConvTranspose        (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
161     void parseTranspose            (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
162     void parseSqueeze              (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
163     void parseFlatten              (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
164     void parseUnsqueeze            (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
165     void parseExpand               (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
166     void parseReshape              (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
167     void parsePad                  (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
168     void parseShape                (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
169     void parseCast                 (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
170     void parseConstantFill         (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
171     void parseGather               (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
172     void parseConcat               (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
173     void parseResize               (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
174     void parseUpsample             (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
175     void parseSoftMax              (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
176     void parseDetectionOutput      (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
177     void parseCumSum               (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
178     void parseDepthToSpace         (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
179     void parseSimpleLayers         (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
180
181     // Domain: com.microsoft
182     // URL: https://github.com/microsoft/onnxruntime/blob/master/docs/ContribOperators.md
183     void parseQuantDequant         (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
184     void parseQConv                (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
185     void parseQMatMul              (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
186     void parseQEltwise             (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
187     void parseQLeakyRelu           (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
188     void parseQSigmoid             (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
189     void parseQAvgPool             (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
190     void parseQConcat              (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
191
192     // '???' domain or '???' layer type
193     void parseCustomLayer          (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto);
194
195     int onnx_opset;  // OperatorSetIdProto for 'onnx' domain
196     std::map<std::string, int> onnx_opset_map;  // map from OperatorSetIdProto
197     void parseOperatorSet();
198
199     const std::string str_domain_ai_onnx = "ai.onnx";
200
201
202     bool useLegacyNames;
203     bool getParamUseLegacyNames()
204     {
205         bool param = utils::getConfigurationParameterBool("OPENCV_DNN_ONNX_USE_LEGACY_NAMES", false);
206         return param;
207     }
208     std::string extractNodeName(const opencv_onnx::NodeProto& node_proto);
209 };
210
211
212 class ONNXLayerHandler : public detail::LayerHandler
213 {
214 public:
215     explicit ONNXLayerHandler(ONNXImporter* importer_);
216
217     void fillRegistry(const opencv_onnx::GraphProto& net);
218
219 protected:
220     ONNXImporter* importer;
221 };
222
223 ONNXLayerHandler::ONNXLayerHandler(ONNXImporter* importer_) : importer(importer_){}
224
225 void ONNXLayerHandler::fillRegistry(const opencv_onnx::GraphProto &net)
226 {
227     int layersSize = net.node_size();
228     for (int li = 0; li < layersSize; li++) {
229         const opencv_onnx::NodeProto &node_proto = net.node(li);
230         const std::string& name = node_proto.output(0);
231         const std::string& type = node_proto.op_type();
232         const std::string& layer_type_domain = importer->getLayerTypeDomain(node_proto);
233         const auto& dispatch = importer->getDispatchMap(node_proto);
234         if (dispatch.find(type) == dispatch.end())
235         {
236             addMissing(name, cv::format("%s.%s", layer_type_domain.c_str(), type.c_str()));
237         }
238     }
239     printMissing();
240 }
241
242 ONNXImporter::ONNXImporter(Net& net, const char *onnxFile)
243     : layerHandler(DNN_DIAGNOSTICS_RUN ? new ONNXLayerHandler(this) : nullptr)
244     , dstNet(net)
245     , onnx_opset(0)
246     , useLegacyNames(getParamUseLegacyNames())
247 {
248     hasDynamicShapes = false;
249     CV_Assert(onnxFile);
250     CV_LOG_DEBUG(NULL, "DNN/ONNX: processing ONNX model from file: " << onnxFile);
251
252     std::fstream input(onnxFile, std::ios::in | std::ios::binary);
253     if (!input)
254     {
255         CV_Error(Error::StsBadArg, cv::format("Can't read ONNX file: %s", onnxFile));
256     }
257
258     if (!model_proto.ParseFromIstream(&input))
259     {
260         CV_Error(Error::StsUnsupportedFormat, cv::format("Failed to parse ONNX model: %s", onnxFile));
261     }
262
263     populateNet();
264 }
265
266 ONNXImporter::ONNXImporter(Net& net, const char* buffer, size_t sizeBuffer)
267     : layerHandler(DNN_DIAGNOSTICS_RUN ? new ONNXLayerHandler(this) : nullptr)
268     , dstNet(net)
269     , onnx_opset(0)
270     , useLegacyNames(getParamUseLegacyNames())
271 {
272     hasDynamicShapes = false;
273     CV_LOG_DEBUG(NULL, "DNN/ONNX: processing in-memory ONNX model (" << sizeBuffer << " bytes)");
274
275     struct _Buf : public std::streambuf
276             {
277         _Buf(const char* buffer, size_t sizeBuffer)
278         {
279             char* p = const_cast<char*>(buffer);
280             setg(p, p, p + sizeBuffer);
281         }
282             };
283
284     _Buf buf(buffer, sizeBuffer);
285     std::istream input(&buf);
286
287     if (!model_proto.ParseFromIstream(&input))
288         CV_Error(Error::StsUnsupportedFormat, "Failed to parse onnx model from in-memory byte array.");
289
290     populateNet();
291 }
292
293
294 inline void replaceLayerParam(LayerParams& layerParams, const String& oldKey, const String& newKey)
295 {
296     if (layerParams.has(oldKey)) {
297         layerParams.set(newKey, layerParams.get(oldKey));
298         layerParams.erase(oldKey);
299     }
300 }
301
302 static
303 void dumpValueInfoProto(int i, const opencv_onnx::ValueInfoProto& valueInfoProto, const std::string& prefix)
304 {
305     CV_Assert(valueInfoProto.has_name());
306     CV_Assert(valueInfoProto.has_type());
307     const opencv_onnx::TypeProto& typeProto = valueInfoProto.type();
308     CV_Assert(typeProto.has_tensor_type());
309     const opencv_onnx::TypeProto::Tensor& tensor = typeProto.tensor_type();
310     CV_Assert(tensor.has_shape());
311     const opencv_onnx::TensorShapeProto& tensorShape = tensor.shape();
312
313     int dim_size = tensorShape.dim_size();
314     CV_CheckGE(dim_size, 0, "");
315     MatShape shape(dim_size);
316     for (int j = 0; j < dim_size; ++j)
317     {
318         const opencv_onnx::TensorShapeProto_Dimension& dimension = tensorShape.dim(j);
319         if (dimension.has_dim_param())
320         {
321             CV_LOG_DEBUG(NULL, "DNN/ONNX: " << prefix << "[" << i << "] dim[" << j << "] = <" << dimension.dim_param() << "> (dynamic)");
322         }
323         // https://github.com/onnx/onnx/blob/master/docs/DimensionDenotation.md#denotation-definition
324         if (dimension.has_denotation())
325         {
326             CV_LOG_INFO(NULL, "DNN/ONNX: " << prefix << "[" << i << "] dim[" << j << "] denotation is '" << dimension.denotation() << "'");
327         }
328         shape[j] = dimension.dim_value();
329     }
330     CV_LOG_DEBUG(NULL, "DNN/ONNX: " << prefix << "[" << i << " as '" << valueInfoProto.name() << "'] shape=" << toString(shape));
331 }
332
333 static
334 void dumpTensorProto(int i, const opencv_onnx::TensorProto& tensorProto, const std::string& prefix)
335 {
336     if (utils::logging::getLogLevel() < utils::logging::LOG_LEVEL_VERBOSE)
337         return;
338     int dim_size = tensorProto.dims_size();
339     CV_CheckGE(dim_size, 0, "");
340     MatShape shape(dim_size);
341     for (int j = 0; j < dim_size; ++j)
342     {
343         int sz = static_cast<int>(tensorProto.dims(j));
344         shape[j] = sz;
345     }
346     CV_LOG_VERBOSE(NULL, 0, "DNN/ONNX: " << prefix << "[" << i << " as '" << tensorProto.name() << "'] shape=" << toString(shape) << " data_type=" << (int)tensorProto.data_type());
347 }
348
349 void releaseONNXTensor(opencv_onnx::TensorProto& tensor_proto)
350 {
351     if (!tensor_proto.raw_data().empty()) {
352         delete tensor_proto.release_raw_data();
353     }
354 }
355
356 void runLayer(LayerParams& params, const std::vector<Mat>& inputs,
357               std::vector<Mat>& outputs)
358 {
359     Ptr<Layer> layer = LayerFactory::createLayerInstance(params.type, params);
360     CV_Assert((bool)layer);
361
362     std::vector<MatShape> inpShapes(inputs.size());
363     int ddepth = params.get<int>("depth", CV_32F);
364     for (size_t i = 0; i < inputs.size(); ++i)
365     {
366         inpShapes[i] = shape(inputs[i]);
367         if (i > 0 && ddepth != inputs[i].depth())
368             CV_Error(Error::StsNotImplemented, "Mixed input data types.");
369         ddepth = inputs[i].depth();
370     }
371
372     std::vector<MatShape> outShapes, internalShapes;
373     layer->getMemoryShapes(inpShapes, 0, outShapes, internalShapes);
374
375     std::vector<Mat> internals(internalShapes.size());
376     outputs.resize(outShapes.size());
377     for (size_t i = 0; i < outShapes.size(); ++i)
378         outputs[i].create(outShapes[i], ddepth);
379     for (size_t i = 0; i < internalShapes.size(); ++i)
380         internals[i].create(internalShapes[i], ddepth);
381
382     layer->finalize(inputs, outputs);
383     layer->forward(inputs, outputs, internals);
384 }
385
386 std::map<std::string, Mat> ONNXImporter::getGraphTensors(
387                                         const opencv_onnx::GraphProto& graph_proto)
388 {
389     std::map<std::string, Mat> layers_weights;
390
391     for (int i = 0; i < graph_proto.initializer_size(); i++)
392     {
393         const opencv_onnx::TensorProto& tensor_proto = graph_proto.initializer(i);
394         dumpTensorProto(i, tensor_proto, "initializer");
395         Mat mat = getMatFromTensor(tensor_proto);
396         releaseONNXTensor(const_cast<opencv_onnx::TensorProto&>(tensor_proto));  // drop already loaded data
397
398         if (DNN_DIAGNOSTICS_RUN && mat.empty())
399             continue;
400
401         layers_weights.insert(std::make_pair(tensor_proto.name(), mat));
402     }
403     return layers_weights;
404 }
405
406 static DictValue parse(const ::google::protobuf::RepeatedField< ::google::protobuf::int64>& src) {
407     std::vector<int32_t> dst(src.size());
408     convertInt64ToInt32(src, dst, src.size());
409     return DictValue::arrayInt(&dst[0], src.size());
410 }
411
412 static DictValue parseStr(const ::google::protobuf::RepeatedPtrField< ::std::string>& src) {
413     return DictValue::arrayString(src.begin(), static_cast<int>(src.size()));
414 }
415
416 LayerParams ONNXImporter::getLayerParams(const opencv_onnx::NodeProto& node_proto)
417 {
418     LayerParams lp;
419     for(int i = 0; i < node_proto.attribute_size(); i++)
420     {
421         opencv_onnx::AttributeProto attribute_proto = node_proto.attribute(i);
422         std::string attribute_name = attribute_proto.name();
423
424         try
425         {
426             if(attribute_name == "kernel_shape")
427             {
428                 CV_Assert(attribute_proto.ints_size() == 1 || attribute_proto.ints_size() == 2 || attribute_proto.ints_size() == 3);
429                 lp.set("kernel_size", parse(attribute_proto.ints()));
430             }
431             else if(attribute_name == "strides")
432             {
433                 CV_Assert(attribute_proto.ints_size() == 1 || attribute_proto.ints_size() == 2 || attribute_proto.ints_size() == 3);
434                 lp.set("stride", parse(attribute_proto.ints()));
435             }
436             else if(attribute_name == "pads")
437             {
438                 if (node_proto.op_type() == "Pad")
439                 {
440                     // Padding layer.
441                     // Paddings are in order begin0, begin1, .. beginN, end0, end1, ..., endN.
442                     // We need to shuffle it to begin0, end0, begin1, end1, ...
443                     CV_Assert(attribute_proto.ints_size() % 2 == 0);
444                     const int dims = attribute_proto.ints_size() / 2;
445                     std::vector<int32_t> paddings;
446                     paddings.reserve(attribute_proto.ints_size());
447                     for (int i = 0; i < dims; ++i)
448                     {
449                         paddings.push_back(attribute_proto.ints(i));
450                         paddings.push_back(attribute_proto.ints(dims + i));
451                     }
452                     lp.set("paddings", DictValue::arrayInt(&paddings[0], paddings.size()));
453                 }
454                 else
455                 {
456                     // Convolution or pooling.
457                     CV_Assert(attribute_proto.ints_size() == 2 || attribute_proto.ints_size() == 4 || attribute_proto.ints_size() == 6);
458                     lp.set("pad", parse(attribute_proto.ints()));
459                 }
460             }
461             else if(attribute_name == "auto_pad")
462             {
463                 if (attribute_proto.s() == "SAME_UPPER" || attribute_proto.s() == "SAME_LOWER") {
464                     lp.set("pad_mode",  "SAME");
465                 }
466                 else if (attribute_proto.s() == "VALID") {
467                     lp.set("pad_mode", "VALID");
468                 }
469             }
470             else if(attribute_name == "dilations")
471             {
472                 CV_Assert(attribute_proto.ints_size() == 1 || attribute_proto.ints_size() == 2 || attribute_proto.ints_size() == 3);
473                 lp.set("dilation", parse(attribute_proto.ints()));
474             }
475             else if(attribute_name == "activations" && node_proto.op_type() == "LSTM")
476             {
477                 lp.set(attribute_name, parseStr(attribute_proto.strings()));
478             }
479             else if (attribute_proto.has_i())
480             {
481                 ::google::protobuf::int64 src = attribute_proto.i();
482                 if (src < std::numeric_limits<int32_t>::min() || src > std::numeric_limits<int32_t>::max())
483                     CV_Error(Error::StsOutOfRange, "Input is out of OpenCV 32S range");
484                 else
485                     lp.set(attribute_name, saturate_cast<int32_t>(src));
486             }
487             else if (attribute_proto.has_f())
488             {
489                 lp.set(attribute_name, attribute_proto.f());
490             }
491             else if (attribute_proto.has_s())
492             {
493                 lp.set(attribute_name, attribute_proto.s());
494             }
495             else if (attribute_proto.floats_size() > 0)
496             {
497                 lp.set(attribute_name, DictValue::arrayReal(
498                     attribute_proto.floats().data(), attribute_proto.floats_size()));
499             }
500             else if (attribute_proto.ints_size() > 0)
501             {
502                 lp.set(attribute_name, parse(attribute_proto.ints()));
503             }
504             else if (attribute_proto.has_t())
505             {
506                 opencv_onnx::TensorProto tensor = attribute_proto.t();
507                 Mat blob = getMatFromTensor(tensor);
508                 lp.blobs.push_back(blob);
509             }
510             else if (attribute_proto.has_g())
511             {
512                 CV_Error(Error::StsNotImplemented, cv::format("DNN/ONNX/Attribute[%s]: 'Graph' is not supported", attribute_name.c_str()));
513             }
514             else if (attribute_proto.graphs_size() > 0)
515             {
516                 CV_Error(Error::StsNotImplemented,
517                         cv::format("DNN/ONNX/Attribute[%s]: 'Graphs' (%d) in attributes is not supported",
518                                 attribute_name.c_str(), attribute_proto.graphs_size())
519                 );
520             }
521             else if (attribute_proto.strings_size() > 0)
522             {
523                 std::string msg = cv::format("DNN/ONNX/Attribute[%s]: 'Strings' (%d) are not supported",
524                         attribute_name.c_str(), attribute_proto.strings_size());
525                 CV_LOG_ERROR(NULL, msg);
526                 for (int i = 0; i < attribute_proto.strings_size(); i++)
527                 {
528                     CV_LOG_ERROR(NULL, "    Attribute[" << attribute_name << "].string(" << i << ") = '" << attribute_proto.strings(i) << "'");
529                 }
530                 CV_Error(Error::StsNotImplemented, msg);
531             }
532             else if (attribute_proto.tensors_size() > 0)
533             {
534                 CV_Error(Error::StsNotImplemented,
535                         cv::format("DNN/ONNX/Attribute[%s]: 'Tensors' (%d) in attributes are not supported",
536                                 attribute_name.c_str(), attribute_proto.tensors_size())
537                 );
538             }
539             else
540             {
541                 CV_Error(Error::StsNotImplemented, cv::format("DNN/ONNX/Attribute[%s]: unsupported attribute format", attribute_name.c_str()));
542             }
543         }
544         catch (const cv::Exception& e)
545         {
546             CV_UNUSED(e);
547             if (DNN_DIAGNOSTICS_RUN)
548             {
549                 CV_LOG_ERROR(NULL, "DNN/ONNX: Potential problem with processing attributes for node " << node_proto.name() << " Attribute " << attribute_name.c_str()
550                 );
551                 continue;
552             }
553             throw;
554         }
555     }
556     return lp;
557 }
558
559 Mat ONNXImporter::getBlob(const opencv_onnx::NodeProto& node_proto, int index)
560 {
561     CV_Assert(index < node_proto.input_size());
562     const std::string& input_name = node_proto.input(index);
563     return getBlob(input_name);
564 }
565
566 Mat ONNXImporter::getBlob(const std::string& input_name)
567 {
568     std::map<std::string, Mat>::const_iterator constBlob = constBlobs.find(input_name);
569     if (constBlob == constBlobs.end())
570     {
571         CV_Error(Error::StsBadArg, std::string("Blob ") + input_name + " not found in const blobs");
572     }
573     return constBlob->second;
574 }
575
576 void ONNXImporter::addLayer(LayerParams& layerParams,
577                             const opencv_onnx::NodeProto& node_proto)
578 {
579     int depth = layerParams.get<int>("depth", CV_32F);
580     int id = dstNet.addLayer(layerParams.name, layerParams.type, depth, layerParams);
581     for (int i = 0; i < node_proto.output_size(); ++i)
582     {
583         const std::string& output_name = node_proto.output(i);
584         if (!output_name.empty())
585         {
586             layer_id.insert(std::make_pair(output_name, LayerInfo(id, i)));
587         }
588     }
589
590     std::vector<MatShape> layerInpShapes, layerOutShapes, layerInternalShapes;
591     int inpNum = 0;
592     for (int j = 0; j < node_proto.input_size(); j++)
593     {
594         const std::string& input_name = node_proto.input(j);
595         IterLayerId_t layerId = layer_id.find(input_name);
596         if (layerId != layer_id.end()) {
597             dstNet.connect(layerId->second.layerId, layerId->second.outputId, id, inpNum);
598             ++inpNum;
599             // Collect input shapes.
600             IterShape_t shapeIt = outShapes.find(input_name);
601             CV_Assert(shapeIt != outShapes.end());
602             layerInpShapes.push_back(shapeIt->second);
603         }
604     }
605     // Compute shape of output blob for this layer.
606     Ptr<Layer> layer = dstNet.getLayer(id);  // FIXIT: avoid instantiation of layers during the import stage
607     layer->getMemoryShapes(layerInpShapes, 0, layerOutShapes, layerInternalShapes);
608     for (int i = 0; i < node_proto.output_size() && i < (int)layerOutShapes.size(); ++i)
609     {
610         const std::string& output_name = node_proto.output(i);
611         if (!output_name.empty())
612         {
613             outShapes[node_proto.output(i)] = layerOutShapes[i];
614         }
615     }
616 }
617
618 /** @brief Make N copies of input layer and set them as input to node_proto.
619  * @param prefix prefix of new layers' names
620  * @param node_proto node which will contain all copies as inputs
621  * @param input name of the node to copy
622  * @param n number of copies
623  */
624 void ONNXImporter::expandMid(const std::string& prefix, opencv_onnx::NodeProto& node_proto,
625                              const std::string& input, size_t n)
626 {
627     std::vector<std::string> input_names;
628     input_names.reserve(n);
629     for (size_t j = 0; j < n; j++)
630     {
631         LayerParams copyLP;
632         copyLP.name = format("%s/copy_%zu", prefix.c_str(), j);
633         copyLP.type = "Identity";
634         CV_Assert((layer_id.find(copyLP.name) == layer_id.end()) &&
635             "Couldn't copy the node: generated name already exists in the graph.");
636         input_names.push_back(copyLP.name);
637
638         node_proto.set_input(0, input);
639         node_proto.set_output(0, copyLP.name);
640         addLayer(copyLP, node_proto);
641     }
642     node_proto.clear_input();
643     for (size_t i = 0; i < input_names.size(); i++)
644     {
645         node_proto.add_input(input_names[i]);
646     }
647 }
648
649 /** @brief Multiply one of node_proto inputs by -1
650  * @param layerParams parameters of the node
651  * @param node_proto node which input will be replaced
652  * @param input_id id of input to be multiplied by -1
653  */
654 void ONNXImporter::addNegation(const LayerParams& layerParams, opencv_onnx::NodeProto& node_proto, int input_id)
655 {
656     LayerParams powerParams;
657     powerParams.name = layerParams.name + "/neg";
658     powerParams.type = "Power";
659     powerParams.set("scale", -1.f);
660
661     //Create Power layer
662     int id = dstNet.addLayer(powerParams.name, powerParams.type, powerParams);
663     //Connect to input
664     IterLayerId_t layerId = layer_id.find(node_proto.input(input_id));
665     CV_Assert(layerId != layer_id.end());
666     dstNet.connect(layerId->second.layerId, layerId->second.outputId, id, 0);
667     //Add shape
668     layer_id.insert(std::make_pair(powerParams.name, LayerInfo(id, 0)));
669     outShapes[powerParams.name] = outShapes[node_proto.input(input_id)];
670
671     //Replace input to Power
672     node_proto.set_input(input_id, powerParams.name);
673 }
674
675 void ONNXImporter::addConstant(const std::string& name, const Mat& blob)
676 {
677     CV_LOG_DEBUG(NULL, "DNN/ONNX: add constant '" << name << "' shape=" << toString(shape(blob)) << ": " << toString(blob));
678     constBlobs.insert(std::make_pair(name, blob));
679     outShapes.insert(std::make_pair(name, shape(blob)));
680 }
681
682 void ONNXImporter::parseOperatorSet()
683 {
684     int ir_version = model_proto.has_ir_version() ? static_cast<int>(model_proto.ir_version()) : -1;
685     if (ir_version < 3)
686         return;
687
688     int opset_size = model_proto.opset_import_size();
689     if (opset_size <= 0)
690     {
691         CV_LOG_INFO(NULL, "DNN/ONNX: missing opset information")
692         return;
693     }
694
695     for (int i = 0; i < opset_size; ++i)
696     {
697         const ::opencv_onnx::OperatorSetIdProto& opset_entry = model_proto.opset_import(i);
698         const std::string& domain = opset_entry.has_domain() ? opset_entry.domain() : std::string();
699         int version = opset_entry.has_version() ? opset_entry.version() : -1;
700         if (domain.empty() || domain == str_domain_ai_onnx)
701         {
702             // ONNX opset covered by specification: https://github.com/onnx/onnx/blob/master/docs/Operators.md
703             onnx_opset = std::max(onnx_opset, version);
704             onnx_opset_map[str_domain_ai_onnx] = onnx_opset;
705         }
706         else
707         {
708             CV_LOG_DEBUG(NULL, "DNN/ONNX: using non-standard ONNX opset[" << i << "]: domain='" << domain << "' version=" << version);
709             onnx_opset_map[domain] = onnx_opset;
710         }
711     }
712
713     CV_LOG_INFO(NULL, "DNN/ONNX: ONNX opset version = " << onnx_opset);
714
715     buildDispatchMap_ONNX_AI(onnx_opset);
716     for (const auto& pair : onnx_opset_map)
717     {
718         if (pair.first == str_domain_ai_onnx)
719         {
720             continue;  // done above
721         }
722         else if (pair.first == "com.microsoft")
723         {
724             buildDispatchMap_COM_MICROSOFT(pair.second);
725         }
726         else
727         {
728             CV_LOG_INFO(NULL, "DNN/ONNX: unknown domain='" << pair.first << "' version=" << pair.second << ". No dispatch map, you may need to register 'custom' layers.");
729         }
730     }
731 }
732
733 void ONNXImporter::handleQuantizedNode(LayerParams& layerParams,
734                                        const opencv_onnx::NodeProto& node_proto)
735 {
736     // Quantized nodes have output names ending with 'quantized'
737     std::string outName = node_proto.output(0);
738     int len = outName.length();
739     if (len <= 9)
740         return;
741
742     if (outName.substr(len - 9) == "quantized")
743     {
744         outName = outName.substr(0, len - 9);
745         Mat scale, zeropoint;
746
747         if (constBlobs.find(outName + "scale") != constBlobs.end() &&
748             constBlobs.find(outName + "zero_point") != constBlobs.end())
749         {
750             scale = getBlob(outName + "scale");
751             zeropoint = getBlob(outName + "zero_point");
752         }
753         else
754         {
755             std::string inpName = node_proto.input(0);
756             inpName = inpName.substr(0, inpName.length() - 9);
757             scale = getBlob(inpName + "scale");
758             zeropoint = getBlob(inpName + "zero_point");
759
760             for (int i = 0; i < node_proto.output_size(); i++)
761             {
762                 std::string out = node_proto.output(i);
763                 out = out.substr(0, out.length() - 9);
764                 addConstant(out + "scale", scale);
765                 addConstant(out + "zero_point", zeropoint);
766             }
767         }
768
769         if (scale.total() != 1 || zeropoint.total() != 1)
770             CV_Error(Error::StsNotImplemented, "Per-channel scales/zeropoints are not supported");
771
772         layerParams.set("depth", CV_8S);
773         layerParams.set("scales", DictValue::arrayReal(scale.ptr<float>(), 1));
774         layerParams.set("zeropoints", DictValue::arrayInt(zeropoint.ptr<int8_t>(), 1));
775     }
776 }
777
778 void ONNXImporter::populateNet()
779 {
780     CV_Assert(model_proto.has_graph());
781     graph_proto = model_proto.graph();
782
783     std::string framework_version;
784     if (model_proto.has_producer_name())
785         framework_name = model_proto.producer_name();
786     if (model_proto.has_producer_version())
787         framework_version = model_proto.producer_version();
788
789     CV_LOG_INFO(NULL, "DNN/ONNX: loading ONNX"
790             << (model_proto.has_ir_version() ? cv::format(" v%d", (int)model_proto.ir_version()) : cv::String())
791             << " model produced by '" << framework_name << "'"
792             << (framework_version.empty() ? cv::String() : cv::format(":%s", framework_version.c_str()))
793             << ". Number of nodes = " << graph_proto.node_size()
794             << ", initializers = " << graph_proto.initializer_size()
795             << ", inputs = " << graph_proto.input_size()
796             << ", outputs = " << graph_proto.output_size()
797             );
798
799     parseOperatorSet();
800
801     simplifySubgraphs(graph_proto);
802
803     const int layersSize = graph_proto.node_size();
804     CV_LOG_DEBUG(NULL, "DNN/ONNX: graph simplified to " << layersSize << " nodes");
805
806     constBlobs = getGraphTensors(graph_proto);  // scan GraphProto.initializer
807     std::vector<String> netInputs;  // map with network inputs (without const blobs)
808     // Add all the inputs shapes. It includes as constant blobs as network's inputs shapes.
809     for (int i = 0; i < graph_proto.input_size(); ++i)
810     {
811         const opencv_onnx::ValueInfoProto& valueInfoProto = graph_proto.input(i);
812         CV_Assert(valueInfoProto.has_name());
813         const std::string& name = valueInfoProto.name();
814         CV_Assert(valueInfoProto.has_type());
815         const opencv_onnx::TypeProto& typeProto = valueInfoProto.type();
816         CV_Assert(typeProto.has_tensor_type());
817         const opencv_onnx::TypeProto::Tensor& tensor = typeProto.tensor_type();
818         CV_Assert(tensor.has_shape());
819         const opencv_onnx::TensorShapeProto& tensorShape = tensor.shape();
820
821         int dim_size = tensorShape.dim_size();
822         CV_CheckGE(dim_size, 0, "");  // some inputs are scalars (dims=0), e.g. in Test_ONNX_nets.Resnet34_kinetics test
823         MatShape inpShape(dim_size);
824         for (int j = 0; j < dim_size; ++j)
825         {
826             const opencv_onnx::TensorShapeProto_Dimension& dimension = tensorShape.dim(j);
827             if (dimension.has_dim_param())
828             {
829                 CV_LOG_DEBUG(NULL, "DNN/ONNX: input[" << i << "] dim[" << j << "] = <" << dimension.dim_param() << "> (dynamic)");
830             }
831             // https://github.com/onnx/onnx/blob/master/docs/DimensionDenotation.md#denotation-definition
832             if (dimension.has_denotation())
833             {
834                 CV_LOG_INFO(NULL, "DNN/ONNX: input[" << i << "] dim[" << j << "] denotation is '" << dimension.denotation() << "'");
835             }
836             inpShape[j] = dimension.dim_value();
837             // NHW, NCHW(NHWC), NCDHW(NDHWC); do not set this flag if only N is dynamic
838             if (dimension.has_dim_param() && !(j == 0 && inpShape.size() >= 3))
839             {
840                 hasDynamicShapes = true;
841             }
842         }
843         bool isInitialized = ((constBlobs.find(name) != constBlobs.end()));
844         CV_LOG_IF_DEBUG(NULL, !isInitialized, "DNN/ONNX: input[" << i << " as '" << name << "'] shape=" << toString(inpShape));
845         CV_LOG_IF_VERBOSE(NULL, 0, isInitialized, "DNN/ONNX: pre-initialized input[" << i << " as '" << name << "'] shape=" << toString(inpShape));
846         if (dim_size > 0 && !hasDynamicShapes)  // FIXIT result is not reliable for models with multiple inputs
847         {
848             inpShape[0] = std::max(inpShape[0], 1); // It's OK to have undetermined batch size
849         }
850         outShapes[valueInfoProto.name()] = inpShape;
851         // fill map: push layer name, layer id and output id
852         if (!isInitialized)
853         {
854             netInputs.push_back(name);
855             layer_id.insert(std::make_pair(name, LayerInfo(0, netInputs.size() - 1)));
856         }
857     }
858
859     dstNet.setInputsNames(netInputs);
860
861     // dump outputs
862     for (int i = 0; i < graph_proto.output_size(); ++i)
863     {
864         dumpValueInfoProto(i, graph_proto.output(i), "output");
865     }
866
867     if (DNN_DIAGNOSTICS_RUN) {
868         CV_LOG_INFO(NULL, "DNN/ONNX: start diagnostic run!");
869         layerHandler->fillRegistry(graph_proto);
870     }
871
872     for(int li = 0; li < layersSize; li++)
873     {
874         const opencv_onnx::NodeProto& node_proto = graph_proto.node(li);
875         handleNode(node_proto);
876     }
877
878     // register outputs
879     for (int i = 0; i < graph_proto.output_size(); ++i)
880     {
881         const std::string& output_name = graph_proto.output(i).name();
882         if (output_name.empty())
883         {
884             CV_LOG_ERROR(NULL, "DNN/ONNX: can't register output without name: " << i);
885             continue;
886         }
887         ConstIterLayerId_t layerIt = layer_id.find(output_name);
888         if (layerIt == layer_id.end())
889         {
890             CV_LOG_ERROR(NULL, "DNN/ONNX: can't find layer for output name: '" << output_name << "'. Does model imported properly?");
891             continue;
892         }
893
894         const LayerInfo& li = layerIt->second;
895         int outputId = dstNet.registerOutput(output_name, li.layerId, li.outputId); CV_UNUSED(outputId);
896         // no need to duplicate message from engine: CV_LOG_DEBUG(NULL, "DNN/ONNX: registered output='" << output_name << "' with id=" << outputId);
897     }
898
899     CV_LOG_DEBUG(NULL, (DNN_DIAGNOSTICS_RUN ? "DNN/ONNX: diagnostic run completed!" : "DNN/ONNX: import completed!"));
900 }
901
902 std::string ONNXImporter::getLayerTypeDomain(const opencv_onnx::NodeProto& node_proto)
903 {
904     if (!node_proto.has_domain())
905         return str_domain_ai_onnx;
906     const std::string& domain = node_proto.domain();
907     if (domain.empty())
908         return str_domain_ai_onnx;
909     return domain;
910 }
911
912 const ONNXImporter::DispatchMap& ONNXImporter::getDispatchMap(const opencv_onnx::NodeProto& node_proto)
913 {
914     static DispatchMap empty_map;
915     const std::string& layer_type_domain = getLayerTypeDomain(node_proto);
916     auto it = domain_dispatch_map.find(layer_type_domain);
917     if (it == domain_dispatch_map.end())
918     {
919         return empty_map;
920     }
921
922     return it->second;
923 }
924
925 std::string ONNXImporter::extractNodeName(const opencv_onnx::NodeProto& node_proto)
926 {
927     // We need to rework DNN outputs API, this is a workaround for #21698
928     if (node_proto.has_name() && !node_proto.name().empty())
929     {
930         if (useLegacyNames)
931             return node_proto.name();
932         return cv::format("onnx_node!%s", node_proto.name().c_str());
933     }
934     for (int i = 0; i < node_proto.output_size(); ++i)
935     {
936         const std::string& name = node_proto.output(i);
937         // There are two ways to leave an optional input or output unspecified:
938         // the first, available only for trailing inputs and outputs, is to simply not provide that input;
939         // the second method is to use an empty string in place of an input or output name.
940         if (!name.empty())
941         {
942             if (useLegacyNames)
943                 return name.c_str();
944             return cv::format("onnx_node_output_%d!%s", i, name.c_str());
945         }
946     }
947     CV_Error(Error::StsAssert, "Couldn't deduce Node name.");
948 }
949
950 void ONNXImporter::handleNode(const opencv_onnx::NodeProto& node_proto)
951 {
952     CV_Assert(node_proto.output_size() >= 1);
953     const std::string& name = extractNodeName(node_proto);
954     const std::string& layer_type = node_proto.op_type();
955     const std::string& layer_type_domain = getLayerTypeDomain(node_proto);
956     const auto& dispatch = getDispatchMap(node_proto);
957
958     CV_LOG_DEBUG(NULL, "DNN/ONNX: processing node with " << node_proto.input_size() << " inputs and "
959                                                          << node_proto.output_size() << " outputs: "
960                                                          << cv::format("[%s]:(%s)", layer_type.c_str(), name.c_str())
961                                                          << cv::format(" from %sdomain='", onnx_opset_map.count(layer_type_domain) == 1 ? "" : "undeclared ")
962                                                          << layer_type_domain << "'"
963     );
964
965     if (dispatch.empty())
966     {
967         CV_LOG_WARNING(NULL, "DNN/ONNX: missing dispatch map for domain='" << layer_type_domain << "'");
968     }
969
970     LayerParams layerParams;
971     try
972     {
973         // FIXIT not all cases can be repacked into "LayerParams". Importer should handle such cases directly for each "layer_type"
974         layerParams = getLayerParams(node_proto);
975
976         layerParams.name = name;
977         layerParams.type = layer_type;
978         layerParams.set("has_dynamic_shapes", hasDynamicShapes);
979
980         handleQuantizedNode(layerParams, node_proto);
981
982         DispatchMap::const_iterator iter = dispatch.find(layer_type);
983         if (iter != dispatch.end())
984         {
985             CALL_MEMBER_FN(*this, iter->second)(layerParams, node_proto);
986         }
987         else
988         {
989             parseCustomLayer(layerParams, node_proto);
990         }
991     }
992     catch (const cv::Exception& e)
993     {
994         if (DNN_DIAGNOSTICS_RUN)
995         {
996             CV_LOG_ERROR(NULL, "DNN/ONNX: Potential problem during processing node with " << node_proto.input_size() << " inputs and " << node_proto.output_size() << " outputs: "
997                     << cv::format("[%s]:(%s)", layer_type.c_str(), name.c_str())
998                     << " from domain='" << layer_type_domain << "'"
999                     << "\n" << e.msg
1000             );
1001             cv::AutoLock lock(getLayerFactoryMutex());
1002             auto registeredLayers = getLayerFactoryImpl();
1003             if (registeredLayers.find(layerParams.type) != registeredLayers.end())
1004             {
1005                 try
1006                 {
1007                     Ptr<Layer> layer = LayerFactory::createLayerInstance(layerParams.type, layerParams);
1008                 }
1009                 catch (const std::exception& e)
1010                 {
1011                     CV_LOG_ERROR(NULL, "DNN/ONNX: Layer of type " << layerParams.type << "(" << layer_type << ") cannot be created with parameters " << layerParams << ". Error: " << e.what()
1012                     );
1013                 }
1014             }
1015         }
1016         else
1017         {
1018             CV_LOG_ERROR(NULL, "DNN/ONNX: ERROR during processing node with " << node_proto.input_size() << " inputs and " << node_proto.output_size() << " outputs: "
1019                     << cv::format("[%s]:(%s)", layer_type.c_str(), name.c_str())
1020                     << " from domain='" << layer_type_domain << "'"
1021             );
1022         }
1023         for (int i = 0; i < node_proto.input_size(); i++)
1024         {
1025             CV_LOG_INFO(NULL, "    Input[" << i << "] = '" << node_proto.input(i) << "'");
1026         }
1027         for (int i = 0; i < node_proto.output_size(); i++)
1028         {
1029             CV_LOG_INFO(NULL, "    Output[" << i << "] = '" << node_proto.output(i) << "'");
1030         }
1031         if (DNN_DIAGNOSTICS_RUN)
1032         {
1033             for (int i = 0; i < node_proto.output_size(); ++i)
1034             {
1035                 layer_id.insert(std::make_pair(node_proto.output(i), LayerInfo(0, i)));
1036                 outShapes[node_proto.output(i)] = outShapes[node_proto.input(0)];
1037             }
1038         }
1039         else
1040             CV_Error(Error::StsError, cv::format("Node [%s@%s]:(%s) parse error: %s", layer_type.c_str(), layer_type_domain.c_str(), name.c_str(), e.what()));
1041     }
1042 }
1043
1044 void ONNXImporter::parseArg(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
1045 {
1046     const std::string& layer_type = node_proto.op_type();
1047     layerParams.type = "Arg";
1048     layerParams.set("op", layer_type == "ArgMax" ? "max" : "min");
1049     addLayer(layerParams, node_proto);
1050 }
1051
1052 void setCeilMode(LayerParams& layerParams)
1053 {
1054     // auto_pad attribute is deprecated and uses ceil
1055     if (layerParams.has("pad_mode"))
1056     {
1057         layerParams.set("ceil_mode", true);
1058     }
1059     else if (!layerParams.has("ceil_mode"))
1060     {
1061         layerParams.set("ceil_mode", false);
1062     }
1063 }
1064
1065 void ONNXImporter::parseMaxUnpool(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
1066 {
1067     layerParams.type = "MaxUnpool";
1068
1069     DictValue kernel_shape = layerParams.get("kernel_size");
1070     CV_Assert(kernel_shape.size() == 2);
1071     layerParams.set("pool_k_w", kernel_shape.get<int>(0));
1072     layerParams.set("pool_k_h", kernel_shape.get<int>(1));
1073
1074     int pool_pad_w = 0, pool_pad_h = 0;
1075     if (layerParams.has("pad"))
1076     {
1077         DictValue pads = layerParams.get("pad");
1078         CV_CheckEQ(pads.size(), 2, "");
1079         pool_pad_w = pads.get<int>(0);
1080         pool_pad_h = pads.get<int>(1);
1081     }
1082     layerParams.set("pool_pad_w", pool_pad_w);
1083     layerParams.set("pool_pad_h", pool_pad_h);
1084
1085
1086     int pool_stride_w = 1, pool_stride_h = 1;
1087     if (layerParams.has("stride"))
1088     {
1089         DictValue strides = layerParams.get("stride");
1090         CV_CheckEQ(strides.size(), 2, "");
1091         pool_stride_w = strides.get<int>(0);
1092         pool_stride_h = strides.get<int>(1);
1093     }
1094     layerParams.set("pool_stride_w", pool_stride_w);
1095     layerParams.set("pool_stride_h", pool_stride_h);
1096
1097     addLayer(layerParams, node_proto);
1098 }
1099
1100 void ONNXImporter::parseMaxPool(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
1101 {
1102     int depth = layerParams.get<int>("depth", CV_32F);
1103     layerParams.type = (depth == CV_8S) ? "PoolingInt8" : "Pooling";
1104     layerParams.set("pool", "MAX");
1105     setCeilMode(layerParams);
1106     addLayer(layerParams, node_proto);
1107 }
1108
1109 void ONNXImporter::parseAveragePool(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
1110 {
1111     layerParams.type = "Pooling";
1112     layerParams.set("pool", "AVE");
1113     setCeilMode(layerParams);
1114     layerParams.set("ave_pool_padded_area", framework_name == "pytorch");
1115     addLayer(layerParams, node_proto);
1116 }
1117
1118 void ONNXImporter::parseGlobalPool(LayerParams &layerParams, const opencv_onnx::NodeProto &node_proto_)
1119 {
1120     opencv_onnx::NodeProto node_proto = node_proto_;
1121     const std::string& layer_type = node_proto.op_type();
1122     const std::string output_name = node_proto.output(0);
1123
1124     CV_Assert(node_proto.input_size() == 1);
1125     layerParams.type = "Pooling";
1126     String pool;
1127     if (layer_type == "GlobalMaxPool")
1128         pool = "MAX";
1129     else if (layer_type == "GlobalAveragePool")
1130         pool = "AVE";
1131     else
1132         CV_Error(Error::StsNotImplemented, "Unsupported Pooling type of " + layer_type + " operation.");
1133
1134     CV_Assert(!layerParams.has("axes"));
1135     layerParams.set("global_pooling", true);
1136     layerParams.set("pool", pool);
1137     addLayer(layerParams, node_proto);
1138 }
1139
1140 void ONNXImporter::parseReduce(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto_)
1141 {
1142     opencv_onnx::NodeProto node_proto = node_proto_;
1143     const std::string& layer_type = node_proto.op_type();
1144     const std::string output_name = node_proto.output(0);
1145     int depth = layerParams.get<int>("depth", CV_32F);
1146
1147     CV_Assert(node_proto.input_size() <= 2);
1148     String reduceType;
1149
1150     if (layer_type == "ReduceMax")
1151         reduceType = "MAX";
1152     else if (layer_type == "ReduceMin")
1153         reduceType = "MIN";
1154     else if (layer_type == "ReduceSum")
1155         reduceType = "SUM";
1156     else if (layer_type == "ReduceSumSquare")
1157         reduceType = "SUM_SQUARE";
1158     else if (layer_type == "ReduceProd")
1159         reduceType = "PROD";
1160     else if (layer_type == "ReduceL1")
1161         reduceType = "L1";
1162     else if (layer_type == "ReduceL2")
1163         reduceType = "L2";
1164     else if (layer_type == "ReduceLogSum")
1165         reduceType = "LOG_SUM";
1166     else if (layer_type == "ReduceLogSumExp")
1167         reduceType = "LOG_SUM_EXP";
1168     else if (layer_type == "ReduceMean")
1169         reduceType = "AVE";
1170     else
1171         CV_Error(Error::StsNotImplemented, "Unsupported Pooling type of " + layer_type + " operation.");
1172
1173     // The ReduceInt8 can only support "MAX" and "MIN".
1174     if (depth == CV_8S)
1175     {
1176         CV_Assert(reduceType == "MAX" || reduceType == "MIN");
1177     }
1178
1179     layerParams.type = (depth == CV_8S) ? "ReduceInt8" : "Reduce";
1180     layerParams.set("reduce", reduceType);
1181     bool keepdims = layerParams.get<int>("keepdims", 1) == 1;
1182
1183     if (layer_type == "ReduceSum" && node_proto.input_size() == 2)
1184     {
1185         // TODO support the opset 13 of ReduceSum.
1186         //  in opset 13, the ReduceSum has two input, it takes axes as input instead of attribute
1187         //  details:https://github.com/onnx/onnx/issues/3420#issuecomment-844295687
1188         CV_Error(Error::StsNotImplemented, "Unsupported " + layer_type + " operation of opset 13, please try to "
1189                                                                          "re-export the onnx model with opset 11.");
1190     }
1191
1192     MatShape inpShape = outShapes[node_proto.input(0)];
1193     std::vector<bool> shouldDelete(inpShape.size(), false);
1194
1195     if (layerParams.has("axes"))
1196     {
1197         DictValue axes = layerParams.get("axes");
1198         for (int i = 0; i < axes.size(); i++)
1199         {
1200             int axis = normalize_axis(axes.get<int>(i), inpShape.size());
1201             shouldDelete[axis] = true;
1202         }
1203     }
1204     else
1205     {
1206         for (int i = 0; i < inpShape.size(); i++)
1207         {
1208             shouldDelete[i] = true;
1209         }
1210     }
1211
1212     MatShape targetShape;
1213     for (int i = 0; i < inpShape.size(); ++i)
1214     {
1215         if (!shouldDelete[i])
1216         {
1217             targetShape.push_back(inpShape[i]);
1218         }
1219         else if (keepdims)
1220         {
1221             targetShape.push_back(1);
1222         }
1223     }
1224
1225     if (targetShape.empty())
1226         targetShape.push_back(1);
1227
1228     // Using PermuteLayer to move the deleted axis to the last.
1229     std::vector<int> perm(inpShape.size(), 0);
1230     for (int i = 0; i < inpShape.size(); i++)
1231         perm[i] = i;
1232
1233     bool needPermuet = false;
1234     for (int i = 0; i < inpShape.size(); i++)
1235     {
1236         if (shouldDelete[i])
1237         {
1238             // find the first not deleted element.
1239             std::vector<bool>::iterator iter = std::find(shouldDelete.begin() + i, shouldDelete.end(), false);
1240
1241             if (iter != shouldDelete.end())
1242             {
1243                 int index = iter - shouldDelete.begin();
1244
1245                 bool temp = shouldDelete[index];
1246                 shouldDelete[index] = shouldDelete[i];
1247                 shouldDelete[i] = temp;
1248
1249                 std::swap(perm[index], perm[i]);
1250                 std::swap(inpShape[index], inpShape[i]);
1251                 needPermuet = true;
1252             }
1253             else
1254                 break;
1255         }
1256     }
1257
1258     auto inputString= node_proto.input(0);
1259     if (needPermuet)
1260     {
1261         LayerParams permuteLp;
1262         permuteLp.name = layerParams.name + "/permute";
1263         permuteLp.type = (depth == CV_8S) ? "PermuteInt8" : "Permute";
1264         permuteLp.set("order", DictValue::arrayInt(perm.data(), perm.size()));
1265
1266         opencv_onnx::NodeProto protoPermute;
1267         protoPermute.add_input(inputString);
1268         protoPermute.add_output(permuteLp.name);
1269         addLayer(permuteLp, protoPermute);
1270         inputString = permuteLp.name;
1271     }
1272
1273     std::vector<int> deletedDims;
1274     for (int axis_i = 0; axis_i < inpShape.size(); ++axis_i)
1275     {
1276         if (shouldDelete[axis_i])
1277         {
1278             deletedDims.push_back(inpShape[axis_i]);
1279         }
1280     }
1281
1282     LayerParams reduceLp = layerParams;
1283     reduceLp.name = layerParams.name + "/reduce";
1284     CV_Assert(layer_id.find(reduceLp.name) == layer_id.end());
1285     reduceLp.set("deleted_dims", DictValue::arrayInt(&deletedDims[0], deletedDims.size()));
1286
1287     node_proto.set_input(0, inputString);
1288     node_proto.set_output(0, reduceLp.name);
1289     addLayer(reduceLp, node_proto);
1290
1291     layerParams.type = (depth == CV_8S) ? "ReshapeInt8" : "Reshape";
1292     layerParams.set("dim", DictValue::arrayInt(&targetShape[0], targetShape.size()));
1293
1294     node_proto.set_input(0, node_proto.output(0));
1295     node_proto.set_output(0, output_name);
1296
1297     addLayer(layerParams, node_proto);
1298 }
1299
1300 void ONNXImporter::parseSlice(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
1301 {
1302     int axis = 0;
1303     std::vector<int> begin;
1304     std::vector<int> end;
1305     std::vector<int> steps;
1306     int inp_size = node_proto.input_size();
1307
1308     if (inp_size == 1)
1309     {
1310         if (layerParams.has("axes")) {
1311             DictValue axes = layerParams.get("axes");
1312             for (int i = 1; i < axes.size(); ++i) {
1313                 CV_Assert(axes.get<int>(i - 1) == axes.get<int>(i) - 1);
1314             }
1315             axis = axes.get<int>(0);
1316         }
1317
1318         DictValue starts = layerParams.get("starts");
1319         DictValue ends = layerParams.get("ends");
1320         CV_Assert(starts.size() == ends.size());
1321
1322         if (axis > 0) {
1323             CV_CheckLE(axis, 1024, "Slice layer can't have more than 1024 axes"); // arbitrary limit
1324             begin.resize(axis, 0);
1325             end.resize(axis, INT_MAX);
1326         }
1327         for (int i = 0; i < starts.size(); ++i)
1328         {
1329             begin.push_back(starts.get<int>(i));
1330             end.push_back(ends.get<int>(i));
1331         }
1332     } else { // inp_size > 1
1333         CV_Assert(inp_size >= 3);
1334         for (int i = 1; i < inp_size; i++) {
1335             CV_Assert(constBlobs.find(node_proto.input(i)) != constBlobs.end());
1336         }
1337         Mat start_blob = getBlob(node_proto, 1);
1338         Mat end_blob   = getBlob(node_proto, 2);
1339         CV_Assert(start_blob.total() == end_blob.total());
1340
1341         if (inp_size > 3) {
1342             Mat axes_blob = getBlob(node_proto, 3);
1343             const int* axes = (int*)axes_blob.data;
1344             for (int i = 1; i < axes_blob.total(); ++i) {
1345                 CV_Assert(axes[i - 1] == axes[i] - 1);
1346             }
1347             axis = axes[0];
1348         }
1349
1350         const int* starts = start_blob.ptr<int>();
1351         const int* ends   = end_blob.ptr<int>();
1352         if (axis > 0) {
1353             begin.resize(axis, 0);
1354             end.resize(axis, INT_MAX);
1355         }
1356         std::copy(starts, starts + start_blob.total(), std::back_inserter(begin));
1357         std::copy(ends, ends + end_blob.total(), std::back_inserter(end));
1358
1359         if (inp_size == 5) {
1360             CV_Assert(constBlobs.find(node_proto.input(4)) != constBlobs.end());
1361             Mat step_blob = getBlob(node_proto, 4);
1362             const int* steps_ptr = step_blob.ptr<int>();
1363
1364             if (axis > 0)
1365                 steps.resize(axis, 1);
1366
1367             std::copy(steps_ptr, steps_ptr + step_blob.total(), std::back_inserter(steps));
1368
1369             // Very strange application for Slice op with tensor reversing.
1370             // We just workaround it for 2d constants.
1371             if (constBlobs.find(node_proto.input(0)) != constBlobs.end() &&
1372                 axis == 0 &&
1373                 start_blob.at<int>(0) == -1 && step_blob.at<int>(0) == -1 &&
1374                 end_blob.at<int>(0) == std::numeric_limits<int32_t>::min())
1375             {
1376                 Mat inp = getBlob(node_proto, 0);
1377                 if (inp.dims == 2)
1378                 {
1379                     Mat flipped;
1380                     flip(inp, flipped, 0);
1381                     addConstant(node_proto.output(0), flipped);
1382                     return;
1383                 }
1384             }
1385         }
1386     }
1387     layerParams.set("begin", DictValue::arrayInt(&begin[0], begin.size()));
1388     layerParams.set("end", DictValue::arrayInt(&end[0], end.size()));
1389     layerParams.set("axis", axis);
1390
1391     if (!steps.empty())
1392         layerParams.set("steps", DictValue::arrayInt(&steps[0], steps.size()));
1393
1394     if (constBlobs.find(node_proto.input(0)) != constBlobs.end())
1395     {
1396         Mat inp = getBlob(node_proto, 0);
1397         std::vector<Mat> inputs, sliced;
1398         inputs.push_back(inp);
1399         runLayer(layerParams, inputs, sliced);
1400         CV_Assert(sliced.size() == 1);
1401         addConstant(node_proto.output(0), sliced[0]);
1402         return;
1403     }
1404     addLayer(layerParams, node_proto);
1405 }
1406
1407 void ONNXImporter::parseSplit(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
1408 {
1409     if (layerParams.has("split"))
1410     {
1411         DictValue splits = layerParams.get("split");
1412         const int numSplits = splits.size();
1413         CV_Assert(numSplits > 1);
1414
1415         std::vector<int> slicePoints(numSplits - 1, splits.get<int>(0));
1416         for (int i = 1; i < splits.size() - 1; ++i)
1417         {
1418             slicePoints[i] = slicePoints[i - 1] + splits.get<int>(i);
1419         }
1420         layerParams.set("slice_point", DictValue::arrayInt(&slicePoints[0], slicePoints.size()));
1421     }
1422     else
1423     {
1424         layerParams.set("num_split", node_proto.output_size());
1425     }
1426     int depth = layerParams.get<int>("depth", CV_32F);
1427     layerParams.type = (depth == CV_8S) ? "SliceInt8" : "Slice";
1428     layerParams.set("axis", layerParams.get<float>("axis", 0));
1429     addLayer(layerParams, node_proto);
1430 }
1431
1432 void ONNXImporter::parseBias(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto_)
1433 {
1434     opencv_onnx::NodeProto node_proto = node_proto_;
1435     const std::string& layer_type = node_proto.op_type();
1436     bool isSub = layer_type == "Sub";
1437
1438     if (layer_type == "Sum" && node_proto.input_size() == 1)
1439     {
1440         layerParams.type = "Identity";
1441         addLayer(layerParams, node_proto);
1442         return;
1443     }
1444
1445     CV_Assert((node_proto.input_size() == 2) || (layer_type == "Sum" && node_proto.input_size() > 2));
1446
1447     if (layer_type == "Sum" && node_proto.input_size() > 2)
1448     {
1449         for (int i = 0; i < node_proto.input_size(); ++i)
1450         {
1451             if (layer_id.find(node_proto.input(i)) == layer_id.end())
1452             {
1453                 CV_Error(Error::StsNotImplemented, "Sum of constants is not implemented for inputs > 2");
1454             }
1455         }
1456     }
1457
1458     bool is_const_0 = layer_id.find(node_proto.input(0)) == layer_id.end();
1459     bool is_const_1 = layer_id.find(node_proto.input(1)) == layer_id.end();
1460     if (is_const_0 && is_const_1)
1461     {
1462         Mat blob_0 = getBlob(node_proto, 0);
1463         Mat blob_1 = getBlob(node_proto, 1);
1464         CV_Assert(blob_0.size == blob_1.size);
1465         Mat output = isSub ? (blob_0 - blob_1) : (blob_0 + blob_1);
1466         addConstant(node_proto.output(0), output);
1467         return;
1468     }
1469     else if (is_const_0 || is_const_1)
1470     {
1471         int const_blob_id = is_const_0 ? 0 : 1;
1472         int input_id = 1 - const_blob_id;
1473         Mat blob = getBlob(node_proto, const_blob_id);
1474         int blob_total = blob.total();
1475
1476         const float inputScale = isSub && is_const_0 ? -1.f : 1.f;
1477         const float constScale = isSub && is_const_1 ? -1.f : 1.f;
1478
1479         if (blob_total == 1) {
1480             layerParams.type = "Power";
1481             layerParams.set("scale", inputScale);
1482             layerParams.set("shift", constScale * blob.ptr<float>()[0]);
1483         }
1484         else {
1485             MatShape inpShape = outShapes[node_proto.input(input_id)];
1486             if (shape(blob) == inpShape)
1487             {
1488                 LayerParams constParams;
1489                 constParams.name = layerParams.name + "/const";
1490                 constParams.type = "Const";
1491                 constParams.blobs.push_back(blob);
1492                 int id = dstNet.addLayer(constParams.name, constParams.type, constParams);
1493                 layer_id.insert(std::make_pair(constParams.name, LayerInfo(id, 0)));
1494                 outShapes[constParams.name] = shape(blob);
1495
1496                 layerParams.type = "Eltwise";
1497                 float coeffs[] = {1., isSub ? -1.f : 1.f};
1498                 layerParams.set("coeff", DictValue::arrayReal<float*>(coeffs, 2));
1499                 node_proto.set_input(const_blob_id, constParams.name);
1500             }
1501             else
1502             {
1503                 if (inputScale < 0.f)
1504                 {
1505                     addNegation(layerParams, node_proto, input_id);
1506                 }
1507
1508                 layerParams.type = "Scale";
1509                 layerParams.set("bias_term", true);
1510                 int axis = 1;
1511                 for (int i = 0; i < graph_proto.initializer_size(); i++)
1512                 {
1513                     opencv_onnx::TensorProto tensor_proto = graph_proto.initializer(i);
1514                     if (tensor_proto.name() == node_proto.input(const_blob_id))
1515                     {
1516                         axis = inpShape.size() - tensor_proto.dims_size();
1517                         break;
1518                     }
1519                 }
1520                 layerParams.set("axis", axis);
1521                 blob = blob.reshape(1, 1);
1522                 layerParams.blobs.push_back(constScale * blob);
1523             }
1524         }
1525     }
1526     else if (outShapes[node_proto.input(0)] == outShapes[node_proto.input(1)])
1527     {
1528         layerParams.type = "Eltwise";
1529         if (isSub)
1530         {
1531             static float subCoeffs[] = {1.f, -1.f};
1532             layerParams.set("coeff", DictValue::arrayReal<float*>(subCoeffs, 2));
1533         }
1534     }
1535     else
1536     {
1537         if (isSub)
1538         {
1539             addNegation(layerParams, node_proto, 1);
1540         }
1541         layerParams.type = "Scale";
1542         layerParams.set("bias_term", true);
1543     }
1544     addLayer(layerParams, node_proto);
1545 }
1546
1547 void ONNXImporter::parsePow(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
1548 {
1549     if (layer_id.find(node_proto.input(1)) != layer_id.end())
1550         CV_Error(Error::StsNotImplemented, "Unsupported Pow op with variable power");
1551
1552     Mat blob = getBlob(node_proto, 1);
1553     if (blob.total() != 1)
1554         CV_Error(Error::StsNotImplemented, "Pow op supports only scalar power");
1555
1556     blob.convertTo(blob, CV_32F);
1557     layerParams.type = "Power";
1558     layerParams.set("power", blob.ptr<float>()[0]);
1559     addLayer(layerParams, node_proto);
1560 }
1561
1562 // "Min" "Max"
1563 void ONNXImporter::parseMinMax(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
1564 {
1565     const std::string& layer_type = node_proto.op_type();
1566     layerParams.type = "Eltwise";
1567     layerParams.set("operation", layer_type == "Max" ? "max" : "min");
1568     addLayer(layerParams, node_proto);
1569 }
1570
1571 void ONNXImporter::parseNeg(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
1572 {
1573     layerParams.type = "Power";
1574     layerParams.set("scale", -1);
1575     addLayer(layerParams, node_proto);
1576 }
1577
1578 void ONNXImporter::parseConstant(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
1579 {
1580     CV_Assert(node_proto.input_size() == 0);
1581     CV_Assert(layerParams.blobs.size() == 1);
1582     addConstant(node_proto.output(0), layerParams.blobs[0]);
1583 }
1584
1585 void transformBlobs(std::vector<Mat>& blobs)
1586 {
1587     Mat Wx = blobs[0];
1588     Mat Wh = blobs[1];
1589     Mat b = blobs[2];
1590     std::vector<Mat> cudaWorkaround;
1591     cudaWorkaround.push_back(Wx.clone());
1592     cudaWorkaround.push_back(Wh.clone());
1593     cudaWorkaround.push_back(b.clone());
1594
1595     const int numHidden = Wh.size[2];
1596
1597     Mat h0 = blobs[3];
1598     h0 = h0.reshape(1, h0.size[0] * h0.size[1]);
1599     Mat c0 = blobs[4];
1600     c0 = c0.reshape(1, c0.size[0] * c0.size[1]);
1601
1602     b = b.reshape(1, b.size[0]);
1603     Mat bx = b.colRange(0, b.cols / 2);
1604     Mat bh = b.colRange(b.cols / 2, b.cols);
1605     b = bx + bh;
1606
1607     auto toIFOC = [] (Mat& in) {
1608         int first = in.size[0];
1609         int rest = in.total() / first / 4;
1610         // every weight blob contains weights for Input, Output, Forget and Cell gates
1611         Mat m = in.reshape(1, {first, 4, rest});
1612         Mat outputGate = m.col(1);
1613         Mat forgetGate = m.col(2);
1614         std::swap_ranges(outputGate.begin<float>(), outputGate.end<float>(), forgetGate.begin<float>());
1615     };
1616
1617     toIFOC(Wx);
1618     toIFOC(Wh);
1619     toIFOC(b);
1620
1621     Wx = Wx.reshape(1, Wx.size[0] * Wx.size[1]);
1622     Wh = Wh.reshape(1, Wh.size[0] * Wh.size[1]);
1623
1624     blobs[0] = Wh;
1625     blobs[1] = Wx;
1626     blobs[2] = b.reshape(1, 1);
1627     blobs[3] = h0;
1628     blobs[4] = c0;
1629
1630     if (blobs.size() == 5) {
1631         // so that future patch removing copies can leave all indexing as is
1632         blobs.insert(blobs.begin(), cudaWorkaround.begin(), cudaWorkaround.end());
1633         return;
1634     }
1635
1636     Mat P = blobs[5];
1637     blobs[5] = P.colRange(0, numHidden);
1638     blobs[5] = blobs[5].clone().reshape(1, blobs[5].total());  // Single column.
1639     blobs[5] = Mat::diag(blobs[5]);
1640
1641     blobs.push_back(P.colRange(numHidden, 2 * numHidden));
1642     blobs[6] = blobs[6].clone().reshape(1, blobs[6].total());  // Single column.
1643     blobs[6] = Mat::diag(blobs[6]);
1644
1645     blobs.push_back(P.colRange(2 * numHidden, 3 * numHidden));
1646     blobs[7] = blobs[7].clone().reshape(1, blobs[7].total());  // Single column.
1647     blobs[7] = Mat::diag(blobs[7]);
1648
1649     // so that future patch removing copies can leave all indexing as is
1650     blobs.insert(blobs.begin(), cudaWorkaround.begin(), cudaWorkaround.end());
1651 }
1652
1653 void ONNXImporter::lstm_extractConsts(LayerParams& layerParams, const opencv_onnx::NodeProto& lstm_proto, size_t idx, int* blobShape_, int size)
1654 {
1655         MatShape blobShape(blobShape_, blobShape_ + size);
1656         Mat blob;
1657         if (idx < lstm_proto.input_size() && !lstm_proto.input(idx).empty())
1658         {
1659             blob = getBlob(lstm_proto, idx);
1660             CV_Assert(shape(blob) == blobShape);
1661         }
1662         else
1663         {
1664             blob = Mat(blobShape, CV_32FC1, 0.);
1665         }
1666         layerParams.blobs.push_back(blob);
1667 };
1668
1669 void ONNXImporter::lstm_add_reshape(const std::string& input_name, const std::string& output_name, int* layerShape, size_t n)
1670 {
1671     LayerParams reshapeLp;
1672     reshapeLp.name = cv::format("%s/reshape", input_name.c_str());
1673     reshapeLp.type = "Reshape";
1674     CV_Assert(layer_id.find(reshapeLp.name) == layer_id.end());
1675
1676     reshapeLp.set("dim", DictValue::arrayInt(layerShape, n));
1677
1678     opencv_onnx::NodeProto reshape_proto;
1679     reshape_proto.add_input(input_name);
1680     reshape_proto.add_output(output_name);
1681     addLayer(reshapeLp, reshape_proto);
1682 };
1683
1684 std::string ONNXImporter::lstm_add_slice(int index, const std::string& input_name, int* begin, int* end, size_t n)
1685 {
1686     LayerParams sliceLP;
1687     sliceLP.name = cv::format("%s/slice_%d", input_name.c_str(), index);
1688     sliceLP.type = "Slice";
1689     CV_Assert(layer_id.find(sliceLP.name) == layer_id.end());
1690
1691     sliceLP.set("begin", DictValue::arrayInt(begin, n));
1692     sliceLP.set("end", DictValue::arrayInt(end, n));
1693     sliceLP.set("axis", 0);
1694
1695     opencv_onnx::NodeProto slice_proto;
1696     slice_proto.add_input(input_name);
1697     slice_proto.add_output(sliceLP.name);
1698     addLayer(sliceLP, slice_proto);
1699
1700     return slice_proto.output(0);
1701 };
1702
1703 std::string ONNXImporter::lstm_fix_dims(LayerParams& layerParams, const opencv_onnx::NodeProto& lstm_proto,
1704                                         int batch_size, int num_directions, int hidden_size, bool need_y, const std::string& y_name,
1705                                         const int index)
1706 {
1707     std::string reshape_output = cv::format("%s/reshape_%d", layerParams.name.c_str(), index);
1708
1709     // reshape from Seq, Batch, Dirs*Hidden to Seq, Batch, Dirs, Hidden
1710     // to not confuse reshape with dynamic first dimension, zero means 'leave unchanged'
1711     int layerShape[] = {0, batch_size, num_directions, hidden_size};
1712     lstm_add_reshape(lstm_proto.output(index), reshape_output, layerShape, sizeof(layerShape) / sizeof(layerShape[0]));
1713
1714     // permute from Seq, Batch, Dirs, Hidden to Seq, Dirs, Batch, Hidden
1715     LayerParams permuteLP;
1716     permuteLP.name = reshape_output + "/permute";
1717     permuteLP.type = "Permute";
1718     CV_Assert(layer_id.find(permuteLP.name) == layer_id.end());
1719
1720     int order[] = {0, 2, 1, 3};
1721     permuteLP.set("order", DictValue::arrayInt(order, 4));
1722
1723     opencv_onnx::NodeProto permute_proto;
1724     permute_proto.add_input(reshape_output);
1725     permute_proto.add_output((need_y && index == 0) ? y_name : static_cast<std::string>(permuteLP.name));
1726     addLayer(permuteLP, permute_proto);
1727
1728     return permute_proto.output(0);
1729 };
1730
1731 void ONNXImporter::lstm_add_transform(int num_directions, int batch_size, int hidden_size,
1732                                       int index, const std::string& input_name, const std::string& output_name)
1733 {
1734     if (num_directions == 1)
1735     {
1736         // Slice: Yh = Y[-1, :, :, :]
1737         int begin[] = {-1}, end[] = {INT_MAX};
1738         std::string slice_output = lstm_add_slice(index, input_name, begin, end, sizeof(begin) / sizeof(begin[0]));
1739
1740         // Reshape: 1x1xBxH -> 1xBxH
1741         int layerShape[] = {1, batch_size, hidden_size};
1742         lstm_add_reshape(slice_output, output_name, layerShape, sizeof(layerShape) / sizeof(layerShape[0]));
1743     }
1744     else
1745     {
1746         // Slice: SxDxBxH -> last sequence, first direction
1747         int begin0[] = {-1, 0}, end0[] = {INT_MAX, 1};
1748         std::string slice_0 = lstm_add_slice(0, input_name, begin0, end0, sizeof(begin0) / sizeof(begin0[0]));
1749
1750         // Slice: SxDxBxH -> first sequence, last direction
1751         int begin1[] = {0, -1}, end1[] = {1, INT_MAX};
1752         std::string slice_1 = lstm_add_slice(1, input_name, begin1, end1, sizeof(begin1) / sizeof(begin1[0]));
1753
1754         LayerParams concatLP;
1755         concatLP.name = cv::format("%s/concat", input_name.c_str());
1756         concatLP.type = "Concat";
1757         CV_Assert(layer_id.find(concatLP.name) == layer_id.end());
1758
1759         concatLP.set("axis", 1); // 1x1xBxH -> 1x2xBxH
1760
1761         opencv_onnx::NodeProto concat_proto;
1762         concat_proto.add_input(slice_0);
1763         concat_proto.add_input(slice_1);
1764         concat_proto.add_output(concatLP.name);
1765         addLayer(concatLP, concat_proto);
1766
1767         // Reshape: 1x2xBxH -> 2xBxH
1768         int layerShape[] = {2, batch_size, hidden_size};
1769         lstm_add_reshape(concat_proto.output(0), output_name, layerShape, sizeof(layerShape) / sizeof(layerShape[0]));
1770     }
1771 };
1772
1773 void ONNXImporter::parseLSTM(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto_)
1774 {
1775     opencv_onnx::NodeProto lstm_proto = node_proto_;
1776     layerParams.name += "/lstm";
1777
1778     // https://github.com/onnx/onnx/blob/main/docs/Operators.md#LSTM
1779     CV_Assert(lstm_proto.input_size() >= 3);
1780     for (size_t i = 1; i < 3; ++i)
1781     {
1782         const std::string& name = lstm_proto.input(i);
1783         CV_Assert(!name.empty() && constBlobs.count(name) == 1);
1784     }
1785
1786     IterShape_t shapeIt = outShapes.find(lstm_proto.input(0));
1787     CV_Assert(shapeIt != outShapes.end());
1788     const MatShape x_shape = shapeIt->second;
1789
1790     const int seq_length = x_shape[0];
1791     const int batch_size = x_shape[1];
1792     const int input_size = x_shape[2];
1793     const int hidden_size = layerParams.get<int>("hidden_size");
1794     const int num_directions = constBlobs[lstm_proto.input(1)].size[0];
1795
1796     int w_size[] = {num_directions, 4*hidden_size, input_size};
1797     lstm_extractConsts(layerParams, lstm_proto, 1, w_size, sizeof(w_size) / sizeof(w_size[0])); // W
1798
1799     int r_size[] =  {num_directions, 4*hidden_size, hidden_size};
1800     lstm_extractConsts(layerParams, lstm_proto, 2, r_size, sizeof(r_size) / sizeof(r_size[0])); // R
1801
1802     int b_size[] = {num_directions, 8*hidden_size};
1803     lstm_extractConsts(layerParams, lstm_proto, 3, b_size, sizeof(b_size) / sizeof(b_size[0])); // B
1804
1805     if (4 < lstm_proto.input_size() && !lstm_proto.input(4).empty())
1806     {
1807         Mat blob = getBlob(lstm_proto, 4);
1808         CV_Assert(blob.total() == batch_size);
1809         for (MatIterator_<int32_t> it = blob.begin<int32_t>(); it != blob.end<int32_t>(); ++it)
1810         {
1811             CV_Assert(*it == seq_length);
1812         }
1813     }
1814
1815     int h_size[] = {num_directions, batch_size, hidden_size};
1816     lstm_extractConsts(layerParams, lstm_proto, 5, h_size, sizeof(h_size) / sizeof(h_size[0])); // initial_h
1817
1818     int c_size[] = {num_directions, batch_size, hidden_size};
1819     lstm_extractConsts(layerParams, lstm_proto, 6, c_size, sizeof(c_size) / sizeof(c_size[0])); // initial_c
1820
1821     if (lstm_proto.input_size() > 7 && !lstm_proto.input(7).empty())
1822     {
1823         layerParams.set("use_peephole", true);
1824         int p_size[] = {num_directions, 3 * hidden_size};
1825         lstm_extractConsts(layerParams, lstm_proto, 7, p_size, sizeof(p_size) / sizeof(p_size[0])); // P
1826     }
1827
1828     transformBlobs(layerParams.blobs);
1829
1830     layerParams.set("is_onnx", true);
1831     layerParams.set("reverse", layerParams.get<String>("direction", "") == "reverse");
1832     layerParams.set("bidirectional", layerParams.get<String>("direction", "") == "bidirectional");
1833
1834     bool need_yc = lstm_proto.output_size() > 2 && !lstm_proto.output(2).empty();
1835     bool need_yh = lstm_proto.output_size() > 1 && !lstm_proto.output(1).empty();
1836     bool need_y = lstm_proto.output_size() > 0 && !lstm_proto.output(0).empty();
1837
1838     const std::string y_name = need_y ? lstm_proto.output(0) : "";
1839     const std::string yh_name = need_yh ? lstm_proto.output(1) : "";
1840     const std::string yc_name = need_yc ? lstm_proto.output(2) : "";
1841
1842     layerParams.set("produce_cell_output", need_yc);
1843
1844     lstm_proto.clear_output();
1845     if (need_y || need_yh)
1846     {
1847         // give random names to LSTMLayer's outputs because every output needs postprocessing
1848         lstm_proto.add_output(cv::format("%s_y", layerParams.name.c_str()));
1849     }
1850     if (need_yc)
1851     {
1852         lstm_proto.add_output(yc_name);
1853     }
1854
1855     addLayer(layerParams, lstm_proto);
1856
1857     std::string y_output = lstm_fix_dims(layerParams, lstm_proto, batch_size, num_directions, hidden_size, need_y,
1858                                          y_name, 0);
1859     if (need_yh)
1860     {
1861         lstm_add_transform(num_directions, batch_size, hidden_size, 0, y_output, yh_name);
1862     }
1863 }
1864
1865 void ONNXImporter::parseGRU(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto_)
1866 {
1867     opencv_onnx::NodeProto node_proto = node_proto_;
1868     const std::string output_name = node_proto.output(0);
1869     LayerParams gruParams = layerParams;
1870     gruParams.name += "/gru";
1871
1872     // https://pytorch.org/docs/stable/generated/torch.nn.GRU.html?highlight=gru#
1873     CV_Assert(node_proto.input_size() == 6);
1874     Mat Wx = getBlob(node_proto, 1);
1875     Mat Wh = getBlob(node_proto, 2);
1876     Mat b = getBlob(node_proto, 3);
1877     Mat h0 = getBlob(node_proto, 5);
1878
1879     Wx = Wx.reshape(1, Wx.size[0] * Wx.size[1]);
1880     Wh = Wh.reshape(1, Wh.size[0] * Wh.size[1]);
1881     h0 = h0.reshape(1, h0.size[0] * h0.size[1]);
1882     b = b.reshape(1, b.size[0]);
1883
1884     gruParams.blobs.resize(4);
1885     gruParams.blobs[0] = Wh;
1886     gruParams.blobs[1] = Wx;
1887     gruParams.blobs[2] = b;
1888     gruParams.blobs[3] = h0;
1889     gruParams.set("bidirectional", gruParams.get<String>("direction", "") == "bidirectional");
1890
1891     node_proto.set_output(0, gruParams.name);  // set different name so output shapes will be registered on that name
1892     addLayer(gruParams, node_proto);
1893
1894     MatShape gruShape = outShapes[node_proto.output(0)];
1895
1896     // Add fake 1 as it is done in ONNX
1897     gruShape.insert(gruShape.begin() + 1, 1);
1898
1899     layerParams.type = "Reshape";
1900     layerParams.set("dim", DictValue::arrayInt(&gruShape[0], gruShape.size()));
1901     node_proto.set_input(0, gruParams.name);  // redirect input to GRU
1902     node_proto.set_output(0, output_name);  // keep origin GRU's name
1903     addLayer(layerParams, node_proto);
1904 }
1905
1906 void ONNXImporter::parseImageScaler(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
1907 {
1908     const float scale = layerParams.has("scale") ? layerParams.get<float>("scale") : 1.0f;
1909     layerParams.erase("scale");
1910
1911     if (layerParams.has("bias"))
1912     {
1913         layerParams.type = "Scale";
1914         layerParams.blobs.push_back(
1915                 Mat(Size(1,  layerParams.get("bias").size()), CV_32FC1, scale));
1916
1917         layerParams.set("bias_term", true);
1918         Mat bias(1, layerParams.get("bias").size(), CV_32FC1);
1919         for (int j = 0; j < bias.total(); j++) {
1920             bias.at<float>(0, j) = layerParams.get("bias").getRealValue(j);
1921         }
1922         layerParams.blobs.push_back(bias);
1923         layerParams.erase("bias");
1924     }
1925     else {
1926         layerParams.set("scale", scale);
1927         layerParams.type = "Power";
1928     }
1929     addLayer(layerParams, node_proto);
1930 }
1931
1932 void ONNXImporter::parseClip(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
1933 {
1934     layerParams.type = "ReLU6";
1935     float min_value = -FLT_MAX, max_value = FLT_MAX;
1936     int input_size = node_proto.input_size();
1937     CV_Check(input_size, 1 <= input_size && input_size <= 3, "");
1938
1939     if (input_size >= 2 && !node_proto.input(1).empty())
1940     {
1941         if (constBlobs.find(node_proto.input(1)) != constBlobs.end())
1942             min_value = getBlob(node_proto, 1).at<float>(0);
1943         else
1944             CV_Error(Error::StsNotImplemented, "Non-constant min values in Clip are not supported");
1945     }
1946
1947     if (input_size == 3 && !node_proto.input(2).empty())
1948     {
1949         if (constBlobs.find(node_proto.input(2)) != constBlobs.end())
1950             max_value = getBlob(node_proto, 2).at<float>(0);
1951         else
1952             CV_Error(Error::StsNotImplemented, "Non-constant max values in Clip are not supported");
1953     }
1954
1955     layerParams.set("min_value", layerParams.get<float>("min", min_value));
1956     layerParams.set("max_value", layerParams.get<float>("max", max_value));
1957     addLayer(layerParams, node_proto);
1958 }
1959
1960 void ONNXImporter::parseLeakyRelu(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
1961 {
1962     layerParams.type = "ReLU";
1963     layerParams.set("negative_slope", layerParams.get<float>("alpha", 0.01));
1964     addLayer(layerParams, node_proto);
1965 }
1966
1967 void ONNXImporter::parseRelu(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
1968 {
1969     layerParams.type = "ReLU";
1970     addLayer(layerParams, node_proto);
1971 }
1972
1973 void ONNXImporter::parseElu(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
1974 {
1975     layerParams.type = "ELU";
1976     addLayer(layerParams, node_proto);
1977 }
1978
1979 void ONNXImporter::parseTanh(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
1980 {
1981     layerParams.type = "TanH";
1982     addLayer(layerParams, node_proto);
1983 }
1984
1985 void ONNXImporter::parseAbs(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
1986 {
1987     layerParams.type = "AbsVal";
1988     addLayer(layerParams, node_proto);
1989 }
1990
1991 void ONNXImporter::parseCompare(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
1992 {
1993     CV_Assert(node_proto.input_size() == 2);
1994     const std::string& layer_type = node_proto.op_type();
1995
1996     bool is_const_0 = layer_id.find(node_proto.input(0)) == layer_id.end();
1997     bool is_const_1 = layer_id.find(node_proto.input(1)) == layer_id.end();
1998
1999     if (is_const_0 || is_const_1)
2000     {
2001         Mat blob = getBlob(node_proto, static_cast<int>(is_const_1));
2002         blob = blob.reshape(1, 1);
2003         layerParams.blobs.push_back(blob);
2004     }
2005
2006     layerParams.type = "Compare";
2007
2008     if (layer_type == "Equal")
2009         layerParams.set("mode", "equal");
2010     else if (layer_type == "Greater")
2011         layerParams.set("mode", "greater");
2012     else
2013         layerParams.set("mode", "less");
2014     addLayer(layerParams, node_proto);
2015 }
2016
2017 void ONNXImporter::parsePRelu(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
2018 {
2019     layerParams.type = "PReLU";
2020     layerParams.blobs.push_back(getBlob(node_proto, 1));
2021     addLayer(layerParams, node_proto);
2022 }
2023
2024 void ONNXImporter::parseLRN(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
2025 {
2026     replaceLayerParam(layerParams, "size", "local_size");
2027     addLayer(layerParams, node_proto);
2028 }
2029
2030 void ONNXImporter::parseInstanceNormalization(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto_)
2031 {
2032     opencv_onnx::NodeProto node_proto = node_proto_;
2033     if (node_proto.input_size() != 3)
2034         CV_Error(Error::StsNotImplemented,
2035                  "Expected input, scale, bias");
2036
2037     layerParams.blobs.resize(4);
2038     layerParams.blobs[2] = getBlob(node_proto, 1);  // weightData
2039     layerParams.blobs[3] = getBlob(node_proto, 2);  // biasData
2040     layerParams.set("has_bias", true);
2041     layerParams.set("has_weight", true);
2042
2043     // Get number of channels in input
2044     int size = layerParams.blobs[2].total();
2045     layerParams.blobs[0] = Mat::zeros(size, 1, CV_32F); // mean
2046     layerParams.blobs[1] = Mat::ones(size, 1, CV_32F); // std
2047
2048     LayerParams mvnParams;
2049     mvnParams.name = layerParams.name + "/MVN";
2050     mvnParams.type = "MVN";
2051     mvnParams.set("eps", layerParams.get<float>("epsilon"));
2052     layerParams.erase("epsilon");
2053
2054     //Create MVN layer
2055     int id = dstNet.addLayer(mvnParams.name, mvnParams.type, mvnParams);
2056     //Connect to input
2057     IterLayerId_t layerId = layer_id.find(node_proto.input(0));
2058     CV_Assert(layerId != layer_id.end());
2059     dstNet.connect(layerId->second.layerId, layerId->second.outputId, id, 0);
2060     //Add shape
2061     layer_id.insert(std::make_pair(mvnParams.name, LayerInfo(id, 0)));
2062     outShapes[mvnParams.name] = outShapes[node_proto.input(0)];
2063
2064     //Replace Batch Norm's input to MVN
2065     node_proto.set_input(0, mvnParams.name);
2066     layerParams.type = "BatchNorm";
2067     addLayer(layerParams, node_proto);
2068 }
2069
2070 void ONNXImporter::parseBatchNormalization(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
2071 {
2072     if (node_proto.input_size() != 5)
2073         CV_Error(Error::StsNotImplemented,
2074                  "Expected input, scale, bias, mean and var");
2075
2076     layerParams.type = "BatchNorm";
2077     replaceLayerParam(layerParams, "epsilon", "eps");
2078     replaceLayerParam(layerParams, "spatial", "use_global_stats");
2079
2080     Mat meanData = getBlob(node_proto, 3);
2081     Mat stdData =  getBlob(node_proto, 4);
2082
2083     layerParams.blobs.push_back(meanData);
2084     layerParams.blobs.push_back(stdData);
2085
2086     if (!node_proto.input(1).empty()) {
2087         layerParams.set("has_weight", true);
2088         layerParams.blobs.push_back(getBlob(node_proto, 1));  // weightData
2089     } else {
2090         layerParams.set("has_weight", false);
2091     }
2092
2093     if (!node_proto.input(2).empty()) {
2094         layerParams.set("has_bias", true);
2095         layerParams.blobs.push_back(getBlob(node_proto, 2)); // biasData
2096     } else {
2097         layerParams.set("has_bias", false);
2098     }
2099     addLayer(layerParams, node_proto);
2100 }
2101
2102 // A * B + C = Y, we require that the dimension of A is [m, k], and the dimension of B is [n, k].
2103 // And the dim of output Y is [m, n]
2104 void ONNXImporter::parseGemm(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
2105 {
2106     CV_Assert(node_proto.input_size() >= 2);
2107     layerParams.type = "InnerProduct";
2108     Mat weights = getBlob(node_proto, 1);
2109
2110     if (!layerParams.get<int>("transB", 0))
2111     {
2112         transpose(weights, weights);
2113     }
2114     layerParams.blobs.push_back(weights);
2115
2116     if (node_proto.input_size() == 3) {
2117         Mat bias = getBlob(node_proto, 2);
2118         layerParams.blobs.push_back(bias);
2119     }
2120     if (constBlobs.find(node_proto.input(0)) != constBlobs.end())
2121     {
2122         Mat inputBuf = getBlob(node_proto, 0);
2123
2124         LayerParams constParams;
2125         constParams.name = node_proto.input(0);
2126         constParams.type = "Const";
2127         constParams.blobs.push_back(inputBuf);
2128
2129         opencv_onnx::NodeProto proto;
2130         proto.add_output(constParams.name);
2131         addLayer(constParams, proto);
2132     }
2133
2134     layerParams.set("num_output", layerParams.blobs[0].size[0]);
2135     layerParams.set("bias_term", node_proto.input_size() == 3);
2136     addLayer(layerParams, node_proto);
2137 }
2138
2139 void ONNXImporter::parseMatMul(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
2140 {
2141     CV_Assert(node_proto.input_size() == 2);
2142     layerParams.type = "InnerProduct";
2143     layerParams.set("bias_term", false);
2144     CV_Assert(constBlobs.find(node_proto.input(0)) == constBlobs.end());
2145     int firstInpDims = outShapes[node_proto.input(0)].size();
2146     int secondInpDims;
2147
2148     if (constBlobs.find(node_proto.input(1)) != constBlobs.end())
2149     {
2150         Mat blob = getBlob(node_proto, 1);
2151         secondInpDims = blob.dims;
2152         layerParams.blobs.push_back(blob.t());
2153         layerParams.set("num_output", layerParams.blobs[0].size[0]);
2154     } else {
2155         secondInpDims = outShapes[node_proto.input(1)].size();
2156     }
2157     layerParams.set("axis", firstInpDims - secondInpDims + 1);
2158     addLayer(layerParams, node_proto);
2159 }
2160
2161 void findBroadAxis(const MatShape& broadShape, const MatShape& outShape, size_t& axis, int& broadAxis)
2162 {
2163     const size_t diff = outShape.size() - broadShape.size();
2164
2165     // find the first non-one element of the broadcasting shape
2166     axis = 0;
2167     for (; axis < broadShape.size() && broadShape[axis] == 1; ++axis) {}
2168
2169     // find the last non-one element of the broadcasting shape
2170     size_t endAxis = broadShape.size();
2171     for (; endAxis > axis && broadShape[endAxis - 1] == 1; --endAxis) {}
2172
2173     // find one between axis and endAxis - as it needs to be broadcasted,
2174     // dimensions from the left of axis and from the right of endAxis will be handled by Scale layer
2175     broadAxis = -1;
2176     for (size_t i = axis; i < endAxis; ++i)
2177     {
2178         size_t outAxis = i + diff;
2179         if (outShape[outAxis] == broadShape[i])
2180         {
2181             continue;
2182         }
2183
2184         // ensure we need to broadcast only 1 dimension in the middle
2185         CV_Assert(broadShape[i] == 1 && broadAxis == -1);
2186         broadAxis = static_cast<int>(outAxis);
2187     }
2188
2189     axis += diff;
2190 }
2191
2192 // "Mul" "Div"
2193 void ONNXImporter::parseMul(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto_)
2194 {
2195     opencv_onnx::NodeProto node_proto = node_proto_;
2196     const std::string& layer_type = node_proto.op_type();
2197     const std::string output_name = node_proto.output(0);
2198     CV_Assert(node_proto.input_size() == 2);
2199
2200     bool isDiv = layer_type == "Div";
2201     int constId = -1;
2202     bool haveVariables = false;
2203     for (int i = 0; i < 2; ++i)
2204     {
2205         if (constBlobs.find(node_proto.input(i)) != constBlobs.end())
2206             constId = i;
2207         else
2208             haveVariables = true;
2209     }
2210     if (constId != -1 && haveVariables)
2211     {
2212         Mat blob = getBlob(node_proto, constId);
2213         blob = blob.reshape(1, 1);
2214         if (blob.total() == 1) {
2215             float blob_value = blob.ptr<float>()[0];
2216             float coeff = blob_value;
2217             if (isDiv)
2218             {
2219                 coeff = 1.f / blob_value;
2220                 if (constId == 0)
2221                 {
2222                     // Power layer calculates (x*scale + shift)^power, so const/x -> (x * (1/const) + 0)^(-1)
2223                     layerParams.set("power", -1.f);
2224                 }
2225             }
2226             layerParams.set("scale", coeff);
2227             layerParams.type = "Power";
2228         }
2229         else {
2230             if (isDiv)
2231                 divide(1.0, blob, blob);
2232             layerParams.blobs.push_back(blob);
2233             layerParams.type = "Scale";
2234         }
2235     }
2236     else if (!haveVariables)
2237     {
2238         Mat inp0 = getBlob(node_proto, 0);
2239         Mat inp1 = getBlob(node_proto, 1);
2240
2241         if (inp0.size != inp1.size && (inp0.total() != 1 || inp1.total() != 1))
2242             CV_Error_(Error::StsNotImplemented, ("Different shapes case is not supported with constant inputs: %s", layer_type.c_str()));
2243
2244         if (inp0.total() == 1 && inp1.total() == 1 && inp0.dims != inp1.dims)
2245         {
2246             if (inp0.dims < inp1.dims)
2247             {
2248                 inp0 = inp0.reshape(1, inp1.dims, inp1.size);
2249                 inp0.dims = inp1.dims;
2250             }
2251             else
2252             {
2253                 inp1 = inp1.reshape(1, inp0.dims, inp0.size);
2254                 inp1.dims = inp0.dims;
2255             }
2256         }
2257
2258         Mat out;
2259         if (inp0.total() != inp1.total())
2260         {
2261             if (inp0.total() == 1)
2262             {
2263                 float inp0_value = inp0.ptr<float>()[0];
2264                 float coeff = isDiv ? 1.0 / inp0_value : inp0_value;
2265                 multiply(inp1, coeff, out);
2266             }
2267             else
2268             {
2269                 float inp1_value = inp1.ptr<float>()[0];
2270                 float coeff = isDiv ? 1.0 / inp1_value : inp1_value;
2271                 multiply(inp0, coeff, out);
2272             }
2273
2274         }
2275         else
2276         {
2277             out = isDiv ? inp0 / inp1 : inp0.mul(inp1);
2278         }
2279
2280         if (inp0.dims == 1 && inp1.dims == 1)
2281             out.dims = 1;  // to workaround dims == 1
2282         addConstant(output_name, out);
2283         return;
2284     }
2285     else if (outShapes[node_proto.input(0)] == outShapes[node_proto.input(1)])
2286     {
2287         layerParams.type = "Eltwise";
2288         layerParams.set("operation", isDiv ? "div" : "prod");
2289     }
2290     else
2291     {
2292         // Scale layer allocate output with the first input shape
2293         if (total(outShapes[node_proto.input(0)]) < total(outShapes[node_proto.input(1)]))
2294         {
2295             opencv_onnx::NodeProto proto;
2296             proto.add_input(node_proto.input(1));
2297             proto.add_input(node_proto.input(0));
2298             proto.add_output(output_name);
2299             node_proto = proto;
2300         }
2301
2302         if (isDiv)
2303         {
2304             LayerParams powerParams;
2305             powerParams.name = layerParams.name + "/inv";
2306             powerParams.type = "Power";
2307             powerParams.set("power", -1);
2308
2309             //Create Power layer
2310             int id = dstNet.addLayer(powerParams.name, powerParams.type, powerParams);
2311             //Connect to input
2312             IterLayerId_t layerId = layer_id.find(node_proto.input(1));
2313             CV_Assert(layerId != layer_id.end());
2314             dstNet.connect(layerId->second.layerId, layerId->second.outputId, id, 0);
2315             //Add shape
2316             layer_id.insert(std::make_pair(powerParams.name, LayerInfo(id, 0)));
2317             outShapes[powerParams.name] = outShapes[node_proto.input(1)];
2318
2319             //Replace input to Power
2320             node_proto.set_input(1, powerParams.name);
2321         }
2322
2323         const MatShape& broadShape = outShapes[node_proto.input(1)];
2324         const MatShape& outShape = outShapes[node_proto.input(0)];
2325
2326         size_t axis = 0;
2327         int broadAxis = -1;
2328         findBroadAxis(broadShape, outShape, axis, broadAxis);
2329
2330         // if there is a one dimension in the middle that should be broadcasted, broadcast it
2331         if (broadAxis != -1)
2332         {
2333             opencv_onnx::NodeProto concat_node_proto = node_proto;
2334             const std::string& input1 = concat_node_proto.input(1);
2335
2336             expandMid(layerParams.name, concat_node_proto, input1, outShape[broadAxis]);
2337
2338             LayerParams concatLP;
2339             concatLP.name = layerParams.name + "/concat";
2340             concatLP.set("axis", broadAxis);
2341             concatLP.type = "Concat";
2342             concat_node_proto.set_output(0, concatLP.name);
2343
2344             addLayer(concatLP, concat_node_proto);
2345             node_proto.set_input(1, concatLP.name);
2346         }
2347
2348         CV_Assert(axis != outShape.size());
2349         layerParams.set("axis", static_cast<int>(axis));
2350         layerParams.type = "Scale";
2351     }
2352     addLayer(layerParams, node_proto);
2353 }
2354
2355 void ONNXImporter::parseConv(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto_)
2356 {
2357     opencv_onnx::NodeProto node_proto = node_proto_;
2358     CV_Assert(node_proto.input_size() >= 2);
2359     layerParams.type = "Convolution";
2360     for (int j = 1; j < node_proto.input_size(); j++) {
2361         if (constBlobs.find(node_proto.input(j)) != constBlobs.end())
2362         {
2363             layerParams.blobs.push_back(getBlob(node_proto, j));
2364         }
2365     }
2366     int outCn = layerParams.blobs.empty() ? outShapes[node_proto.input(1)][0] : layerParams.blobs[0].size[0];
2367     layerParams.set("num_output", outCn);
2368
2369     // Check for asymmetric padding in Conv2D
2370     if (layerParams.has("pad"))
2371     {
2372         bool asymmetricPadding = false;
2373         DictValue pads = layerParams.get("pad");
2374         const int dims = pads.size() / 2;
2375         for (int i = 0; i < dims; ++i)
2376         {
2377             if (pads.get<int>(i) != pads.get<int>(i + dims))
2378             {
2379                 asymmetricPadding = true;
2380                 break;
2381             }
2382         }
2383         if (asymmetricPadding && pads.size() == 4) // [pad_t, pad_l, pad_b, pad_r]
2384         {
2385             layerParams.erase("pad");
2386             // No paddings required for N, C axis
2387             std::vector<int> paddings(4, 0);
2388             // Add paddings for H, W axis
2389             for (int i = 0; i < dims; ++i)
2390             {
2391                 paddings.push_back(pads.get<int>(i));
2392                 paddings.push_back(pads.get<int>(dims + i));
2393             }
2394             LayerParams padLp;
2395             padLp.name = layerParams.name + "/pad";
2396             padLp.type = "Padding";
2397             padLp.set("paddings", DictValue::arrayInt(&paddings[0], paddings.size()));
2398
2399             opencv_onnx::NodeProto proto;
2400             proto.add_input(node_proto.input(0));
2401             proto.add_output(padLp.name);
2402
2403             addLayer(padLp, proto);
2404             node_proto.set_input(0, padLp.name);
2405         }
2406     }
2407     addLayer(layerParams, node_proto);
2408 }
2409
2410 void ONNXImporter::parseConvTranspose(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
2411 {
2412     CV_Assert(node_proto.input_size() >= 2);
2413     layerParams.type = "Deconvolution";
2414     for (int j = 1; j < node_proto.input_size(); j++) {
2415         layerParams.blobs.push_back(getBlob(node_proto, j));
2416     }
2417     layerParams.set("num_output", layerParams.blobs[0].size[1] * layerParams.get<int>("group", 1));
2418     layerParams.set("bias_term", node_proto.input_size() == 3);
2419
2420     if (!layerParams.has("kernel_size"))
2421         CV_Error(Error::StsNotImplemented,
2422                  "Required attribute 'kernel_size' is not present.");
2423
2424     if (layerParams.has("output_shape"))
2425     {
2426         const DictValue& outShape = layerParams.get("output_shape");
2427         DictValue strides = layerParams.get("stride");
2428         DictValue kernel = layerParams.get("kernel_size");
2429
2430         String padMode;
2431         std::vector<int> adjust_pads;
2432         if (layerParams.has("pad_mode"))
2433         {
2434             padMode = toUpperCase(layerParams.get<String>("pad_mode"));
2435             if (padMode != "SAME" && padMode != "VALID")
2436                 CV_Error(Error::StsError, "Unsupported padding mode " + padMode);
2437
2438             for (int i = 0; i < strides.size(); i++)
2439             {
2440                 int sz = outShape.get<int>(2 + i);
2441                 int stride = strides.get<int>(i);
2442                 adjust_pads.push_back(padMode == "SAME"? (sz - 1) % stride :
2443                                                          (sz - kernel.get<int>(i)) % stride);
2444             }
2445             layerParams.set("adj", DictValue::arrayInt(&adjust_pads[0], adjust_pads.size()));
2446         }
2447     }
2448     else if (layerParams.has("output_padding"))
2449     {
2450         replaceLayerParam(layerParams, "output_padding", "adj");
2451     }
2452     addLayer(layerParams, node_proto);
2453 }
2454
2455 void ONNXImporter::parseTranspose(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
2456 {
2457     int depth = layerParams.get<int>("depth", CV_32F);
2458     layerParams.type = (depth == CV_8S) ? "PermuteInt8" : "Permute";
2459     replaceLayerParam(layerParams, "perm", "order");
2460     if (!layerParams.has("order")) {
2461         MatShape inpShape = outShapes[node_proto.input(0)];
2462         size_t dims = inpShape.size();
2463         std::vector<int> perm(dims);
2464         for (size_t d = 0; d < dims; ++d)
2465         {
2466             perm[d] = static_cast<int>(dims - 1 - d);
2467         }
2468         layerParams.set("order", DictValue::arrayInt(perm.data(), perm.size()));
2469     }
2470
2471     CV_Assert(node_proto.input_size() == 1);
2472     if (constBlobs.find(node_proto.input(0)) != constBlobs.end())
2473     {
2474         std::vector<Mat> inputs(1, getBlob(node_proto, 0)), transposed;
2475         runLayer(layerParams, inputs, transposed);
2476         CV_Assert(transposed.size() == 1);
2477         addConstant(node_proto.output(0), transposed[0]);
2478         return;
2479     }
2480     addLayer(layerParams, node_proto);
2481 }
2482
2483 void ONNXImporter::parseSqueeze(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
2484 {
2485     CV_Assert_N(node_proto.input_size() == 1, layerParams.has("axes"));
2486     DictValue axes_dict = layerParams.get("axes");
2487     MatShape inpShape = outShapes[node_proto.input(0)];
2488
2489     std::vector<bool> maskedAxes(inpShape.size(), false);
2490     for (int i = 0; i < axes_dict.size(); ++i)
2491     {
2492         int axis = axes_dict.getIntValue(i);
2493         CV_CheckLE(axis, static_cast<int>(inpShape.size()), "Squeeze axis");
2494         maskedAxes[axis] = inpShape[axis] == 1;
2495     }
2496     MatShape outShape;
2497     for (int i = 0; i < inpShape.size(); ++i)
2498     {
2499         if (!maskedAxes[i])
2500             outShape.push_back(inpShape[i]);
2501     }
2502     if (outShape.size() != inpShape.size())
2503     {
2504         layerParams.type = "Reshape";
2505         layerParams.set("dim", DictValue::arrayInt(&outShape[0], outShape.size()));
2506         if (hasDynamicShapes)
2507         {
2508             std::vector<int> dynamicAxes;
2509             std::vector<int> inputIndices;
2510             for (int index = 0; index < inpShape.size(); ++index)
2511             {
2512                 if (!maskedAxes[index])
2513                     inputIndices.push_back(index);
2514             }
2515             for (int index = 0; index < outShape.size(); ++index)
2516                 dynamicAxes.push_back(index);
2517             layerParams.set("dynamic_axes", DictValue::arrayInt(dynamicAxes.data(), dynamicAxes.size()));
2518             layerParams.set("input_indices", DictValue::arrayInt(inputIndices.data(), inputIndices.size()));
2519         }
2520     }
2521     else
2522         layerParams.type = "Identity";
2523
2524     if (constBlobs.find(node_proto.input(0)) != constBlobs.end())
2525     {
2526         Mat inp = getBlob(node_proto, 0);
2527         Mat out = inp.reshape(1, outShape);
2528         out.dims = outShape.size();  // to workaround dims == 1
2529         addConstant(node_proto.output(0), out);
2530         return;
2531     }
2532     int depth = layerParams.get<int>("depth", CV_32F);
2533     layerParams.type += (depth == CV_8S) ? "Int8" : "";
2534     addLayer(layerParams, node_proto);
2535 }
2536
2537 void ONNXImporter::parseFlatten(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto_)
2538 {
2539     opencv_onnx::NodeProto node_proto = node_proto_;
2540     CV_CheckEQ(node_proto.input_size(), 1, "");
2541     int axis_ = layerParams.get<int>("axis", 1);
2542     if (constBlobs.find(node_proto.input(0)) != constBlobs.end())
2543     {
2544         Mat input = getBlob(node_proto, 0);
2545         int axis = normalize_axis(axis_, input.dims);
2546
2547         int out_size[2] = {1, 1};
2548         for (int i = 0; i < axis; ++i)
2549         {
2550             out_size[0] *= input.size[i];
2551         }
2552         for (int i = axis; i < input.dims; ++i)
2553         {
2554             out_size[1] *= input.size[i];
2555         }
2556
2557         Mat output = input.reshape(1, 2, out_size);
2558         addConstant(node_proto.output(0), output);
2559         return;
2560     }
2561     IterShape_t shapeIt = outShapes.find(node_proto.input(0));
2562     CV_Assert(shapeIt != outShapes.end());
2563     MatShape inpShape = shapeIt->second;
2564     int axis = normalize_axis(axis_, inpShape.size());
2565
2566     if (axis == 0 || axis == inpShape.size())
2567     {
2568         LayerParams reshapeLp;
2569         reshapeLp.name = layerParams.name + "/reshape";
2570         reshapeLp.type = "Reshape";
2571         CV_Assert(layer_id.find(reshapeLp.name) == layer_id.end());
2572
2573         inpShape.insert(axis == 0 ? inpShape.begin() : inpShape.end(), 1);
2574         reshapeLp.set("dim", DictValue::arrayInt(&inpShape[0], inpShape.size()));
2575
2576         opencv_onnx::NodeProto proto;
2577         proto.add_input(node_proto.input(0));
2578         proto.add_output(reshapeLp.name);
2579         addLayer(reshapeLp, proto);
2580         node_proto.set_input(0, reshapeLp.name);
2581         axis += 1;
2582     }
2583
2584     LayerParams first_pass;
2585     first_pass.name = layerParams.name + "/flatten";
2586     CV_Assert(layer_id.find(first_pass.name) == layer_id.end());
2587     first_pass.type = "Flatten";
2588     first_pass.set("axis", 0);
2589     first_pass.set("end_axis", axis - 1);
2590
2591     opencv_onnx::NodeProto proto;
2592     proto.add_input(node_proto.input(0));
2593     proto.add_output(first_pass.name);
2594     addLayer(first_pass, proto);
2595
2596     layerParams.set("axis", 1);
2597     node_proto.set_input(0, first_pass.name);
2598     addLayer(layerParams, node_proto);
2599 }
2600
2601 void ONNXImporter::parseUnsqueeze(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
2602 {
2603     CV_Assert(node_proto.input_size() == 1 || node_proto.input_size() == 2);
2604     DictValue axes;
2605     if (node_proto.input_size() == 2)
2606     {
2607         Mat blob = getBlob(node_proto, 1);
2608         axes = DictValue::arrayInt(blob.ptr<int>(), blob.total());
2609     }
2610     else
2611         axes = layerParams.get("axes");
2612
2613     if (constBlobs.find(node_proto.input(0)) != constBlobs.end())
2614     {
2615         // Constant input.
2616         Mat input = getBlob(node_proto, 0);
2617
2618         std::vector<int> dims;
2619         for (int j = 0; j < input.dims; j++) {
2620             dims.push_back(input.size[j]);
2621         }
2622         CV_Assert(axes.getIntValue(axes.size()-1) <= dims.size());
2623         for (int j = 0; j < axes.size(); j++) {
2624             const int idx = axes.getIntValue(j);
2625             CV_Assert(idx <= dims.size());
2626             dims.insert(dims.begin() + idx, 1);
2627         }
2628
2629         Mat out = input.reshape(0, dims);
2630         addConstant(node_proto.output(0), out);
2631         return;
2632     }
2633
2634     // Variable input.
2635     if (axes.size() != 1)
2636         CV_Error(Error::StsNotImplemented, "Multidimensional unsqueeze");
2637
2638     int depth = layerParams.get<int>("depth", CV_32F);
2639
2640     MatShape inpShape = outShapes[node_proto.input(0)];
2641     int axis = axes.getIntValue(0);
2642     CV_Assert(0 <= axis && axis <= inpShape.size());
2643     std::vector<int> outShape = inpShape;
2644     outShape.insert(outShape.begin() + axis, 1);
2645     layerParams.type = (depth == CV_8S) ? "ReshapeInt8" : "Reshape";
2646     layerParams.set("dim", DictValue::arrayInt(&outShape[0], outShape.size()));
2647     if (hasDynamicShapes)
2648     {
2649         std::vector<int> dynamicAxes;
2650         std::vector<int> inputIndices;
2651         for (int index = 0; index < outShape.size(); ++index) {
2652             if (index != axis)
2653                 dynamicAxes.push_back(index);
2654         }
2655         for (int index = 0; index < inpShape.size(); ++index)
2656             inputIndices.push_back(index);
2657         layerParams.set("dynamic_axes", DictValue::arrayInt(dynamicAxes.data(), dynamicAxes.size()));
2658         layerParams.set("input_indices", DictValue::arrayInt(inputIndices.data(), inputIndices.size()));
2659     }
2660     addLayer(layerParams, node_proto);
2661 }
2662
2663 void ONNXImporter::parseExpand(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto_)
2664 {
2665     opencv_onnx::NodeProto node_proto = node_proto_;
2666     CV_CheckEQ(node_proto.input_size(), 2, "");
2667     const std::string& input0 = node_proto.input(0);
2668     const std::string& input1 = node_proto.input(1);
2669     const std::string output_name = node_proto.output(0);
2670     Mat newShapeMat = getBlob(input1);
2671     MatShape targetShape(newShapeMat.ptr<int>(), newShapeMat.ptr<int>() + newShapeMat.total());
2672
2673     MatShape inpShape;
2674     bool haveVariables = constBlobs.find(input0) == constBlobs.end();
2675     if (haveVariables)
2676     {
2677         IterShape_t shapeIt = outShapes.find(input0);
2678         CV_Assert(shapeIt != outShapes.end());
2679         inpShape = shapeIt->second;
2680     }
2681     else
2682     {
2683         inpShape = shape(getBlob(input0));
2684     }
2685
2686     String srcName = input0;
2687     // Unsqueeze and repeat along new axis
2688     if (targetShape.size() == inpShape.size() + 1)
2689     {
2690         inpShape.insert(inpShape.begin(), targetShape.size() - inpShape.size(), 1);
2691         for (int i = 0; i < targetShape.size(); i++)
2692         {
2693             if (abs(targetShape[i]) == 1)
2694                 targetShape[i] = inpShape[i];
2695         }
2696         if (haveVariables)
2697         {
2698             LayerParams reshapeLp;
2699             reshapeLp.name = layerParams.name + "/reshape";
2700             reshapeLp.type = "Reshape";
2701             CV_Assert(layer_id.find(reshapeLp.name) == layer_id.end());
2702             reshapeLp.set("dim", DictValue::arrayInt(&inpShape[0], inpShape.size()));
2703
2704             opencv_onnx::NodeProto proto;
2705             proto.add_input(node_proto.input(0));
2706             proto.add_output(reshapeLp.name);
2707             addLayer(reshapeLp, proto);
2708             srcName = reshapeLp.name;
2709         }
2710     }
2711     CV_CheckEQ(inpShape.size(), targetShape.size(), "Unsupported Expand op with different dims");
2712
2713     std::vector<int> broadcast_axes;
2714     // shapes aren't right-aligned here because targetShape.size() == inpShape.size()
2715     for (int i = 0; i < targetShape.size(); i++)
2716     {
2717         if (targetShape[i] != inpShape[i])
2718         {
2719             if (inpShape[i] == 1)
2720             {
2721                 broadcast_axes.push_back(i);
2722             }
2723             else if (targetShape[i] != 1)
2724             {
2725                 CV_Error(Error::StsError, format("Could not be broadcast by axis: %d", i));
2726             }
2727         }
2728     }
2729
2730     if (!haveVariables)
2731     {
2732         if (broadcast_axes.size() > 1)
2733             CV_Error(Error::StsNotImplemented, "Expand op doesn't support multiple axes for constant input");
2734
2735         if (broadcast_axes.empty())
2736         {
2737             addConstant(output_name, getBlob(node_proto, 0));
2738             return;
2739         }
2740
2741         Mat input = getBlob(node_proto, 0);
2742         input = input.reshape(0, total(inpShape, 0, broadcast_axes[0]));
2743         Mat output = cv::repeat(input, 1, targetShape[broadcast_axes[0]]);
2744         output = output.reshape(0, targetShape);
2745         addConstant(output_name, output);
2746         return;
2747     }
2748
2749     if (broadcast_axes.size() == 2 &&
2750         broadcast_axes[0] == broadcast_axes[1] - 1 && broadcast_axes[1] == inpShape.size() - 1)
2751     {
2752         LayerParams constParams;
2753         constParams.name = layerParams.name + "/const";
2754         CV_Assert(layer_id.find(constParams.name) == layer_id.end());
2755         constParams.type = "Const";
2756
2757         Mat inp = Mat::ones(newShapeMat.total(), newShapeMat.ptr<int>(), CV_32F);
2758         constParams.blobs.push_back(inp);
2759
2760         opencv_onnx::NodeProto proto;
2761         proto.add_output(constParams.name);
2762         addLayer(constParams, proto);
2763
2764         layerParams.type = "Scale";
2765         layerParams.set("bias_term", false);
2766         node_proto.set_input(0, constParams.name);
2767         node_proto.set_input(1, srcName);
2768     }
2769     else if (broadcast_axes.size() == 1 && broadcast_axes[0] <= 1)
2770     {
2771         expandMid(layerParams.name, node_proto, srcName, targetShape[broadcast_axes[0]]);
2772
2773         layerParams.set("axis", broadcast_axes[0]);
2774         layerParams.type = "Concat";
2775         node_proto.set_output(0, output_name);
2776     }
2777     else if (broadcast_axes.empty())
2778     {
2779         layerParams.type = "Identity";
2780     }
2781     else
2782         CV_Error(Error::StsNotImplemented, "Unsupported Expand op");
2783     addLayer(layerParams, node_proto);
2784 }
2785
2786 void ONNXImporter::parseReshape(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
2787 {
2788     CV_Assert(node_proto.input_size() == 2 || layerParams.has("shape"));
2789     int depth = layerParams.get<int>("depth", CV_32F);
2790     layerParams.type += (depth == CV_8S) ? "Int8" : "";
2791
2792     if (node_proto.input_size() == 2) {
2793         Mat blob = getBlob(node_proto, 1);
2794         CV_Assert(blob.type() == CV_32SC1);
2795
2796         layerParams.set("dim", DictValue::arrayInt<int*>(blob.ptr<int>(), blob.total()));
2797
2798         if (layer_id.find(node_proto.input(0)) == layer_id.end()) {
2799             std::vector<Mat> inputs(1, getBlob(node_proto, 0)), outputs;
2800             runLayer(layerParams, inputs, outputs);
2801             addConstant(node_proto.output(0), outputs[0]);
2802             return;
2803         }
2804     }
2805     else {
2806         DictValue shape = layerParams.get("shape");
2807         std::vector<int> dim;
2808         for (int j = 0; j < shape.size(); j++) {
2809             dim.push_back(shape.getIntValue(j));
2810         }
2811
2812         if (layer_id.find(node_proto.input(0)) == layer_id.end()) {
2813             Mat input = getBlob(node_proto, 0);
2814             Mat out = input.reshape(0, dim);
2815             addConstant(node_proto.output(0), out);
2816             return;
2817         }
2818         replaceLayerParam(layerParams, "shape", "dim");
2819     }
2820     addLayer(layerParams, node_proto);
2821 }
2822
2823 void ONNXImporter::parsePad(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
2824 {
2825     int depth = layerParams.get<int>("depth", CV_32F);
2826     layerParams.type = (depth == CV_8S) ? "PaddingInt8" : "Padding";
2827     replaceLayerParam(layerParams, "mode", "type");
2828     if (node_proto.input_size() == 3 || node_proto.input_size() == 2)
2829     {
2830         // Paddings are in order begin0, begin1, .. beginN, end0, end1, ..., endN.
2831         // We need to shuffle it to begin0, end0, begin1, end1, ...
2832         Mat paddings = getBlob(node_proto, 1).reshape(1, 2);
2833         paddings = paddings.t();
2834         layerParams.set("paddings", DictValue::arrayInt(paddings.ptr<int>(), paddings.total()));
2835
2836         if (node_proto.input_size() == 3)
2837         {
2838             Mat value = getBlob(node_proto, 2);
2839             float padValue = (depth == CV_8S) ? (float)value.ptr<int8_t>()[0] : value.ptr<float>()[0];
2840             layerParams.set("value", padValue);
2841         }
2842     }
2843     addLayer(layerParams, node_proto);
2844 }
2845
2846 void ONNXImporter::parseShape(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
2847 {
2848     CV_Assert(node_proto.input_size() == 1);
2849     IterShape_t shapeIt = outShapes.find(node_proto.input(0));
2850     CV_Assert(shapeIt != outShapes.end());
2851     const MatShape& inpShape = shapeIt->second;
2852
2853     int dims = static_cast<int>(inpShape.size());
2854     Mat shapeMat(dims, 1, CV_32S);
2855     bool isDynamicShape = false;
2856     for (int j = 0; j < dims; ++j)
2857     {
2858         int sz = inpShape[j];
2859         isDynamicShape |= (sz == 0);
2860         shapeMat.at<int>(j) = sz;
2861     }
2862     shapeMat.dims = 1;  // FIXIT Mat 1D
2863
2864     if (isDynamicShape)
2865     {
2866         CV_LOG_ERROR(NULL, "DNN/ONNX(Shape): dynamic 'zero' shapes are not supported, input " << toString(inpShape, node_proto.input(0)));
2867         CV_Assert(!isDynamicShape);  // not supported
2868     }
2869     addConstant(node_proto.output(0), shapeMat);
2870 }
2871
2872 void ONNXImporter::parseCast(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
2873 {
2874     if (constBlobs.find(node_proto.input(0)) != constBlobs.end())
2875     {
2876         Mat blob = getBlob(node_proto, 0);
2877         int type;
2878         switch (layerParams.get<int>("to"))
2879         {
2880             case opencv_onnx::TensorProto_DataType_FLOAT:   type = CV_32F; break;
2881             case opencv_onnx::TensorProto_DataType_UINT8:   type = CV_8U; break;
2882             case opencv_onnx::TensorProto_DataType_UINT16:  type = CV_16U; break;
2883             case opencv_onnx::TensorProto_DataType_FLOAT16: type = CV_16S; break;
2884             case opencv_onnx::TensorProto_DataType_INT8:
2885             case opencv_onnx::TensorProto_DataType_INT16:
2886             case opencv_onnx::TensorProto_DataType_INT32:
2887             case opencv_onnx::TensorProto_DataType_INT64:   type = CV_32S; break;
2888             default: type = blob.type();
2889         }
2890         Mat dst;
2891         blob.convertTo(dst, type);
2892         dst.dims = blob.dims;
2893         addConstant(node_proto.output(0), dst);
2894         return;
2895     }
2896     else
2897         layerParams.type = "Identity";
2898     addLayer(layerParams, node_proto);
2899 }
2900
2901 void ONNXImporter::parseConstantFill(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
2902 {
2903     int depth = CV_32F;
2904     float fill_value;
2905     if (!layerParams.blobs.empty())
2906     {
2907         CV_Assert(!layerParams.has("value"));
2908         depth = layerParams.blobs[0].depth();
2909         Mat floats;
2910         layerParams.blobs[0].convertTo(floats, CV_32F);
2911         fill_value = floats.at<float>(0, 0);
2912     }
2913     else
2914         fill_value = layerParams.get("value", 0);
2915
2916     MatShape inpShape = getBlob(node_proto, 0);
2917     for (int i = 0; i < inpShape.size(); i++)
2918         CV_CheckGT(inpShape[i], 0, "");
2919     Mat tensor(inpShape.size(), &inpShape[0], depth, Scalar(fill_value));
2920     addConstant(node_proto.output(0), tensor);
2921 }
2922
2923 void ONNXImporter::parseGather(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto_)
2924 {
2925     opencv_onnx::NodeProto node_proto = node_proto_;
2926     CV_Assert(node_proto.input_size() == 2);
2927     Mat indexMat = getBlob(node_proto, 1);
2928     CV_Assert_N(indexMat.type() == CV_32S, indexMat.total() == 1);
2929     int index = indexMat.at<int>(0);
2930     int axis = layerParams.get<int>("axis", 0);
2931
2932     if ((constBlobs.find(node_proto.input(0)) != constBlobs.end()))
2933     {
2934         Mat input = getBlob(node_proto, 0);
2935         Mat out;
2936         std::vector<cv::Range> ranges(input.dims, Range::all());
2937         ranges[axis] = Range(index, index + 1);
2938
2939         out = input(ranges);
2940         MatShape outShape = shape(out);
2941         if (outShape.size() > 1)
2942         {
2943             outShape.erase(outShape.begin() + axis);
2944             out.reshape(0, outShape);
2945         } else {
2946             out.dims = 1;
2947         }
2948         addConstant(node_proto.output(0), out);
2949         return;
2950     }
2951     else
2952     {
2953         IterShape_t shapeIt = outShapes.find(node_proto.input(0));
2954         CV_Assert(shapeIt != outShapes.end());
2955         MatShape inpShape = shapeIt->second;
2956
2957         LayerParams sliceLp;
2958         sliceLp.type = "Slice";
2959         sliceLp.name = inpShape.size() > 1 ? layerParams.name + "/slice" : layerParams.name;
2960         std::vector<int> begin(inpShape.size(), 0);
2961         std::vector<int> end(inpShape.size(), INT_MAX);
2962         begin[axis] = index;
2963         end[axis] = index + 1;
2964
2965         cv::dnn::DictValue paramBegin = cv::dnn::DictValue::arrayInt(begin.data(), begin.size());
2966         cv::dnn::DictValue paramEnd = cv::dnn::DictValue::arrayInt(end.data(), end.size());
2967         sliceLp.set("begin", paramBegin);
2968         sliceLp.set("end", paramEnd);
2969         sliceLp.set("has_dynamic_shapes", hasDynamicShapes);
2970
2971         if (inpShape.size() > 1)
2972         {
2973             opencv_onnx::NodeProto proto;
2974             proto.add_input(node_proto.input(0));
2975             proto.add_output(sliceLp.name);
2976             addLayer(sliceLp, proto);
2977
2978             inpShape.erase(inpShape.begin() + axis);
2979             layerParams.type = "Reshape";
2980             layerParams.set("axis", 0);
2981             layerParams.set("dim", DictValue::arrayInt(&inpShape[0], inpShape.size()));
2982             if (hasDynamicShapes)
2983             {
2984                 std::vector<int> dynamicAxes;
2985                 std::vector<int> inputIndices;
2986                 for (int index = 0; index < inpShape.size(); ++index)
2987                     dynamicAxes.push_back(index);
2988                 for (int index = 0; index < inpShape.size(); ++index)
2989                     inputIndices.push_back(index);
2990                 layerParams.set("dynamic_axes", DictValue::arrayInt(dynamicAxes.data(), dynamicAxes.size()));
2991                 layerParams.set("input_indices", DictValue::arrayInt(inputIndices.data(), inputIndices.size()));
2992             }
2993             node_proto.set_input(0, sliceLp.name);
2994         }
2995         else
2996         {
2997             layerParams = sliceLp;
2998         }
2999     }
3000     addLayer(layerParams, node_proto);
3001 }
3002
3003 void ONNXImporter::parseConcat(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
3004 {
3005     bool hasVariableInps = false;
3006     for (int i = 0; i < node_proto.input_size(); ++i)
3007     {
3008         if (layer_id.find(node_proto.input(i)) != layer_id.end())
3009         {
3010             hasVariableInps = true;
3011             break;
3012         }
3013     }
3014
3015     if (!hasVariableInps)
3016     {
3017         std::vector<Mat> inputs(node_proto.input_size()), concatenated;
3018         // Due constant folding we can get inputs with different number of dimensions
3019         // Insert the missing dimension to inputs
3020         MatShape inputShape;
3021         for (size_t i = 0; i < inputs.size(); ++i)
3022         {
3023             inputs[i] = getBlob(node_proto, i);
3024             if (inputs[i].size.dims() > inputShape.size())
3025             {
3026                 inputShape = shape(inputs[i]);
3027             }
3028         }
3029
3030         // Concat-1 has default value for axis is 1: https://github.com/onnx/onnx/blob/master/docs/Changelog.md#Concat-1
3031         int axis = layerParams.get<int>("axis", 1);
3032         for (size_t i = 0; i < inputs.size(); ++i)
3033         {
3034             MatShape targetShape = inputShape;
3035             targetShape[axis] = shape(inputs[i])[axis];
3036             CV_CheckEQ(total(targetShape), total(shape(inputs[i])), "");
3037             inputs[i] = inputs[i].reshape(0, targetShape);
3038         }
3039         runLayer(layerParams, inputs, concatenated);
3040
3041         CV_Assert(concatenated.size() == 1);
3042         addConstant(node_proto.output(0), concatenated[0]);
3043         return;
3044     }
3045     else
3046     {
3047         for (int i = 0; i < node_proto.input_size(); ++i)
3048         {
3049             if (constBlobs.find(node_proto.input(i)) != constBlobs.end())
3050             {
3051                 LayerParams constParams;
3052                 constParams.name = node_proto.input(i);
3053                 constParams.type = "Const";
3054                 constParams.blobs.push_back(getBlob(node_proto, i));
3055
3056                 opencv_onnx::NodeProto proto;
3057                 proto.add_output(constParams.name);
3058                 addLayer(constParams, proto);
3059             }
3060         }
3061     }
3062     addLayer(layerParams, node_proto);
3063 }
3064
3065 // https://github.com/onnx/onnx/blob/master/docs/Operators.md#Resize
3066 void ONNXImporter::parseResize(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
3067 {
3068     for (int i = 1; i < node_proto.input_size(); i++)
3069         CV_Assert(layer_id.find(node_proto.input(i)) == layer_id.end());
3070
3071     int depth = layerParams.get<int>("depth", CV_32F);
3072     layerParams.type += (depth == CV_8S) ? "Int8" : "";
3073
3074     if (layerParams.has("coordinate_transformation_mode"))
3075     {
3076         String interp_mode = layerParams.get<String>("coordinate_transformation_mode");
3077         CV_Assert_N(interp_mode != "tf_crop_and_resize", interp_mode != "tf_half_pixel_for_nn");
3078
3079         layerParams.set("align_corners", interp_mode == "align_corners");
3080         if (layerParams.get<String>("mode") == "linear")
3081         {
3082             layerParams.set("mode", interp_mode == "pytorch_half_pixel" || interp_mode == "half_pixel" ?
3083                                     "opencv_linear" : "bilinear");
3084         }
3085     }
3086     if (layerParams.get<String>("mode") == "linear" && framework_name == "pytorch")
3087         layerParams.set("mode", "opencv_linear");
3088
3089     // opset-10: input = [X, scales]
3090     // opset-11: input = [X, roi, scales] or [x, roi, scales, sizes]
3091     // opset-13: may have empty input, [X, "", "", sizes] or [x, "", scales]
3092     int scalesInputId = node_proto.input_size() == 2 ? 1 : 2;
3093     const std::string& scale_name = node_proto.input(scalesInputId);
3094     Mat scales;
3095     if(!scale_name.empty())
3096         scales = getBlob(node_proto, scalesInputId);
3097
3098     if (!scales.empty())
3099     {
3100         CV_CheckEQ(scales.total(), (size_t)4, "HCHW layout is expected");
3101         layerParams.set("zoom_factor_y", scales.at<float>(2));
3102         layerParams.set("zoom_factor_x", scales.at<float>(3));
3103     }
3104     else if (node_proto.input_size() >= 4)  // opset-11 [x, roi, scales, sizes] or opset-13: input = [X, "", "", sizes]
3105     {
3106         const std::string& inputSizes = node_proto.input(3);
3107         if (constBlobs.find(inputSizes) != constBlobs.end())
3108         {
3109             Mat shapes = getBlob(inputSizes);
3110             CV_CheckEQ(shapes.total(), (size_t)4, "HCHW layout is expected");
3111             CV_CheckDepth(shapes.depth(), shapes.depth() == CV_32S || shapes.depth() == CV_32F, "");
3112             if (shapes.depth() == CV_32F)
3113                 shapes.convertTo(shapes, CV_32S);
3114             layerParams.set("width", shapes.at<int>(3));
3115             layerParams.set("height", shapes.at<int>(2));
3116         }
3117         else
3118         {
3119             CV_Error(Error::StsNotImplemented, cv::format("ONNX/Resize: doesn't support dynamic non-constant 'sizes' input: %s", inputSizes.c_str()));
3120         }
3121     }
3122     else
3123     {
3124         CV_Error(Error::StsNotImplemented, "ONNX/Resize: can't find neither 'scale' nor destination sizes parameters");
3125     }
3126     replaceLayerParam(layerParams, "mode", "interpolation");
3127     addLayer(layerParams, node_proto);
3128 }
3129
3130 void ONNXImporter::parseUpsample(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
3131 {
3132     //fused from Resize Subgraph
3133     if (layerParams.has("coordinate_transformation_mode"))
3134     {
3135         String interp_mode = layerParams.get<String>("coordinate_transformation_mode");
3136         CV_Assert_N(interp_mode != "tf_crop_and_resize", interp_mode != "tf_half_pixel_for_nn");
3137
3138         layerParams.set("align_corners", interp_mode == "align_corners");
3139         if (layerParams.get<String>("mode") == "linear")
3140         {
3141             layerParams.set("mode", interp_mode == "pytorch_half_pixel" ?
3142                                     "opencv_linear" : "bilinear");
3143         }
3144     }
3145     if (layerParams.get<String>("mode") == "linear" && framework_name == "pytorch")
3146         layerParams.set("mode", "opencv_linear");
3147
3148     layerParams.type = "Resize";
3149     if (layerParams.has("scales"))
3150     {
3151         // Pytorch layer
3152         DictValue scales = layerParams.get("scales");
3153         CV_Assert(scales.size() == 4);
3154         layerParams.set("zoom_factor_y", scales.getIntValue(2));
3155         layerParams.set("zoom_factor_x", scales.getIntValue(3));
3156     }
3157     else if (layerParams.has("height_scale") && layerParams.has("width_scale"))
3158     {
3159         // Caffe2 layer
3160         replaceLayerParam(layerParams, "height_scale", "zoom_factor_y");
3161         replaceLayerParam(layerParams, "width_scale", "zoom_factor_x");
3162     }
3163     else
3164     {
3165         // scales as input
3166         const std::string& input1 = node_proto.input(1);
3167         if (constBlobs.find(input1) != constBlobs.end())
3168         {
3169             Mat scales = getBlob(input1);
3170             CV_Assert(scales.total() == 4);
3171             layerParams.set("zoom_factor_y", scales.at<float>(2));
3172             layerParams.set("zoom_factor_x", scales.at<float>(3));
3173         }
3174     }
3175     replaceLayerParam(layerParams, "mode", "interpolation");
3176     addLayer(layerParams, node_proto);
3177 }
3178
3179 void ONNXImporter::parseSoftMax(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
3180 {
3181     const std::string& layer_type = node_proto.op_type();
3182     layerParams.type = "Softmax";
3183     layerParams.set("log_softmax", layer_type == "LogSoftmax");
3184     addLayer(layerParams, node_proto);
3185 }
3186
3187 void ONNXImporter::parseDetectionOutput(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto_)
3188 {
3189     opencv_onnx::NodeProto node_proto = node_proto_;
3190     CV_CheckEQ(node_proto.input_size(), 3, "");
3191     if (constBlobs.find(node_proto.input(2)) != constBlobs.end())
3192     {
3193         Mat priors = getBlob(node_proto, 2);
3194
3195         LayerParams constParams;
3196         constParams.name = layerParams.name + "/priors";
3197         constParams.type = "Const";
3198         constParams.blobs.push_back(priors);
3199
3200         opencv_onnx::NodeProto priorsProto;
3201         priorsProto.add_output(constParams.name);
3202         addLayer(constParams, priorsProto);
3203
3204         node_proto.set_input(2, constParams.name);
3205     }
3206     addLayer(layerParams, node_proto);
3207 }
3208
3209 void ONNXImporter::parseCumSum(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
3210 {
3211     layerParams.type = "CumSum";
3212
3213     // Get axis.
3214     const std::string& input1 = node_proto.input(1);
3215
3216     if (constBlobs.find(input1) != constBlobs.end())
3217     {
3218         Mat axis_blob = getBlob(input1);
3219         CV_Assert(axis_blob.total() == 1u);
3220         layerParams.set("axis", axis_blob.at<int>(0));
3221     }
3222
3223     addLayer(layerParams, node_proto);
3224 }
3225
3226 void ONNXImporter::parseDepthToSpace(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto_)
3227 {
3228     // We parse "DepthToSpace" and "SpaceToDepth" in this function.
3229     opencv_onnx::NodeProto node_proto = node_proto_;
3230     const std::string& layer_type = node_proto.op_type();
3231     CV_Assert(layer_type == "DepthToSpace" || layer_type == "SpaceToDepth");
3232
3233     // Get blocksize
3234     CV_Assert(layerParams.has("blocksize"));
3235     int blocksize = layerParams.get<int>("blocksize");
3236     CV_Assert(blocksize > 0);
3237
3238     // Get mode, only for "DepthToSpace"
3239     std::string modeType = layerParams.get<std::string>("mode", "DCR");
3240
3241     MatShape inpShape = outShapes[node_proto.input(0)];
3242     CV_Assert(inpShape.size() == 4);
3243     int N = inpShape[0], C = inpShape[1], H = inpShape[2], W = inpShape[3];
3244
3245     // Implement DepthToSpace and SpaceToDepth by the Reshape and Permute layer.
3246     std::array<int, 6> shape0, perm;
3247     std::array<int, 4> shape1;
3248
3249     if (layer_type == "DepthToSpace")
3250     {
3251         if (modeType == "DCR")
3252         {
3253             shape0 = {N, blocksize, blocksize, C/(blocksize * blocksize), H, W};
3254             perm = {0, 3, 4, 1, 5, 2};
3255             shape1 = {N, C/(blocksize * blocksize), H * blocksize, W * blocksize};
3256         }
3257         else if (modeType == "CRD")
3258         {
3259             shape0 = {N, C/(blocksize * blocksize), blocksize, blocksize, H, W};
3260             perm = {0, 1, 4, 2, 5, 3};
3261             shape1 = {N, C/(blocksize * blocksize), H * blocksize, W * blocksize};
3262         }
3263         else
3264             CV_Error(Error::StsNotImplemented, "The mode of " + modeType + " in " + layer_type + " Layer is not supported");
3265     }
3266     else // SpaceToDepth
3267     {
3268         shape0 = {N, C, H/blocksize, blocksize, W/blocksize, blocksize};
3269         perm = {0, 3, 5, 1, 2, 4};
3270         shape1 = {N, C * blocksize * blocksize, H/blocksize, W/blocksize};
3271     }
3272
3273     // Step1: Reshape
3274     LayerParams reshapeLp;
3275     reshapeLp.name = layerParams.name + "/reshape";
3276     reshapeLp.type = "Reshape";
3277     CV_Assert(layer_id.find(reshapeLp.name) == layer_id.end());
3278     reshapeLp.set("dim", DictValue::arrayInt(shape0.data(), shape0.size()));
3279
3280     opencv_onnx::NodeProto protoReshape;
3281     protoReshape.add_input(node_proto.input(0));
3282     protoReshape.add_output(reshapeLp.name);
3283     addLayer(reshapeLp, protoReshape);
3284
3285     // Step2: Transpose
3286     LayerParams permuteLp;
3287     permuteLp.name = layerParams.name + "/permute";
3288     permuteLp.type = "Permute";
3289     CV_Assert(layer_id.find(permuteLp.name) == layer_id.end());
3290     permuteLp.set("order", DictValue::arrayInt(perm.data(), perm.size()));
3291
3292     opencv_onnx::NodeProto protoPermute;
3293     protoPermute.add_input(reshapeLp.name);
3294     protoPermute.add_output(permuteLp.name);
3295     addLayer(permuteLp, protoPermute);
3296
3297     // Step3: Reshape
3298     layerParams.type = "Reshape";
3299     layerParams.set("dim", DictValue::arrayInt(shape1.data(), shape1.size()));
3300
3301     node_proto.set_input(0, permuteLp.name);
3302     addLayer(layerParams, node_proto);
3303 }
3304
3305 void ONNXImporter::parseSimpleLayers(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
3306 {
3307     for (int j = 0; j < node_proto.input_size(); j++) {
3308         if (layer_id.find(node_proto.input(j)) == layer_id.end())
3309             layerParams.blobs.push_back(getBlob(node_proto, j));
3310     }
3311     addLayer(layerParams, node_proto);
3312 }
3313
3314 void ONNXImporter::parseCustomLayer(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
3315 {
3316     const std::string& name = layerParams.name;
3317     std::string& layer_type = layerParams.type;
3318     const std::string& layer_type_domain = node_proto.has_domain() ? node_proto.domain() : std::string();
3319     if (!layer_type_domain.empty() && layer_type_domain != str_domain_ai_onnx)
3320     {
3321         // append ONNX domain name
3322         static bool DNN_CUSTOM_ONNX_TYPE_INCLUDE_DOMAIN_NAME = utils::getConfigurationParameterBool("OPENCV_DNN_CUSTOM_ONNX_TYPE_INCLUDE_DOMAIN_NAME", true);
3323         if (DNN_CUSTOM_ONNX_TYPE_INCLUDE_DOMAIN_NAME)
3324         {
3325             layer_type = layer_type_domain + "." + layer_type;
3326         }
3327     }
3328
3329     CV_LOG_IF_INFO(NULL, !LayerFactory::isLayerRegistered(layer_type), "DNN/ONNX: unknown node type, try using custom handler for node with " << node_proto.input_size() << " inputs and " << node_proto.output_size() << " outputs: "
3330             << cv::format("[%s]:(%s)", layer_type.c_str(), name.c_str())
3331     );
3332
3333     parseSimpleLayers(layerParams, node_proto);
3334 }
3335
3336 void ONNXImporter::parseQuantDequant(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
3337 {
3338     CV_Assert(node_proto.input_size() == 3);
3339     layerParams.type = (node_proto.op_type() == "QuantizeLinear") ? "Quantize" : "Dequantize";
3340
3341     if (node_proto.op_type() == "DequantizeLinear")
3342     {
3343         Mat scale = getBlob(node_proto, 1);
3344         Mat zeropoint = getBlob(node_proto, 2);
3345
3346         layerParams.set("scales", DictValue::arrayReal(scale.ptr<float>(), 1));
3347         layerParams.set("zeropoints", DictValue::arrayInt(zeropoint.ptr<int8_t>(), 1));
3348     }
3349     addLayer(layerParams, node_proto);
3350 }
3351
3352 void ONNXImporter::parseQConv(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto_)
3353 {
3354     opencv_onnx::NodeProto node_proto = node_proto_;
3355     int ninputs = node_proto.input_size();
3356     CV_Assert(ninputs == 8 || ninputs == 9);
3357
3358     Mat inp_sc = getBlob(node_proto, 1);
3359     Mat inp_zp = getBlob(node_proto, 2);
3360
3361     if (layerParams.has("pad"))
3362     {
3363         bool asymmetricPadding = false;
3364         DictValue pads = layerParams.get("pad");
3365         const int dims = pads.size() / 2;
3366
3367         for (int i = 0; i < dims; ++i)
3368         {
3369             if (pads.get<int>(i) != pads.get<int>(i + dims))
3370             {
3371                 asymmetricPadding = true;
3372                 break;
3373             }
3374         }
3375         if (asymmetricPadding && pads.size() == 4)
3376         {
3377             layerParams.erase("pad");
3378             std::vector<int> paddings(4, 0);
3379             for (int i = 0; i < dims; ++i)
3380             {
3381                 paddings.push_back(pads.get<int>(i));
3382                 paddings.push_back(pads.get<int>(dims + i));
3383             }
3384             LayerParams padLp;
3385             padLp.name = layerParams.name + "/pad";
3386             padLp.type = "PaddingInt8";
3387             padLp.set("paddings", DictValue::arrayInt(&paddings[0], paddings.size()));
3388             padLp.set("depth", CV_8S);
3389             padLp.set("value", inp_zp.at<int8_t>(0));
3390
3391             opencv_onnx::NodeProto proto;
3392             proto.add_input(node_proto.input(0));
3393             proto.add_output(padLp.name);
3394
3395             addLayer(padLp, proto);
3396             node_proto.set_input(0, padLp.name);
3397         }
3398     }
3399
3400     Mat weights = getBlob(node_proto, 3);
3401     int outCn = weights.size[0];
3402     Mat w_scale = getBlob(node_proto, 4);
3403     CV_Assert(w_scale.total() == 1 || w_scale.total() == outCn);
3404     bool per_channel = w_scale.total() == outCn ? true : false;
3405     Mat wt_sc = (w_scale.total() == outCn) ? w_scale : Mat(1, outCn, CV_32F, Scalar(w_scale.at<float>(0)));
3406
3407     Mat out_sc = getBlob(node_proto, 6);
3408     Mat bias = (ninputs == 9) ? getBlob(node_proto, 8) : Mat::zeros(1, outCn, CV_32S);
3409
3410     Mat weights_2d = weights.reshape(1, outCn);
3411     Mat biasFused(1, outCn, CV_32S);
3412     Mat outputMultiplier(1, outCn, CV_32F);
3413     for (int i = 0; i < outCn; i++)
3414     {
3415         biasFused.at<int>(i) = bias.at<int>(i) - inp_zp.at<int8_t>(0)*(cv::sum(weights_2d.row(i))[0]);
3416         outputMultiplier.at<float>(i) = (inp_sc.at<float>(0) * wt_sc.at<float>(i)) / out_sc.at<float>(0);
3417     }
3418
3419     layerParams.type = "ConvolutionInt8";
3420     layerParams.set("num_output", outCn);
3421     layerParams.set("input_zeropoint", inp_zp.at<int8_t>(0));
3422     layerParams.set("input_scale",inp_sc.at<float>(0));
3423     layerParams.set("per_channel", per_channel);
3424     layerParams.blobs.push_back(weights);
3425     layerParams.blobs.push_back(biasFused);
3426     layerParams.blobs.push_back(outputMultiplier);
3427     addLayer(layerParams, node_proto);
3428 }
3429
3430 void ONNXImporter::parseQMatMul(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
3431 {
3432     int ninputs = node_proto.input_size();
3433     CV_Assert(ninputs == 8);
3434
3435     if (constBlobs.find(node_proto.input(3)) == constBlobs.end())
3436         CV_Error(Error::StsNotImplemented, "Variable weights is not supported");
3437
3438     int firstInpDims = outShapes[node_proto.input(0)].size();
3439
3440     Mat inp_sc = getBlob(node_proto, 1);
3441     Mat inp_zp = getBlob(node_proto, 2);
3442
3443     Mat weights = getBlob(node_proto, 3).t();
3444     int outCn = weights.size[0];
3445     int secondInpDims = weights.dims;
3446
3447     Mat w_scale = getBlob(node_proto, 4);
3448     CV_Assert(w_scale.total() == 1 || w_scale.total() == outCn);
3449     bool per_channel = w_scale.total() == outCn ? true : false;
3450     Mat wt_sc = (w_scale.total() == outCn) ? w_scale : Mat(1, outCn, CV_32F, Scalar(w_scale.at<float>(0)));
3451     Mat out_sc = getBlob(node_proto, 6);
3452
3453     Mat bias(1, outCn, CV_32S);
3454     Mat outputMultiplier(1, outCn, CV_32F);
3455     for (int i = 0; i < outCn; i++)
3456     {
3457         bias.at<int>(i) = -inp_zp.at<int8_t>(0)*(cv::sum(weights.row(i))[0]);
3458         outputMultiplier.at<float>(i) = (inp_sc.at<float>(0) * wt_sc.at<float>(i)) / out_sc.at<float>(0);
3459     }
3460
3461     layerParams.type = "InnerProductInt8";
3462     layerParams.set("num_output", outCn);
3463     layerParams.set("axis", firstInpDims - secondInpDims + 1);
3464     layerParams.set("input_scale", inp_sc.at<float>(0));
3465     layerParams.set("input_zeropoint", inp_zp.at<int8_t>(0));
3466     layerParams.set("per_channel", per_channel);
3467
3468     layerParams.blobs.push_back(weights);
3469     layerParams.blobs.push_back(bias);
3470     layerParams.blobs.push_back(outputMultiplier);
3471     addLayer(layerParams, node_proto);
3472 }
3473
3474 void ONNXImporter::parseQEltwise(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto_)
3475 {
3476     opencv_onnx::NodeProto node_proto = node_proto_;
3477     CV_Assert(node_proto.input_size() == 8);
3478     std::string op = (node_proto.op_type() == "QLinearAdd") ? "sum" : "prod";
3479     int constId = -1;
3480     for (int i = 0; i < 4; i += 3)
3481     {
3482         if (constBlobs.find(node_proto.input(i)) != constBlobs.end())
3483             constId = i;
3484     }
3485
3486     Mat inp_0_sc = getBlob(node_proto, 1);
3487     Mat inp_0_zp = getBlob(node_proto, 2);
3488
3489     Mat inp_1_sc = getBlob(node_proto, 4);
3490     Mat inp_1_zp = getBlob(node_proto, 5);
3491
3492     // Set 2nd input as the const input
3493     if (constId == 0)
3494     {
3495         cv::swap(inp_0_sc, inp_1_sc);
3496         cv::swap(inp_0_zp, inp_1_zp);
3497     }
3498
3499     float out_sc = getBlob(node_proto, 6).at<float>(0);
3500     int8_t out_zp = getBlob(node_proto, 7).at<int8_t>(0);
3501
3502     std::vector<float> inp_scales = {inp_0_sc.at<float>(0), inp_1_sc.at<float>(0)};
3503     std::vector<int8_t> inp_zps = {inp_0_zp.at<int8_t>(0), inp_1_zp.at<int8_t>(0)};
3504
3505     std::vector<float> coeffs;
3506     float offset;
3507     if (op == "sum")
3508     {
3509         coeffs = {inp_scales[0]/out_sc, inp_scales[1]/out_sc};
3510         offset = out_zp - coeffs[0]*inp_zps[0] - coeffs[1]*inp_zps[1];
3511     }
3512     else
3513     {
3514         coeffs = {inp_scales[0]/out_sc, inp_scales[1]};
3515         offset = out_zp;
3516     }
3517
3518     if (constId != -1)
3519     {
3520         Mat blob = getBlob(node_proto, constId);
3521         if (blob.total() == 1)
3522         {
3523             float val = inp_scales[1] * (blob.at<int8_t>(0) - inp_zps[1]);
3524             float scale = inp_scales[0] / out_sc;
3525             if (op == "prod")
3526                 scale *= val;
3527
3528             float shift = out_zp - scale*inp_zps[0];
3529             if (op == "sum")
3530                 shift += (val/out_sc);
3531
3532             LayerParams rescaleParams;
3533             rescaleParams.name = layerParams.name;
3534             rescaleParams.type = "Requantize";
3535             rescaleParams.set("depth", CV_8S);
3536             rescaleParams.set("scale", scale);
3537             rescaleParams.set("shift", shift);
3538             rescaleParams.set("isEltwise", true);
3539             addLayer(rescaleParams, node_proto);
3540             return;
3541         }
3542         else
3543         {
3544             MatShape inpShape = outShapes[node_proto.input(3 - constId)];
3545             if (blob.dims == 2)
3546                 blob = blob.t();
3547
3548             if (shape(blob) == inpShape)
3549             {
3550                 LayerParams constParams;
3551                 constParams.name = layerParams.name + "/const";
3552                 constParams.type = "ConstInt8";
3553                 constParams.set("depth", CV_8S);
3554                 constParams.set("scales", DictValue::arrayReal(inp_1_sc.ptr<float>(), 1));
3555                 constParams.set("zeropoints", DictValue::arrayInt(inp_1_zp.ptr<int8_t>(), 1));
3556                 constParams.blobs.push_back(blob);
3557
3558                 int id = dstNet.addLayer(constParams.name, constParams.type, CV_8S, constParams);
3559                 layer_id.insert(std::make_pair(constParams.name, LayerInfo(id, 0)));
3560                 outShapes[constParams.name] = shape(blob);
3561                 node_proto.set_input(constId, constParams.name);
3562
3563                 layerParams.type = "EltwiseInt8";
3564                 layerParams.set("operation", op);
3565                 layerParams.set("coeff", DictValue::arrayReal(coeffs.data(), coeffs.size()));
3566                 layerParams.set("offset", offset);
3567             }
3568             else
3569             {
3570                 layerParams.type = "ScaleInt8";
3571                 layerParams.set("bias_term", op == "sum");
3572                 int axis = 1;
3573                 for (int i = 0; i < graph_proto.initializer_size(); i++)
3574                 {
3575                     opencv_onnx::TensorProto tensor_proto = graph_proto.initializer(i);
3576                     if (tensor_proto.name() == node_proto.input(constId))
3577                     {
3578                         axis = inpShape.size() - tensor_proto.dims_size();
3579                         break;
3580                     }
3581                 }
3582                 layerParams.set("axis", axis);
3583                 blob = blob.reshape(1, 1);
3584                 Mat blob_dequantized;
3585                 blob.convertTo(blob_dequantized, CV_32F, inp_scales[1], -(inp_scales[1] * inp_zps[1]));
3586                 layerParams.blobs.push_back(blob_dequantized);
3587             }
3588         }
3589     }
3590     else if (outShapes[node_proto.input(0)] == outShapes[node_proto.input(3)])
3591     {
3592         layerParams.type = "EltwiseInt8";
3593         layerParams.set("operation", op);
3594         layerParams.set("coeff", DictValue::arrayReal(coeffs.data(), coeffs.size()));
3595         layerParams.set("offset", offset);
3596     }
3597     else
3598     {
3599         layerParams.type = "ScaleInt8";
3600         layerParams.set("bias_term", op == "sum");
3601     }
3602
3603     layerParams.set("input_scales", DictValue::arrayReal(inp_scales.data(), inp_scales.size()));
3604     layerParams.set("input_zeropoints", DictValue::arrayInt(inp_zps.data(), inp_zps.size()));
3605     addLayer(layerParams, node_proto);
3606 }
3607
3608 void ONNXImporter::parseQLeakyRelu(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
3609 {
3610     CV_Assert(node_proto.input_size() == 5);
3611
3612     float slope = layerParams.get<float>("alpha");
3613     float inp_sc = getBlob(node_proto, 1).at<float>(0);
3614     int8_t inp_zp = getBlob(node_proto, 2).at<int8_t>(0);
3615     float out_sc = getBlob(node_proto, 3).at<float>(0);
3616     int8_t out_zp = getBlob(node_proto, 4).at<int8_t>(0);
3617
3618     Mat lookUpTable(1, 256, CV_8S);
3619     int8_t* table = lookUpTable.ptr<int8_t>();
3620     for (int i = -128; i < 128; i++)
3621     {
3622         float x = inp_sc*(i - inp_zp);
3623         float y = x >= 0.f ? x : slope*x;
3624         int quantized = out_zp + cvRound(y/out_sc);
3625         table[i+128] = saturate_cast<int8_t>(quantized);
3626     }
3627
3628     layerParams.type = "ReLUInt8";
3629     layerParams.set("input_scale", inp_sc);
3630     layerParams.set("input_zeropoint", inp_zp);
3631     layerParams.set("slope", slope);
3632     layerParams.blobs.push_back(lookUpTable);
3633     addLayer(layerParams, node_proto);
3634 }
3635
3636 void ONNXImporter::parseQSigmoid(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
3637 {
3638     CV_Assert(node_proto.input_size() == 5);
3639
3640     float inp_sc = getBlob(node_proto, 1).at<float>(0);
3641     int8_t inp_zp = getBlob(node_proto, 2).at<int8_t>(0);
3642     float out_sc = getBlob(node_proto, 3).at<float>(0);
3643     int8_t out_zp = getBlob(node_proto, 4).at<int8_t>(0);
3644
3645     Mat lookUpTable(1, 256, CV_8S);
3646     int8_t* table = lookUpTable.ptr<int8_t>();
3647     for (int i = -128; i < 128; i++)
3648     {
3649         float x = inp_sc*(i - inp_zp);
3650         float y = 1.f/(1.f + std::exp(-x));
3651         int quantized = out_zp + cvRound(y/out_sc);
3652         table[i+128] = saturate_cast<int8_t>(quantized);
3653     }
3654
3655     layerParams.type = "SigmoidInt8";
3656     layerParams.set("input_scale", inp_sc);
3657     layerParams.set("input_zeropoint", inp_zp);
3658     layerParams.blobs.push_back(lookUpTable);
3659     addLayer(layerParams, node_proto);
3660 }
3661
3662 void ONNXImporter::parseQAvgPool(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto)
3663 {
3664     CV_Assert(node_proto.input_size() == 5);
3665     float inp_sc = getBlob(node_proto, 1).at<float>(0);
3666     int8_t inp_zp = getBlob(node_proto, 2).at<int8_t>(0);
3667     float out_sc = getBlob(node_proto, 3).at<float>(0);
3668
3669     layerParams.type = "PoolingInt8";
3670     layerParams.set("pool", "ave");
3671     layerParams.set("global_pooling", node_proto.op_type() == "QLinearGlobalAveragePool");
3672     layerParams.set("multiplier", inp_sc/out_sc);
3673     layerParams.set("input_zeropoint", inp_zp);
3674     addLayer(layerParams, node_proto);
3675 }
3676
3677 void ONNXImporter::parseQConcat(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto_)
3678 {
3679     opencv_onnx::NodeProto node_proto = node_proto_;
3680     layerParams.type = "ConcatInt8";
3681     int num_inputs = node_proto.input_size();
3682
3683     float out_scale = getBlob(node_proto, 0).at<float>(0);
3684     int out_zp = getBlob(node_proto, 1).at<int8_t>(0);
3685
3686     for (int i = 2; i < num_inputs; i += 3)
3687     {
3688         float inp_scale = getBlob(node_proto, i + 1).at<float>(0);
3689         int inp_zp = getBlob(node_proto, i + 2).at<int8_t>(0);
3690
3691         if (inp_scale != out_scale || inp_zp != out_zp)
3692         {
3693             float scale = inp_scale/out_scale;
3694             float shift = out_zp - scale*inp_zp;
3695
3696             if (constBlobs.find(node_proto.input(i)) != constBlobs.end())
3697             {
3698                 Mat blob = getBlob(node_proto, i);
3699                 Mat blob_rescaled;
3700                 blob.convertTo(blob_rescaled, CV_8S, scale, shift);
3701                 constBlobs[node_proto.input(i)] = blob_rescaled;
3702             }
3703             else
3704             {
3705                 LayerParams rescaleParams;
3706                 rescaleParams.name = node_proto.input(i) + "/rescale";
3707                 rescaleParams.type = "Requantize";
3708                 rescaleParams.set("depth", CV_8S);
3709                 rescaleParams.set("scale", scale);
3710                 rescaleParams.set("shift", shift);
3711                 rescaleParams.set("isEltwise", false);
3712
3713                 opencv_onnx::NodeProto proto;
3714                 proto.add_input(node_proto.input(i));
3715                 proto.add_output(rescaleParams.name);
3716                 addLayer(rescaleParams, proto);
3717                 node_proto.set_input(i, rescaleParams.name);
3718             }
3719         }
3720     }
3721
3722     bool hasVariableInps = false;
3723     for (int i = 2; i < num_inputs; i += 3)
3724     {
3725         if (layer_id.find(node_proto.input(i)) != layer_id.end())
3726         {
3727             hasVariableInps = true;
3728             break;
3729         }
3730     }
3731
3732     if (!hasVariableInps)
3733     {
3734         std::vector<Mat> inputs, concatenated;
3735         MatShape inputShape;
3736         for (size_t i = 2; i < num_inputs; i += 3)
3737         {
3738             Mat blob = getBlob(node_proto, i);
3739             if (blob.size.dims() > inputShape.size())
3740             {
3741                 inputShape = shape(blob);
3742             }
3743             inputs.push_back(blob);
3744         }
3745
3746         int axis = layerParams.get<int>("axis", 1);
3747         for (size_t i = 0; i < inputs.size(); ++i)
3748         {
3749             MatShape targetShape = inputShape;
3750             targetShape[axis] = shape(inputs[i])[axis];
3751             CV_CheckEQ(total(targetShape), total(shape(inputs[i])), "");
3752             inputs[i] = inputs[i].reshape(0, targetShape);
3753         }
3754         runLayer(layerParams, inputs, concatenated);
3755         CV_Assert(concatenated.size() == 1);
3756         addConstant(layerParams.name, concatenated[0]);
3757         return;
3758     }
3759     else
3760     {
3761         for (int i = 2; i < num_inputs; i += 3)
3762         {
3763             if (constBlobs.find(node_proto.input(i)) != constBlobs.end())
3764             {
3765                 LayerParams constParams;
3766                 constParams.name = node_proto.input(i);
3767                 constParams.type = "ConstInt8";
3768                 constParams.blobs.push_back(getBlob(node_proto, i));
3769                 constParams.set("depth", CV_8S);
3770
3771                 opencv_onnx::NodeProto proto;
3772                 proto.add_output(constParams.name);
3773                 addLayer(constParams, proto);
3774             }
3775         }
3776     }
3777     addLayer(layerParams, node_proto);
3778 }
3779
3780 // Domain: ai.onnx (default)
3781 // URL: https://github.com/onnx/onnx/blob/master/docs/Operators.md
3782 void ONNXImporter::buildDispatchMap_ONNX_AI(int opset_version)
3783 {
3784     CV_UNUSED(opset_version);
3785     DispatchMap dispatch;
3786
3787     dispatch["ArgMax"] = dispatch["ArgMin"] = &ONNXImporter::parseArg;
3788     dispatch["MaxUnpool"] = &ONNXImporter::parseMaxUnpool;
3789     dispatch["MaxPool"] = &ONNXImporter::parseMaxPool;
3790     dispatch["AveragePool"] = &ONNXImporter::parseAveragePool;
3791     dispatch["GlobalAveragePool"] = dispatch["GlobalMaxPool"] = &ONNXImporter::parseGlobalPool;
3792     dispatch["ReduceMax"] = dispatch["ReduceMin"] = dispatch["ReduceMean"] = dispatch["ReduceSum"] = dispatch["ReduceMax"] =
3793             dispatch["ReduceMin"] = dispatch["ReduceSumSquare"] = dispatch["ReduceProd"] = dispatch["ReduceL1"] =
3794             dispatch["ReduceL2"] = dispatch["ReduceLogSum"] = dispatch["ReduceLogSumExp"] = &ONNXImporter::parseReduce;
3795     dispatch["Slice"] = &ONNXImporter::parseSlice;
3796     dispatch["Split"] = &ONNXImporter::parseSplit;
3797     dispatch["Add"] = dispatch["Sum"] = dispatch["Sub"] = &ONNXImporter::parseBias;
3798     dispatch["Pow"] = &ONNXImporter::parsePow;
3799     dispatch["Min"] = dispatch["Max"] = &ONNXImporter::parseMinMax;
3800     dispatch["Neg"] = &ONNXImporter::parseNeg;
3801     dispatch["Constant"] = &ONNXImporter::parseConstant;
3802     dispatch["LSTM"] = &ONNXImporter::parseLSTM;
3803     dispatch["GRU"] = &ONNXImporter::parseGRU;
3804     dispatch["ImageScaler"] = &ONNXImporter::parseImageScaler;
3805     dispatch["Clip"] = &ONNXImporter::parseClip;
3806     dispatch["LeakyRelu"] = &ONNXImporter::parseLeakyRelu;
3807     dispatch["Relu"] = &ONNXImporter::parseRelu;
3808     dispatch["Elu"] = &ONNXImporter::parseElu;
3809     dispatch["Tanh"] = &ONNXImporter::parseTanh;
3810     dispatch["Abs"] = &ONNXImporter::parseAbs;
3811     dispatch["Equal"] = dispatch["Greater"] = dispatch["Less"] = &ONNXImporter::parseCompare;
3812     dispatch["PRelu"] = &ONNXImporter::parsePRelu;
3813     dispatch["LRN"] = &ONNXImporter::parseLRN;
3814     dispatch["InstanceNormalization"] = &ONNXImporter::parseInstanceNormalization;
3815     dispatch["BatchNormalization"] = &ONNXImporter::parseBatchNormalization;
3816     dispatch["Gemm"] = &ONNXImporter::parseGemm;
3817     dispatch["MatMul"] = &ONNXImporter::parseMatMul;
3818     dispatch["Mul"] = dispatch["Div"] = &ONNXImporter::parseMul;
3819     dispatch["Conv"] = &ONNXImporter::parseConv;
3820     dispatch["ConvTranspose"] = &ONNXImporter::parseConvTranspose;
3821     dispatch["Transpose"] = &ONNXImporter::parseTranspose;
3822     dispatch["Squeeze"] = &ONNXImporter::parseSqueeze;
3823     dispatch["Flatten"] = &ONNXImporter::parseFlatten;
3824     dispatch["Unsqueeze"] = &ONNXImporter::parseUnsqueeze;
3825     dispatch["Expand"] = &ONNXImporter::parseExpand;
3826     dispatch["Reshape"] = &ONNXImporter::parseReshape;
3827     dispatch["Pad"] = &ONNXImporter::parsePad;
3828     dispatch["Shape"] = &ONNXImporter::parseShape;
3829     dispatch["Cast"] = &ONNXImporter::parseCast;
3830     dispatch["ConstantFill"] = dispatch["ConstantOfShape"] = &ONNXImporter::parseConstantFill;
3831     dispatch["Gather"] = &ONNXImporter::parseGather;
3832     dispatch["Concat"] = &ONNXImporter::parseConcat;
3833     dispatch["Resize"] = &ONNXImporter::parseResize;
3834     dispatch["Upsample"] = &ONNXImporter::parseUpsample;
3835     dispatch["SoftMax"] = dispatch["LogSoftmax"] = &ONNXImporter::parseSoftMax;
3836     dispatch["DetectionOutput"] = &ONNXImporter::parseDetectionOutput;
3837     dispatch["CumSum"] = &ONNXImporter::parseCumSum;
3838     dispatch["SpaceToDepth"] = dispatch["DepthToSpace"] = &ONNXImporter::parseDepthToSpace;
3839
3840     std::vector<std::string> simpleLayers{"Acos", "Acosh", "Asin", "Asinh", "Atan", "Atanh", "Ceil", "Celu", "Cos",
3841                                           "Cosh", "Dropout", "Erf", "Exp", "Floor", "HardSigmoid", "HardSwish",
3842                                           "Identity", "Log", "Round", "Reciprocal", "Selu", "Sign", "Sigmoid", "Sin", "Sinh", "Softmax",
3843                                           "Softplus", "Softsign", "Shrink", "Sqrt", "Tan", "ThresholdedRelu"};
3844     for (const auto& name : simpleLayers)
3845     {
3846         dispatch[name] = &ONNXImporter::parseSimpleLayers;
3847     }
3848
3849     // ai.onnx: opset 10+
3850     dispatch["QuantizeLinear"] = dispatch["DequantizeLinear"] = &ONNXImporter::parseQuantDequant;
3851     dispatch["QLinearConv"] = &ONNXImporter::parseQConv;
3852     dispatch["QLinearMatMul"] = &ONNXImporter::parseQMatMul;
3853
3854     domain_dispatch_map[str_domain_ai_onnx] = dispatch;
3855 }
3856
3857 // Domain: com.microsoft
3858 // URL: https://github.com/microsoft/onnxruntime/blob/master/docs/ContribOperators.md
3859 void ONNXImporter::buildDispatchMap_COM_MICROSOFT(int opset_version)
3860 {
3861     CV_UNUSED(opset_version);
3862     DispatchMap dispatch;
3863
3864     dispatch["QLinearAdd"] = dispatch["QLinearMul"] = &ONNXImporter::parseQEltwise;
3865     dispatch["QLinearAveragePool"] = dispatch["QLinearGlobalAveragePool"] = &ONNXImporter::parseQAvgPool;
3866     dispatch["QLinearLeakyRelu"] = &ONNXImporter::parseQLeakyRelu;
3867     dispatch["QLinearSigmoid"] = &ONNXImporter::parseQSigmoid;
3868     dispatch["QLinearConcat"] = &ONNXImporter::parseQConcat;
3869
3870     domain_dispatch_map["com.microsoft"] = dispatch;
3871 }
3872
3873
3874 Net readNetFromONNX(const String& onnxFile)
3875 {
3876     return detail::readNetDiagnostic<ONNXImporter>(onnxFile.c_str());
3877 }
3878
3879 Net readNetFromONNX(const char* buffer, size_t sizeBuffer)
3880 {
3881     return detail::readNetDiagnostic<ONNXImporter>(buffer, sizeBuffer);
3882 }
3883
3884 Net readNetFromONNX(const std::vector<uchar>& buffer)
3885 {
3886     return readNetFromONNX(reinterpret_cast<const char*>(buffer.data()), buffer.size());
3887 }
3888
3889 Mat readTensorFromONNX(const String& path)
3890 {
3891     std::fstream input(path.c_str(), std::ios::in | std::ios::binary);
3892     if (!input)
3893     {
3894         CV_Error(Error::StsBadArg, cv::format("Can't read ONNX file: %s", path.c_str()));
3895     }
3896
3897     opencv_onnx::TensorProto tensor_proto = opencv_onnx::TensorProto();
3898     if (!tensor_proto.ParseFromIstream(&input))
3899     {
3900         CV_Error(Error::StsUnsupportedFormat, cv::format("Failed to parse ONNX data: %s", path.c_str()));
3901     }
3902     Mat mat = getMatFromTensor(tensor_proto);
3903     releaseONNXTensor(tensor_proto);
3904     return mat;
3905 }
3906
3907 CV__DNN_INLINE_NS_END
3908 }} // namespace
3909
3910 #endif