Coverage Report

Created: 2023-06-07 08:11

/work/install-coverage/include/opencv4/opencv2/dnn/dnn.hpp
Line
Count
Source (jump to first uncovered line)
1
/*M///////////////////////////////////////////////////////////////////////////////////////
2
//
3
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4
//
5
//  By downloading, copying, installing or using the software you agree to this license.
6
//  If you do not agree to this license, do not download, install,
7
//  copy or use the software.
8
//
9
//
10
//                           License Agreement
11
//                For Open Source Computer Vision Library
12
//
13
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
14
// Third party copyrights are property of their respective owners.
15
//
16
// Redistribution and use in source and binary forms, with or without modification,
17
// are permitted provided that the following conditions are met:
18
//
19
//   * Redistribution's of source code must retain the above copyright notice,
20
//     this list of conditions and the following disclaimer.
21
//
22
//   * Redistribution's in binary form must reproduce the above copyright notice,
23
//     this list of conditions and the following disclaimer in the documentation
24
//     and/or other materials provided with the distribution.
25
//
26
//   * The name of the copyright holders may not be used to endorse or promote products
27
//     derived from this software without specific prior written permission.
28
//
29
// This software is provided by the copyright holders and contributors "as is" and
30
// any express or implied warranties, including, but not limited to, the implied
31
// warranties of merchantability and fitness for a particular purpose are disclaimed.
32
// In no event shall the Intel Corporation or contributors be liable for any direct,
33
// indirect, incidental, special, exemplary, or consequential damages
34
// (including, but not limited to, procurement of substitute goods or services;
35
// loss of use, data, or profits; or business interruption) however caused
36
// and on any theory of liability, whether in contract, strict liability,
37
// or tort (including negligence or otherwise) arising in any way out of
38
// the use of this software, even if advised of the possibility of such damage.
39
//
40
//M*/
41
42
#ifndef OPENCV_DNN_DNN_HPP
43
#define OPENCV_DNN_DNN_HPP
44
45
#include <vector>
46
#include <opencv2/core.hpp>
47
#include "opencv2/core/async.hpp"
48
49
#include "../dnn/version.hpp"
50
51
#include <opencv2/dnn/dict.hpp>
52
53
namespace cv {
54
namespace dnn {
55
56
namespace accessor {
57
class DnnNetAccessor;  // forward declaration
58
}
59
60
CV__DNN_INLINE_NS_BEGIN
61
//! @addtogroup dnn
62
//! @{
63
64
    typedef std::vector<int> MatShape;
65
66
    /**
67
     * @brief Enum of computation backends supported by layers.
68
     * @see Net::setPreferableBackend
69
     */
70
    enum Backend
71
    {
72
        //! DNN_BACKEND_DEFAULT equals to DNN_BACKEND_INFERENCE_ENGINE if
73
        //! OpenCV is built with Intel OpenVINO or
74
        //! DNN_BACKEND_OPENCV otherwise.
75
        DNN_BACKEND_DEFAULT = 0,
76
        DNN_BACKEND_HALIDE,
77
        DNN_BACKEND_INFERENCE_ENGINE,            //!< Intel OpenVINO computational backend
78
                                                 //!< @note Tutorial how to build OpenCV with OpenVINO: @ref tutorial_dnn_openvino
79
        DNN_BACKEND_OPENCV,
80
        DNN_BACKEND_VKCOM,
81
        DNN_BACKEND_CUDA,
82
        DNN_BACKEND_WEBNN,
83
        DNN_BACKEND_TIMVX,
84
        DNN_BACKEND_CANN,
85
#if defined(__OPENCV_BUILD) || defined(BUILD_PLUGIN)
86
#if !defined(OPENCV_BINDING_PARSER)
87
        DNN_BACKEND_INFERENCE_ENGINE_NGRAPH = 1000000,     // internal - use DNN_BACKEND_INFERENCE_ENGINE + setInferenceEngineBackendType()
88
        DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019,      // internal - use DNN_BACKEND_INFERENCE_ENGINE + setInferenceEngineBackendType()
89
#endif
90
#endif
91
    };
92
93
    /**
94
     * @brief Enum of target devices for computations.
95
     * @see Net::setPreferableTarget
96
     */
97
    enum Target
98
    {
99
        DNN_TARGET_CPU = 0,
100
        DNN_TARGET_OPENCL,
101
        DNN_TARGET_OPENCL_FP16,
102
        DNN_TARGET_MYRIAD,
103
        DNN_TARGET_VULKAN,
104
        DNN_TARGET_FPGA,  //!< FPGA device with CPU fallbacks using Inference Engine's Heterogeneous plugin.
105
        DNN_TARGET_CUDA,
106
        DNN_TARGET_CUDA_FP16,
107
        DNN_TARGET_HDDL,
108
        DNN_TARGET_NPU,
109
        DNN_TARGET_CPU_FP16, // Only the ARM platform is supported. Low precision computing, accelerate model inference.
110
    };
111
112
    /**
113
     * @brief Enum of data layout for model inference.
114
     * @see Image2BlobParams
115
     */
116
    enum DataLayout
117
    {
118
        DNN_LAYOUT_UNKNOWN = 0,
119
        DNN_LAYOUT_ND = 1,        //!< OpenCV data layout for 2D data.
120
        DNN_LAYOUT_NCHW = 2,      //!< OpenCV data layout for 4D data.
121
        DNN_LAYOUT_NCDHW = 3,      //!< OpenCV data layout for 5D data.
122
        DNN_LAYOUT_NHWC = 4,      //!< Tensorflow-like data layout for 4D data.
123
        DNN_LAYOUT_NDHWC = 5,      //!< Tensorflow-like data layout for 5D data.
124
        DNN_LAYOUT_PLANAR = 6,     //!< Tensorflow-like data layout, it should only be used at tf or tflite model parsing.
125
    };
126
127
    CV_EXPORTS std::vector< std::pair<Backend, Target> > getAvailableBackends();
128
    CV_EXPORTS_W std::vector<Target> getAvailableTargets(dnn::Backend be);
129
130
    /**
131
     * @brief Enables detailed logging of the DNN model loading with CV DNN API.
132
     * @param[in] isDiagnosticsMode Indicates whether diagnostic mode should be set.
133
     *
134
     * Diagnostic mode provides detailed logging of the model loading stage to explore
135
     * potential problems (ex.: not implemented layer type).
136
     *
137
     * @note In diagnostic mode series of assertions will be skipped, it can lead to the
138
     * expected application crash.
139
     */
140
    CV_EXPORTS void enableModelDiagnostics(bool isDiagnosticsMode);
141
142
    /** @brief This class provides all data needed to initialize layer.
143
     *
144
     * It includes dictionary with scalar params (which can be read by using Dict interface),
145
     * blob params #blobs and optional meta information: #name and #type of layer instance.
146
    */
147
    class CV_EXPORTS LayerParams : public Dict
148
    {
149
    public:
150
        //TODO: Add ability to name blob params
151
        std::vector<Mat> blobs; //!< List of learned parameters stored as blobs.
152
153
        String name; //!< Name of the layer instance (optional, can be used internal purposes).
154
        String type; //!< Type name which was used for creating layer by layer factory (optional).
155
    };
156
157
   /**
158
    * @brief Derivatives of this class encapsulates functions of certain backends.
159
    */
160
    class BackendNode
161
    {
162
    public:
163
        explicit BackendNode(int backendId);
164
165
        virtual ~BackendNode(); //!< Virtual destructor to make polymorphism.
166
167
        int backendId; //!< Backend identifier.
168
    };
169
170
    /**
171
     * @brief Derivatives of this class wraps cv::Mat for different backends and targets.
172
     */
173
    class BackendWrapper
174
    {
175
    public:
176
        BackendWrapper(int backendId, int targetId);
177
178
        /**
179
         * @brief Wrap cv::Mat for specific backend and target.
180
         * @param[in] targetId Target identifier.
181
         * @param[in] m cv::Mat for wrapping.
182
         *
183
         * Make CPU->GPU data transfer if it's require for the target.
184
         */
185
        BackendWrapper(int targetId, const cv::Mat& m);
186
187
        /**
188
         * @brief Make wrapper for reused cv::Mat.
189
         * @param[in] base Wrapper of cv::Mat that will be reused.
190
         * @param[in] shape Specific shape.
191
         *
192
         * Initialize wrapper from another one. It'll wrap the same host CPU
193
         * memory and mustn't allocate memory on device(i.e. GPU). It might
194
         * has different shape. Use in case of CPU memory reusing for reuse
195
         * associated memory on device too.
196
         */
197
        BackendWrapper(const Ptr<BackendWrapper>& base, const MatShape& shape);
198
199
        virtual ~BackendWrapper(); //!< Virtual destructor to make polymorphism.
200
201
        /**
202
         * @brief Transfer data to CPU host memory.
203
         */
204
        virtual void copyToHost() = 0;
205
206
        /**
207
         * @brief Indicate that an actual data is on CPU.
208
         */
209
        virtual void setHostDirty() = 0;
210
211
        int backendId;  //!< Backend identifier.
212
        int targetId;   //!< Target identifier.
213
    };
214
215
    class CV_EXPORTS ActivationLayer;
216
217
    /** @brief This interface class allows to build new Layers - are building blocks of networks.
218
     *
219
     * Each class, derived from Layer, must implement allocate() methods to declare own outputs and forward() to compute outputs.
220
     * Also before using the new layer into networks you must register your layer by using one of @ref dnnLayerFactory "LayerFactory" macros.
221
     */
222
    class CV_EXPORTS_W Layer : public Algorithm
223
    {
224
    public:
225
226
        //! List of learned parameters must be stored here to allow read them by using Net::getParam().
227
        CV_PROP_RW std::vector<Mat> blobs;
228
229
        /** @brief Computes and sets internal parameters according to inputs, outputs and blobs.
230
         *  @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead
231
         *  @param[in]  input  vector of already allocated input blobs
232
         *  @param[out] output vector of already allocated output blobs
233
         *
234
         * If this method is called after network has allocated all memory for input and output blobs
235
         * and before inferencing.
236
         */
237
        CV_DEPRECATED_EXTERNAL
238
        virtual void finalize(const std::vector<Mat*> &input, std::vector<Mat> &output);
239
240
        /** @brief Computes and sets internal parameters according to inputs, outputs and blobs.
241
         *  @param[in]  inputs  vector of already allocated input blobs
242
         *  @param[out] outputs vector of already allocated output blobs
243
         *
244
         * If this method is called after network has allocated all memory for input and output blobs
245
         * and before inferencing.
246
         */
247
        CV_WRAP virtual void finalize(InputArrayOfArrays inputs, OutputArrayOfArrays outputs);
248
249
        /** @brief Given the @p input blobs, computes the output @p blobs.
250
         *  @deprecated Use Layer::forward(InputArrayOfArrays, OutputArrayOfArrays, OutputArrayOfArrays) instead
251
         *  @param[in]  input  the input blobs.
252
         *  @param[out] output allocated output blobs, which will store results of the computation.
253
         *  @param[out] internals allocated internal blobs
254
         */
255
        CV_DEPRECATED_EXTERNAL
256
        virtual void forward(std::vector<Mat*> &input, std::vector<Mat> &output, std::vector<Mat> &internals);
257
258
        /** @brief Given the @p input blobs, computes the output @p blobs.
259
         *  @param[in]  inputs  the input blobs.
260
         *  @param[out] outputs allocated output blobs, which will store results of the computation.
261
         *  @param[out] internals allocated internal blobs
262
         */
263
        virtual void forward(InputArrayOfArrays inputs, OutputArrayOfArrays outputs, OutputArrayOfArrays internals);
264
265
        /** @brief Tries to quantize the given layer and compute the quantization parameters required for fixed point implementation.
266
         *  @param[in] scales input and output scales.
267
         *  @param[in] zeropoints input and output zeropoints.
268
         *  @param[out] params Quantized parameters required for fixed point implementation of that layer.
269
         *  @returns True if layer can be quantized.
270
         */
271
        virtual bool tryQuantize(const std::vector<std::vector<float> > &scales,
272
                                 const std::vector<std::vector<int> > &zeropoints, LayerParams& params);
273
274
        /** @brief Given the @p input blobs, computes the output @p blobs.
275
         *  @param[in]  inputs  the input blobs.
276
         *  @param[out] outputs allocated output blobs, which will store results of the computation.
277
         *  @param[out] internals allocated internal blobs
278
         */
279
        void forward_fallback(InputArrayOfArrays inputs, OutputArrayOfArrays outputs, OutputArrayOfArrays internals);
280
281
        /** @brief
282
         * @overload
283
         * @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead
284
         */
285
        CV_DEPRECATED_EXTERNAL
286
        void finalize(const std::vector<Mat> &inputs, CV_OUT std::vector<Mat> &outputs);
287
288
        /** @brief
289
         * @overload
290
         * @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead
291
         */
292
        CV_DEPRECATED std::vector<Mat> finalize(const std::vector<Mat> &inputs);
293
294
        /** @brief Allocates layer and computes output.
295
         *  @deprecated This method will be removed in the future release.
296
         */
297
        CV_DEPRECATED CV_WRAP void run(const std::vector<Mat> &inputs, CV_OUT std::vector<Mat> &outputs,
298
                                       CV_IN_OUT std::vector<Mat> &internals);
299
300
        /** @brief Returns index of input blob into the input array.
301
         *  @param inputName label of input blob
302
         *
303
         * Each layer input and output can be labeled to easily identify them using "%<layer_name%>[.output_name]" notation.
304
         * This method maps label of input blob to its index into input vector.
305
         */
306
        virtual int inputNameToIndex(String inputName);  // FIXIT const
307
        /** @brief Returns index of output blob in output array.
308
         *  @see inputNameToIndex()
309
         */
310
        CV_WRAP virtual int outputNameToIndex(const String& outputName);  // FIXIT const
311
312
        /**
313
         * @brief Ask layer if it support specific backend for doing computations.
314
         * @param[in] backendId computation backend identifier.
315
         * @see Backend
316
         */
317
        virtual bool supportBackend(int backendId);  // FIXIT const
318
319
        /**
320
         * @brief Returns Halide backend node.
321
         * @param[in] inputs Input Halide buffers.
322
         * @see BackendNode, BackendWrapper
323
         *
324
         * Input buffers should be exactly the same that will be used in forward invocations.
325
         * Despite we can use Halide::ImageParam based on input shape only,
326
         * it helps prevent some memory management issues (if something wrong,
327
         * Halide tests will be failed).
328
         */
329
        virtual Ptr<BackendNode> initHalide(const std::vector<Ptr<BackendWrapper> > &inputs);
330
331
        virtual Ptr<BackendNode> initNgraph(const std::vector<Ptr<BackendWrapper> > &inputs, const std::vector<Ptr<BackendNode> >& nodes);
332
333
        virtual Ptr<BackendNode> initVkCom(const std::vector<Ptr<BackendWrapper> > &inputs, std::vector<Ptr<BackendWrapper> > &outputs);
334
335
        virtual Ptr<BackendNode> initWebnn(const std::vector<Ptr<BackendWrapper> > &inputs, const std::vector<Ptr<BackendNode> >& nodes);
336
337
        /**
338
         * @brief Returns a CUDA backend node
339
         *
340
         * @param   context  void pointer to CSLContext object
341
         * @param   inputs   layer inputs
342
         * @param   outputs  layer outputs
343
         */
344
        virtual Ptr<BackendNode> initCUDA(
345
            void *context,
346
            const std::vector<Ptr<BackendWrapper>>& inputs,
347
            const std::vector<Ptr<BackendWrapper>>& outputs
348
        );
349
350
        /**
351
         * @brief Returns a TimVX backend node
352
         *
353
         * @param   timVxInfo  void pointer to CSLContext object
354
         * @param   inputsWrapper   layer inputs
355
         * @param   outputsWrapper  layer outputs
356
         * @param   isLast if the node is the last one of the TimVX Graph.
357
         */
358
        virtual Ptr<BackendNode> initTimVX(void* timVxInfo,
359
                                           const std::vector<Ptr<BackendWrapper> > &inputsWrapper,
360
                                           const std::vector<Ptr<BackendWrapper> > &outputsWrapper,
361
                                           bool isLast);
362
363
        /**
364
         * @brief Returns a CANN backend node
365
         *
366
         * @param   inputs   input tensors of CANN operator
367
         * @param   outputs  output tensors of CANN operator
368
         * @param   nodes           nodes of input tensors
369
         */
370
        virtual Ptr<BackendNode> initCann(const std::vector<Ptr<BackendWrapper> > &inputs,
371
                                          const std::vector<Ptr<BackendWrapper> > &outputs,
372
                                          const std::vector<Ptr<BackendNode> >& nodes);
373
374
       /**
375
        * @brief Automatic Halide scheduling based on layer hyper-parameters.
376
        * @param[in] node Backend node with Halide functions.
377
        * @param[in] inputs Blobs that will be used in forward invocations.
378
        * @param[in] outputs Blobs that will be used in forward invocations.
379
        * @param[in] targetId Target identifier
380
        * @see BackendNode, Target
381
        *
382
        * Layer don't use own Halide::Func members because we can have applied
383
        * layers fusing. In this way the fused function should be scheduled.
384
        */
385
        virtual void applyHalideScheduler(Ptr<BackendNode>& node,
386
                                          const std::vector<Mat*> &inputs,
387
                                          const std::vector<Mat> &outputs,
388
                                          int targetId) const;
389
390
        /**
391
         * @brief Implement layers fusing.
392
         * @param[in] node Backend node of bottom layer.
393
         * @see BackendNode
394
         *
395
         * Actual for graph-based backends. If layer attached successfully,
396
         * returns non-empty cv::Ptr to node of the same backend.
397
         * Fuse only over the last function.
398
         */
399
        virtual Ptr<BackendNode> tryAttach(const Ptr<BackendNode>& node);
400
401
        /**
402
         * @brief Tries to attach to the layer the subsequent activation layer, i.e. do the layer fusion in a partial case.
403
         * @param[in] layer The subsequent activation layer.
404
         *
405
         * Returns true if the activation layer has been attached successfully.
406
         */
407
        virtual bool setActivation(const Ptr<ActivationLayer>& layer);
408
409
        /**
410
         * @brief Try to fuse current layer with a next one
411
         * @param[in] top Next layer to be fused.
412
         * @returns True if fusion was performed.
413
         */
414
        virtual bool tryFuse(Ptr<Layer>& top);
415
416
        /**
417
         * @brief Returns parameters of layers with channel-wise multiplication and addition.
418
         * @param[out] scale Channel-wise multipliers. Total number of values should
419
         *                   be equal to number of channels.
420
         * @param[out] shift Channel-wise offsets. Total number of values should
421
         *                   be equal to number of channels.
422
         *
423
         * Some layers can fuse their transformations with further layers.
424
         * In example, convolution + batch normalization. This way base layer
425
         * use weights from layer after it. Fused layer is skipped.
426
         * By default, @p scale and @p shift are empty that means layer has no
427
         * element-wise multiplications or additions.
428
         */
429
        virtual void getScaleShift(Mat& scale, Mat& shift) const;
430
431
        /**
432
         * @brief Returns scale and zeropoint of layers
433
         * @param[out] scale Output scale
434
         * @param[out] zeropoint Output zeropoint
435
         *
436
         * By default, @p scale is 1 and @p zeropoint is 0.
437
         */
438
        virtual void getScaleZeropoint(float& scale, int& zeropoint) const;
439
440
441
        /**
442
         * @brief "Detaches" all the layers, attached to particular layer.
443
         */
444
        virtual void unsetAttached();
445
446
        virtual bool getMemoryShapes(const std::vector<MatShape> &inputs,
447
                                     const int requiredOutputs,
448
                                     std::vector<MatShape> &outputs,
449
                                     std::vector<MatShape> &internals) const;
450
451
        virtual int64 getFLOPS(const std::vector<MatShape> &inputs,
452
0
                               const std::vector<MatShape> &outputs) const {CV_UNUSED(inputs); CV_UNUSED(outputs); return 0;}
453
454
        virtual bool updateMemoryShapes(const std::vector<MatShape> &inputs);
455
456
        CV_PROP String name; //!< Name of the layer instance, can be used for logging or other internal purposes.
457
        CV_PROP String type; //!< Type name which was used for creating layer by layer factory.
458
        CV_PROP int preferableTarget; //!< prefer target for layer forwarding
459
460
        Layer();
461
        explicit Layer(const LayerParams &params);      //!< Initializes only #name, #type and #blobs fields.
462
        void setParamsFrom(const LayerParams &params);  //!< Initializes only #name, #type and #blobs fields.
463
        virtual ~Layer();
464
    };
465
466
    /** @brief This class allows to create and manipulate comprehensive artificial neural networks.
467
     *
468
     * Neural network is presented as directed acyclic graph (DAG), where vertices are Layer instances,
469
     * and edges specify relationships between layers inputs and outputs.
470
     *
471
     * Each network layer has unique integer id and unique string name inside its network.
472
     * LayerId can store either layer name or layer id.
473
     *
474
     * This class supports reference counting of its instances, i. e. copies point to the same instance.
475
     */
476
    class CV_EXPORTS_W_SIMPLE Net
477
    {
478
    public:
479
480
        CV_WRAP Net();  //!< Default constructor.
481
        CV_WRAP ~Net(); //!< Destructor frees the net only if there aren't references to the net anymore.
482
483
        /** @brief Create a network from Intel's Model Optimizer intermediate representation (IR).
484
         *  @param[in] xml XML configuration file with network's topology.
485
         *  @param[in] bin Binary file with trained weights.
486
         *  Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine
487
         *  backend.
488
         */
489
        CV_WRAP static Net readFromModelOptimizer(const String& xml, const String& bin);
490
491
        /** @brief Create a network from Intel's Model Optimizer in-memory buffers with intermediate representation (IR).
492
         *  @param[in] bufferModelConfig buffer with model's configuration.
493
         *  @param[in] bufferWeights buffer with model's trained weights.
494
         *  @returns Net object.
495
         */
496
        CV_WRAP static
497
        Net readFromModelOptimizer(const std::vector<uchar>& bufferModelConfig, const std::vector<uchar>& bufferWeights);
498
499
        /** @brief Create a network from Intel's Model Optimizer in-memory buffers with intermediate representation (IR).
500
         *  @param[in] bufferModelConfigPtr buffer pointer of model's configuration.
501
         *  @param[in] bufferModelConfigSize buffer size of model's configuration.
502
         *  @param[in] bufferWeightsPtr buffer pointer of model's trained weights.
503
         *  @param[in] bufferWeightsSize buffer size of model's trained weights.
504
         *  @returns Net object.
505
         */
506
        static
507
        Net readFromModelOptimizer(const uchar* bufferModelConfigPtr, size_t bufferModelConfigSize,
508
                                            const uchar* bufferWeightsPtr, size_t bufferWeightsSize);
509
510
        /** Returns true if there are no layers in the network. */
511
        CV_WRAP bool empty() const;
512
513
        /** @brief Dump net to String
514
         *  @returns String with structure, hyperparameters, backend, target and fusion
515
         *  Call method after setInput(). To see correct backend, target and fusion run after forward().
516
         */
517
        CV_WRAP String dump();
518
        /** @brief Dump net structure, hyperparameters, backend, target and fusion to dot file
519
         *  @param path   path to output file with .dot extension
520
         *  @see dump()
521
         */
522
        CV_WRAP void dumpToFile(const String& path);
523
        /** @brief Adds new layer to the net.
524
         *  @param name   unique name of the adding layer.
525
         *  @param type   typename of the adding layer (type must be registered in LayerRegister).
526
         *  @param dtype  datatype of output blobs.
527
         *  @param params parameters which will be used to initialize the creating layer.
528
         *  @returns unique identifier of created layer, or -1 if a failure will happen.
529
         */
530
        int addLayer(const String &name, const String &type, const int &dtype, LayerParams &params);
531
532
        /** @overload Datatype of output blobs set to default CV_32F */
533
        int addLayer(const String &name, const String &type, LayerParams &params);
534
535
        /** @brief Adds new layer and connects its first input to the first output of previously added layer.
536
         *  @see addLayer()
537
         */
538
        int addLayerToPrev(const String &name, const String &type, const int &dtype, LayerParams &params);
539
540
        /** @overload */
541
        int addLayerToPrev(const String &name, const String &type, LayerParams &params);
542
543
        /** @brief Converts string name of the layer to the integer identifier.
544
         *  @returns id of the layer, or -1 if the layer wasn't found.
545
         */
546
        CV_WRAP int getLayerId(const String &layer) const;
547
548
        CV_WRAP std::vector<String> getLayerNames() const;
549
550
        /** @brief Container for strings and integers.
551
         *
552
         * @deprecated Use getLayerId() with int result.
553
         */
554
        typedef DictValue LayerId;
555
556
        /** @brief Returns pointer to layer with specified id or name which the network use. */
557
        CV_WRAP Ptr<Layer> getLayer(int layerId) const;
558
        /** @overload
559
         *  @deprecated Use int getLayerId(const String &layer)
560
         */
561
0
        CV_WRAP inline Ptr<Layer> getLayer(const String& layerName) const { return getLayer(getLayerId(layerName)); }
562
        /** @overload
563
         *  @deprecated to be removed
564
         */
565
        CV_WRAP Ptr<Layer> getLayer(const LayerId& layerId) const;
566
567
        /** @brief Returns pointers to input layers of specific layer. */
568
        std::vector<Ptr<Layer> > getLayerInputs(int layerId) const; // FIXIT: CV_WRAP
569
570
        /** @brief Connects output of the first layer to input of the second layer.
571
         *  @param outPin descriptor of the first layer output.
572
         *  @param inpPin descriptor of the second layer input.
573
         *
574
         * Descriptors have the following template <DFN>&lt;layer_name&gt;[.input_number]</DFN>:
575
         * - the first part of the template <DFN>layer_name</DFN> is string name of the added layer.
576
         *   If this part is empty then the network input pseudo layer will be used;
577
         * - the second optional part of the template <DFN>input_number</DFN>
578
         *   is either number of the layer input, either label one.
579
         *   If this part is omitted then the first layer input will be used.
580
         *
581
         *  @see setNetInputs(), Layer::inputNameToIndex(), Layer::outputNameToIndex()
582
         */
583
        CV_WRAP void connect(String outPin, String inpPin);
584
585
        /** @brief Connects #@p outNum output of the first layer to #@p inNum input of the second layer.
586
         *  @param outLayerId identifier of the first layer
587
         *  @param outNum number of the first layer output
588
         *  @param inpLayerId identifier of the second layer
589
         *  @param inpNum number of the second layer input
590
         */
591
        void connect(int outLayerId, int outNum, int inpLayerId, int inpNum);
592
593
        /** @brief Registers network output with name
594
         *
595
         *  Function may create additional 'Identity' layer.
596
         *
597
         *  @param outputName identifier of the output
598
         *  @param layerId identifier of the second layer
599
         *  @param outputPort number of the second layer input
600
         *
601
         *  @returns index of bound layer (the same as layerId or newly created)
602
         */
603
        int registerOutput(const std::string& outputName, int layerId, int outputPort);
604
605
        /** @brief Sets outputs names of the network input pseudo layer.
606
         *
607
         * Each net always has special own the network input pseudo layer with id=0.
608
         * This layer stores the user blobs only and don't make any computations.
609
         * In fact, this layer provides the only way to pass user data into the network.
610
         * As any other layer, this layer can label its outputs and this function provides an easy way to do this.
611
         */
612
        CV_WRAP void setInputsNames(const std::vector<String> &inputBlobNames);
613
614
        /** @brief Specify shape of network input.
615
         */
616
        CV_WRAP void setInputShape(const String &inputName, const MatShape& shape);
617
618
        /** @brief Runs forward pass to compute output of layer with name @p outputName.
619
         *  @param outputName name for layer which output is needed to get
620
         *  @return blob for first output of specified layer.
621
         *  @details By default runs forward pass for the whole network.
622
         */
623
        CV_WRAP Mat forward(const String& outputName = String());
624
625
        /** @brief Runs forward pass to compute output of layer with name @p outputName.
626
         *  @param outputName name for layer which output is needed to get
627
         *  @details By default runs forward pass for the whole network.
628
         *
629
         *  This is an asynchronous version of forward(const String&).
630
         *  dnn::DNN_BACKEND_INFERENCE_ENGINE backend is required.
631
         */
632
        CV_WRAP AsyncArray forwardAsync(const String& outputName = String());
633
634
        /** @brief Runs forward pass to compute output of layer with name @p outputName.
635
         *  @param outputBlobs contains all output blobs for specified layer.
636
         *  @param outputName name for layer which output is needed to get
637
         *  @details If @p outputName is empty, runs forward pass for the whole network.
638
         */
639
        CV_WRAP void forward(OutputArrayOfArrays outputBlobs, const String& outputName = String());
640
641
        /** @brief Runs forward pass to compute outputs of layers listed in @p outBlobNames.
642
         *  @param outputBlobs contains blobs for first outputs of specified layers.
643
         *  @param outBlobNames names for layers which outputs are needed to get
644
         */
645
        CV_WRAP void forward(OutputArrayOfArrays outputBlobs,
646
                             const std::vector<String>& outBlobNames);
647
648
        /** @brief Runs forward pass to compute outputs of layers listed in @p outBlobNames.
649
         *  @param outputBlobs contains all output blobs for each layer specified in @p outBlobNames.
650
         *  @param outBlobNames names for layers which outputs are needed to get
651
         */
652
        CV_WRAP_AS(forwardAndRetrieve) void forward(CV_OUT std::vector<std::vector<Mat> >& outputBlobs,
653
                                                    const std::vector<String>& outBlobNames);
654
655
        /** @brief Returns a quantized Net from a floating-point Net.
656
         *  @param calibData Calibration data to compute the quantization parameters.
657
         *  @param inputsDtype Datatype of quantized net's inputs. Can be CV_32F or CV_8S.
658
         *  @param outputsDtype Datatype of quantized net's outputs. Can be CV_32F or CV_8S.
659
         *  @param perChannel Quantization granularity of quantized Net. The default is true, that means quantize model
660
         *  in per-channel way (channel-wise). Set it false to quantize model in per-tensor way (or tensor-wise).
661
         */
662
        CV_WRAP Net quantize(InputArrayOfArrays calibData, int inputsDtype, int outputsDtype, bool perChannel=true);
663
664
        /** @brief Returns input scale and zeropoint for a quantized Net.
665
         *  @param scales output parameter for returning input scales.
666
         *  @param zeropoints output parameter for returning input zeropoints.
667
         */
668
        CV_WRAP void getInputDetails(CV_OUT std::vector<float>& scales, CV_OUT std::vector<int>& zeropoints) const;
669
670
        /** @brief Returns output scale and zeropoint for a quantized Net.
671
         *  @param scales output parameter for returning output scales.
672
         *  @param zeropoints output parameter for returning output zeropoints.
673
         */
674
        CV_WRAP void getOutputDetails(CV_OUT std::vector<float>& scales, CV_OUT std::vector<int>& zeropoints) const;
675
676
        /**
677
         * @brief Compile Halide layers.
678
         * @param[in] scheduler Path to YAML file with scheduling directives.
679
         * @see setPreferableBackend
680
         *
681
         * Schedule layers that support Halide backend. Then compile them for
682
         * specific target. For layers that not represented in scheduling file
683
         * or if no manual scheduling used at all, automatic scheduling will be applied.
684
         */
685
        CV_WRAP void setHalideScheduler(const String& scheduler);
686
687
        /**
688
         * @brief Ask network to use specific computation backend where it supported.
689
         * @param[in] backendId backend identifier.
690
         * @see Backend
691
         *
692
         * If OpenCV is compiled with Intel's Inference Engine library, DNN_BACKEND_DEFAULT
693
         * means DNN_BACKEND_INFERENCE_ENGINE. Otherwise it equals to DNN_BACKEND_OPENCV.
694
         */
695
        CV_WRAP void setPreferableBackend(int backendId);
696
697
        /**
698
         * @brief Ask network to make computations on specific target device.
699
         * @param[in] targetId target identifier.
700
         * @see Target
701
         *
702
         * List of supported combinations backend / target:
703
         * |                        | DNN_BACKEND_OPENCV | DNN_BACKEND_INFERENCE_ENGINE | DNN_BACKEND_HALIDE |  DNN_BACKEND_CUDA |
704
         * |------------------------|--------------------|------------------------------|--------------------|-------------------|
705
         * | DNN_TARGET_CPU         |                  + |                            + |                  + |                   |
706
         * | DNN_TARGET_OPENCL      |                  + |                            + |                  + |                   |
707
         * | DNN_TARGET_OPENCL_FP16 |                  + |                            + |                    |                   |
708
         * | DNN_TARGET_MYRIAD      |                    |                            + |                    |                   |
709
         * | DNN_TARGET_FPGA        |                    |                            + |                    |                   |
710
         * | DNN_TARGET_CUDA        |                    |                              |                    |                 + |
711
         * | DNN_TARGET_CUDA_FP16   |                    |                              |                    |                 + |
712
         * | DNN_TARGET_HDDL        |                    |                            + |                    |                   |
713
         */
714
        CV_WRAP void setPreferableTarget(int targetId);
715
716
        /** @brief Sets the new input value for the network
717
         *  @param blob        A new blob. Should have CV_32F or CV_8U depth.
718
         *  @param name        A name of input layer.
719
         *  @param scalefactor An optional normalization scale.
720
         *  @param mean        An optional mean subtraction values.
721
         *  @see connect(String, String) to know format of the descriptor.
722
         *
723
         *  If scale or mean values are specified, a final input blob is computed
724
         *  as:
725
         * \f[input(n,c,h,w) = scalefactor \times (blob(n,c,h,w) - mean_c)\f]
726
         */
727
        CV_WRAP void setInput(InputArray blob, const String& name = "",
728
                              double scalefactor = 1.0, const Scalar& mean = Scalar());
729
730
        /** @brief Sets the new value for the learned param of the layer.
731
         *  @param layer name or id of the layer.
732
         *  @param numParam index of the layer parameter in the Layer::blobs array.
733
         *  @param blob the new value.
734
         *  @see Layer::blobs
735
         *  @note If shape of the new blob differs from the previous shape,
736
         *  then the following forward pass may fail.
737
        */
738
        CV_WRAP void setParam(int layer, int numParam, const Mat &blob);
739
0
        CV_WRAP inline void setParam(const String& layerName, int numParam, const Mat &blob) { return setParam(getLayerId(layerName), numParam, blob); }
740
741
        /** @brief Returns parameter blob of the layer.
742
         *  @param layer name or id of the layer.
743
         *  @param numParam index of the layer parameter in the Layer::blobs array.
744
         *  @see Layer::blobs
745
         */
746
        CV_WRAP Mat getParam(int layer, int numParam = 0) const;
747
0
        CV_WRAP inline Mat getParam(const String& layerName, int numParam = 0) const { return getParam(getLayerId(layerName), numParam); }
748
749
        /** @brief Returns indexes of layers with unconnected outputs.
750
         *
751
         * FIXIT: Rework API to registerOutput() approach, deprecate this call
752
         */
753
        CV_WRAP std::vector<int> getUnconnectedOutLayers() const;
754
755
        /** @brief Returns names of layers with unconnected outputs.
756
         *
757
         * FIXIT: Rework API to registerOutput() approach, deprecate this call
758
         */
759
        CV_WRAP std::vector<String> getUnconnectedOutLayersNames() const;
760
761
        /** @brief Returns input and output shapes for all layers in loaded model;
762
         *  preliminary inferencing isn't necessary.
763
         *  @param netInputShapes shapes for all input blobs in net input layer.
764
         *  @param layersIds output parameter for layer IDs.
765
         *  @param inLayersShapes output parameter for input layers shapes;
766
         * order is the same as in layersIds
767
         *  @param outLayersShapes output parameter for output layers shapes;
768
         * order is the same as in layersIds
769
         */
770
        CV_WRAP void getLayersShapes(const std::vector<MatShape>& netInputShapes,
771
                                     CV_OUT std::vector<int>& layersIds,
772
                                     CV_OUT std::vector<std::vector<MatShape> >& inLayersShapes,
773
                                     CV_OUT std::vector<std::vector<MatShape> >& outLayersShapes) const;
774
775
        /** @overload */
776
        CV_WRAP void getLayersShapes(const MatShape& netInputShape,
777
                                     CV_OUT std::vector<int>& layersIds,
778
                                     CV_OUT std::vector<std::vector<MatShape> >& inLayersShapes,
779
                                     CV_OUT std::vector<std::vector<MatShape> >& outLayersShapes) const;
780
781
        /** @brief Returns input and output shapes for layer with specified
782
         * id in loaded model; preliminary inferencing isn't necessary.
783
         *  @param netInputShape shape input blob in net input layer.
784
         *  @param layerId id for layer.
785
         *  @param inLayerShapes output parameter for input layers shapes;
786
         * order is the same as in layersIds
787
         *  @param outLayerShapes output parameter for output layers shapes;
788
         * order is the same as in layersIds
789
         */
790
        void getLayerShapes(const MatShape& netInputShape,
791
                                    const int layerId,
792
                                    CV_OUT std::vector<MatShape>& inLayerShapes,
793
                                    CV_OUT std::vector<MatShape>& outLayerShapes) const; // FIXIT: CV_WRAP
794
795
        /** @overload */
796
        void getLayerShapes(const std::vector<MatShape>& netInputShapes,
797
                                    const int layerId,
798
                                    CV_OUT std::vector<MatShape>& inLayerShapes,
799
                                    CV_OUT std::vector<MatShape>& outLayerShapes) const; // FIXIT: CV_WRAP
800
801
        /** @brief Computes FLOP for whole loaded model with specified input shapes.
802
         * @param netInputShapes vector of shapes for all net inputs.
803
         * @returns computed FLOP.
804
         */
805
        CV_WRAP int64 getFLOPS(const std::vector<MatShape>& netInputShapes) const;
806
        /** @overload */
807
        CV_WRAP int64 getFLOPS(const MatShape& netInputShape) const;
808
        /** @overload */
809
        CV_WRAP int64 getFLOPS(const int layerId,
810
                               const std::vector<MatShape>& netInputShapes) const;
811
        /** @overload */
812
        CV_WRAP int64 getFLOPS(const int layerId,
813
                               const MatShape& netInputShape) const;
814
815
        /** @brief Returns list of types for layer used in model.
816
         * @param layersTypes output parameter for returning types.
817
         */
818
        CV_WRAP void getLayerTypes(CV_OUT std::vector<String>& layersTypes) const;
819
820
        /** @brief Returns count of layers of specified type.
821
         * @param layerType type.
822
         * @returns count of layers
823
         */
824
        CV_WRAP int getLayersCount(const String& layerType) const;
825
826
        /** @brief Computes bytes number which are required to store
827
         * all weights and intermediate blobs for model.
828
         * @param netInputShapes vector of shapes for all net inputs.
829
         * @param weights output parameter to store resulting bytes for weights.
830
         * @param blobs output parameter to store resulting bytes for intermediate blobs.
831
         */
832
        void getMemoryConsumption(const std::vector<MatShape>& netInputShapes,
833
                                          CV_OUT size_t& weights, CV_OUT size_t& blobs) const; // FIXIT: CV_WRAP
834
        /** @overload */
835
        CV_WRAP void getMemoryConsumption(const MatShape& netInputShape,
836
                                          CV_OUT size_t& weights, CV_OUT size_t& blobs) const;
837
        /** @overload */
838
        CV_WRAP void getMemoryConsumption(const int layerId,
839
                                          const std::vector<MatShape>& netInputShapes,
840
                                          CV_OUT size_t& weights, CV_OUT size_t& blobs) const;
841
        /** @overload */
842
        CV_WRAP void getMemoryConsumption(const int layerId,
843
                                          const MatShape& netInputShape,
844
                                          CV_OUT size_t& weights, CV_OUT size_t& blobs) const;
845
846
        /** @brief Computes bytes number which are required to store
847
         * all weights and intermediate blobs for each layer.
848
         * @param netInputShapes vector of shapes for all net inputs.
849
         * @param layerIds output vector to save layer IDs.
850
         * @param weights output parameter to store resulting bytes for weights.
851
         * @param blobs output parameter to store resulting bytes for intermediate blobs.
852
         */
853
        void getMemoryConsumption(const std::vector<MatShape>& netInputShapes,
854
                                          CV_OUT std::vector<int>& layerIds,
855
                                          CV_OUT std::vector<size_t>& weights,
856
                                          CV_OUT std::vector<size_t>& blobs) const; // FIXIT: CV_WRAP
857
        /** @overload */
858
        void getMemoryConsumption(const MatShape& netInputShape,
859
                                          CV_OUT std::vector<int>& layerIds,
860
                                          CV_OUT std::vector<size_t>& weights,
861
                                          CV_OUT std::vector<size_t>& blobs) const; // FIXIT: CV_WRAP
862
863
        /** @brief Enables or disables layer fusion in the network.
864
         * @param fusion true to enable the fusion, false to disable. The fusion is enabled by default.
865
         */
866
        CV_WRAP void enableFusion(bool fusion);
867
868
        /** @brief Enables or disables the Winograd compute branch. The Winograd compute branch can speed up
869
         * 3x3 Convolution at a small loss of accuracy.
870
        * @param useWinograd true to enable the Winograd compute branch. The default is true.
871
        */
872
        CV_WRAP void enableWinograd(bool useWinograd);
873
874
        /** @brief Returns overall time for inference and timings (in ticks) for layers.
875
         *
876
         * Indexes in returned vector correspond to layers ids. Some layers can be fused with others,
877
         * in this case zero ticks count will be return for that skipped layers. Supported by DNN_BACKEND_OPENCV on DNN_TARGET_CPU only.
878
         *
879
         * @param[out] timings vector for tick timings for all layers.
880
         * @return overall ticks for model inference.
881
         */
882
        CV_WRAP int64 getPerfProfile(CV_OUT std::vector<double>& timings);
883
884
885
        struct Impl;
886
0
        inline Impl* getImpl() const { return impl.get(); }
887
0
        inline Impl& getImplRef() const { CV_DbgAssert(impl); return *impl.get(); }
888
        friend class accessor::DnnNetAccessor;
889
    protected:
890
        Ptr<Impl> impl;
891
    };
892
893
    /** @brief Reads a network model stored in <a href="https://pjreddie.com/darknet/">Darknet</a> model files.
894
    *  @param cfgFile      path to the .cfg file with text description of the network architecture.
895
    *  @param darknetModel path to the .weights file with learned network.
896
    *  @returns Network object that ready to do forward, throw an exception in failure cases.
897
    *  @returns Net object.
898
    */
899
    CV_EXPORTS_W Net readNetFromDarknet(const String &cfgFile, const String &darknetModel = String());
900
901
    /** @brief Reads a network model stored in <a href="https://pjreddie.com/darknet/">Darknet</a> model files.
902
     *  @param bufferCfg   A buffer contains a content of .cfg file with text description of the network architecture.
903
     *  @param bufferModel A buffer contains a content of .weights file with learned network.
904
     *  @returns Net object.
905
     */
906
    CV_EXPORTS_W Net readNetFromDarknet(const std::vector<uchar>& bufferCfg,
907
                                        const std::vector<uchar>& bufferModel = std::vector<uchar>());
908
909
    /** @brief Reads a network model stored in <a href="https://pjreddie.com/darknet/">Darknet</a> model files.
910
     *  @param bufferCfg   A buffer contains a content of .cfg file with text description of the network architecture.
911
     *  @param lenCfg      Number of bytes to read from bufferCfg
912
     *  @param bufferModel A buffer contains a content of .weights file with learned network.
913
     *  @param lenModel    Number of bytes to read from bufferModel
914
     *  @returns Net object.
915
     */
916
    CV_EXPORTS Net readNetFromDarknet(const char *bufferCfg, size_t lenCfg,
917
                                      const char *bufferModel = NULL, size_t lenModel = 0);
918
919
    /** @brief Reads a network model stored in <a href="http://caffe.berkeleyvision.org">Caffe</a> framework's format.
920
      * @param prototxt   path to the .prototxt file with text description of the network architecture.
921
      * @param caffeModel path to the .caffemodel file with learned network.
922
      * @returns Net object.
923
      */
924
    CV_EXPORTS_W Net readNetFromCaffe(const String &prototxt, const String &caffeModel = String());
925
926
    /** @brief Reads a network model stored in Caffe model in memory.
927
      * @param bufferProto buffer containing the content of the .prototxt file
928
      * @param bufferModel buffer containing the content of the .caffemodel file
929
      * @returns Net object.
930
      */
931
    CV_EXPORTS_W Net readNetFromCaffe(const std::vector<uchar>& bufferProto,
932
                                      const std::vector<uchar>& bufferModel = std::vector<uchar>());
933
934
    /** @brief Reads a network model stored in Caffe model in memory.
935
      * @details This is an overloaded member function, provided for convenience.
936
      * It differs from the above function only in what argument(s) it accepts.
937
      * @param bufferProto buffer containing the content of the .prototxt file
938
      * @param lenProto length of bufferProto
939
      * @param bufferModel buffer containing the content of the .caffemodel file
940
      * @param lenModel length of bufferModel
941
      * @returns Net object.
942
      */
943
    CV_EXPORTS Net readNetFromCaffe(const char *bufferProto, size_t lenProto,
944
                                    const char *bufferModel = NULL, size_t lenModel = 0);
945
946
    /** @brief Reads a network model stored in <a href="https://www.tensorflow.org/">TensorFlow</a> framework's format.
947
      * @param model  path to the .pb file with binary protobuf description of the network architecture
948
      * @param config path to the .pbtxt file that contains text graph definition in protobuf format.
949
      *               Resulting Net object is built by text graph using weights from a binary one that
950
      *               let us make it more flexible.
951
      * @returns Net object.
952
      */
953
    CV_EXPORTS_W Net readNetFromTensorflow(const String &model, const String &config = String());
954
955
    /** @brief Reads a network model stored in <a href="https://www.tensorflow.org/">TensorFlow</a> framework's format.
956
      * @param bufferModel buffer containing the content of the pb file
957
      * @param bufferConfig buffer containing the content of the pbtxt file
958
      * @returns Net object.
959
      */
960
    CV_EXPORTS_W Net readNetFromTensorflow(const std::vector<uchar>& bufferModel,
961
                                           const std::vector<uchar>& bufferConfig = std::vector<uchar>());
962
963
    /** @brief Reads a network model stored in <a href="https://www.tensorflow.org/">TensorFlow</a> framework's format.
964
      * @details This is an overloaded member function, provided for convenience.
965
      * It differs from the above function only in what argument(s) it accepts.
966
      * @param bufferModel buffer containing the content of the pb file
967
      * @param lenModel length of bufferModel
968
      * @param bufferConfig buffer containing the content of the pbtxt file
969
      * @param lenConfig length of bufferConfig
970
      */
971
    CV_EXPORTS Net readNetFromTensorflow(const char *bufferModel, size_t lenModel,
972
                                         const char *bufferConfig = NULL, size_t lenConfig = 0);
973
974
    /** @brief Reads a network model stored in <a href="https://www.tensorflow.org/lite">TFLite</a> framework's format.
975
      * @param model  path to the .tflite file with binary flatbuffers description of the network architecture
976
      * @returns Net object.
977
      */
978
    CV_EXPORTS_W Net readNetFromTFLite(const String &model);
979
980
    /** @brief Reads a network model stored in <a href="https://www.tensorflow.org/lite">TFLite</a> framework's format.
981
      * @param bufferModel buffer containing the content of the tflite file
982
      * @returns Net object.
983
      */
984
    CV_EXPORTS_W Net readNetFromTFLite(const std::vector<uchar>& bufferModel);
985
986
    /** @brief Reads a network model stored in <a href="https://www.tensorflow.org/lite">TFLite</a> framework's format.
987
      * @details This is an overloaded member function, provided for convenience.
988
      * It differs from the above function only in what argument(s) it accepts.
989
      * @param bufferModel buffer containing the content of the tflite file
990
      * @param lenModel length of bufferModel
991
      */
992
    CV_EXPORTS Net readNetFromTFLite(const char *bufferModel, size_t lenModel);
993
994
    /**
995
     *  @brief Reads a network model stored in <a href="http://torch.ch">Torch7</a> framework's format.
996
     *  @param model    path to the file, dumped from Torch by using torch.save() function.
997
     *  @param isBinary specifies whether the network was serialized in ascii mode or binary.
998
     *  @param evaluate specifies testing phase of network. If true, it's similar to evaluate() method in Torch.
999
     *  @returns Net object.
1000
     *
1001
     *  @note Ascii mode of Torch serializer is more preferable, because binary mode extensively use `long` type of C language,
1002
     *  which has various bit-length on different systems.
1003
     *
1004
     * The loading file must contain serialized <a href="https://github.com/torch/nn/blob/master/doc/module.md">nn.Module</a> object
1005
     * with importing network. Try to eliminate a custom objects from serialazing data to avoid importing errors.
1006
     *
1007
     * List of supported layers (i.e. object instances derived from Torch nn.Module class):
1008
     * - nn.Sequential
1009
     * - nn.Parallel
1010
     * - nn.Concat
1011
     * - nn.Linear
1012
     * - nn.SpatialConvolution
1013
     * - nn.SpatialMaxPooling, nn.SpatialAveragePooling
1014
     * - nn.ReLU, nn.TanH, nn.Sigmoid
1015
     * - nn.Reshape
1016
     * - nn.SoftMax, nn.LogSoftMax
1017
     *
1018
     * Also some equivalents of these classes from cunn, cudnn, and fbcunn may be successfully imported.
1019
     */
1020
     CV_EXPORTS_W Net readNetFromTorch(const String &model, bool isBinary = true, bool evaluate = true);
1021
1022
     /**
1023
      * @brief Read deep learning network represented in one of the supported formats.
1024
      * @param[in] model Binary file contains trained weights. The following file
1025
      *                  extensions are expected for models from different frameworks:
1026
      *                  * `*.caffemodel` (Caffe, http://caffe.berkeleyvision.org/)
1027
      *                  * `*.pb` (TensorFlow, https://www.tensorflow.org/)
1028
      *                  * `*.t7` | `*.net` (Torch, http://torch.ch/)
1029
      *                  * `*.weights` (Darknet, https://pjreddie.com/darknet/)
1030
      *                  * `*.bin` (DLDT, https://software.intel.com/openvino-toolkit)
1031
      *                  * `*.onnx` (ONNX, https://onnx.ai/)
1032
      * @param[in] config Text file contains network configuration. It could be a
1033
      *                   file with the following extensions:
1034
      *                  * `*.prototxt` (Caffe, http://caffe.berkeleyvision.org/)
1035
      *                  * `*.pbtxt` (TensorFlow, https://www.tensorflow.org/)
1036
      *                  * `*.cfg` (Darknet, https://pjreddie.com/darknet/)
1037
      *                  * `*.xml` (DLDT, https://software.intel.com/openvino-toolkit)
1038
      * @param[in] framework Explicit framework name tag to determine a format.
1039
      * @returns Net object.
1040
      *
1041
      * This function automatically detects an origin framework of trained model
1042
      * and calls an appropriate function such @ref readNetFromCaffe, @ref readNetFromTensorflow,
1043
      * @ref readNetFromTorch or @ref readNetFromDarknet. An order of @p model and @p config
1044
      * arguments does not matter.
1045
      */
1046
     CV_EXPORTS_W Net readNet(const String& model, const String& config = "", const String& framework = "");
1047
1048
     /**
1049
      * @brief Read deep learning network represented in one of the supported formats.
1050
      * @details This is an overloaded member function, provided for convenience.
1051
      *          It differs from the above function only in what argument(s) it accepts.
1052
      * @param[in] framework    Name of origin framework.
1053
      * @param[in] bufferModel  A buffer with a content of binary file with weights
1054
      * @param[in] bufferConfig A buffer with a content of text file contains network configuration.
1055
      * @returns Net object.
1056
      */
1057
     CV_EXPORTS_W Net readNet(const String& framework, const std::vector<uchar>& bufferModel,
1058
                              const std::vector<uchar>& bufferConfig = std::vector<uchar>());
1059
1060
    /** @brief Loads blob which was serialized as torch.Tensor object of Torch7 framework.
1061
     *  @warning This function has the same limitations as readNetFromTorch().
1062
     */
1063
    CV_EXPORTS_W Mat readTorchBlob(const String &filename, bool isBinary = true);
1064
1065
    /** @brief Load a network from Intel's Model Optimizer intermediate representation.
1066
     *  @param[in] xml XML configuration file with network's topology.
1067
     *  @param[in] bin Binary file with trained weights.
1068
     *  @returns Net object.
1069
     *  Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine
1070
     *  backend.
1071
     */
1072
    CV_EXPORTS_W
1073
    Net readNetFromModelOptimizer(const String &xml, const String &bin);
1074
1075
    /** @brief Load a network from Intel's Model Optimizer intermediate representation.
1076
     *  @param[in] bufferModelConfig Buffer contains XML configuration with network's topology.
1077
     *  @param[in] bufferWeights Buffer contains binary data with trained weights.
1078
     *  @returns Net object.
1079
     *  Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine
1080
     *  backend.
1081
     */
1082
    CV_EXPORTS_W
1083
    Net readNetFromModelOptimizer(const std::vector<uchar>& bufferModelConfig, const std::vector<uchar>& bufferWeights);
1084
1085
    /** @brief Load a network from Intel's Model Optimizer intermediate representation.
1086
     *  @param[in] bufferModelConfigPtr Pointer to buffer which contains XML configuration with network's topology.
1087
     *  @param[in] bufferModelConfigSize Binary size of XML configuration data.
1088
     *  @param[in] bufferWeightsPtr Pointer to buffer which contains binary data with trained weights.
1089
     *  @param[in] bufferWeightsSize Binary size of trained weights data.
1090
     *  @returns Net object.
1091
     *  Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine
1092
     *  backend.
1093
     */
1094
    CV_EXPORTS
1095
    Net readNetFromModelOptimizer(const uchar* bufferModelConfigPtr, size_t bufferModelConfigSize,
1096
                                           const uchar* bufferWeightsPtr, size_t bufferWeightsSize);
1097
1098
    /** @brief Reads a network model <a href="https://onnx.ai/">ONNX</a>.
1099
     *  @param onnxFile path to the .onnx file with text description of the network architecture.
1100
     *  @returns Network object that ready to do forward, throw an exception in failure cases.
1101
     */
1102
    CV_EXPORTS_W Net readNetFromONNX(const String &onnxFile);
1103
1104
    /** @brief Reads a network model from <a href="https://onnx.ai/">ONNX</a>
1105
     *         in-memory buffer.
1106
     *  @param buffer memory address of the first byte of the buffer.
1107
     *  @param sizeBuffer size of the buffer.
1108
     *  @returns Network object that ready to do forward, throw an exception
1109
     *        in failure cases.
1110
     */
1111
    CV_EXPORTS Net readNetFromONNX(const char* buffer, size_t sizeBuffer);
1112
1113
    /** @brief Reads a network model from <a href="https://onnx.ai/">ONNX</a>
1114
     *         in-memory buffer.
1115
     *  @param buffer in-memory buffer that stores the ONNX model bytes.
1116
     *  @returns Network object that ready to do forward, throw an exception
1117
     *        in failure cases.
1118
     */
1119
    CV_EXPORTS_W Net readNetFromONNX(const std::vector<uchar>& buffer);
1120
1121
    /** @brief Creates blob from .pb file.
1122
     *  @param path to the .pb file with input tensor.
1123
     *  @returns Mat.
1124
     */
1125
    CV_EXPORTS_W Mat readTensorFromONNX(const String& path);
1126
1127
    /** @brief Creates 4-dimensional blob from image. Optionally resizes and crops @p image from center,
1128
     *  subtract @p mean values, scales values by @p scalefactor, swap Blue and Red channels.
1129
     *  @param image input image (with 1-, 3- or 4-channels).
1130
     *  @param scalefactor multiplier for @p images values.
1131
     *  @param size spatial size for output image
1132
     *  @param mean scalar with mean values which are subtracted from channels. Values are intended
1133
     *  to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true.
1134
     *  @param swapRB flag which indicates that swap first and last channels
1135
     *  in 3-channel image is necessary.
1136
     *  @param crop flag which indicates whether image will be cropped after resize or not
1137
     *  @param ddepth Depth of output blob. Choose CV_32F or CV_8U.
1138
     *  @details if @p crop is true, input image is resized so one side after resize is equal to corresponding
1139
     *  dimension in @p size and another one is equal or larger. Then, crop from the center is performed.
1140
     *  If @p crop is false, direct resize without cropping and preserving aspect ratio is performed.
1141
     *  @returns 4-dimensional Mat with NCHW dimensions order.
1142
     *
1143
     * @note
1144
     * The order and usage of `scalefactor` and `mean` are (input - mean) * scalefactor.
1145
     */
1146
    CV_EXPORTS_W Mat blobFromImage(InputArray image, double scalefactor=1.0, const Size& size = Size(),
1147
                                   const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false,
1148
                                   int ddepth=CV_32F);
1149
1150
    /** @brief Creates 4-dimensional blob from image.
1151
     *  @details This is an overloaded member function, provided for convenience.
1152
     *           It differs from the above function only in what argument(s) it accepts.
1153
     */
1154
    CV_EXPORTS void blobFromImage(InputArray image, OutputArray blob, double scalefactor=1.0,
1155
                                  const Size& size = Size(), const Scalar& mean = Scalar(),
1156
                                  bool swapRB=false, bool crop=false, int ddepth=CV_32F);
1157
1158
1159
    /** @brief Creates 4-dimensional blob from series of images. Optionally resizes and
1160
     *  crops @p images from center, subtract @p mean values, scales values by @p scalefactor,
1161
     *  swap Blue and Red channels.
1162
     *  @param images input images (all with 1-, 3- or 4-channels).
1163
     *  @param size spatial size for output image
1164
     *  @param mean scalar with mean values which are subtracted from channels. Values are intended
1165
     *  to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true.
1166
     *  @param scalefactor multiplier for @p images values.
1167
     *  @param swapRB flag which indicates that swap first and last channels
1168
     *  in 3-channel image is necessary.
1169
     *  @param crop flag which indicates whether image will be cropped after resize or not
1170
     *  @param ddepth Depth of output blob. Choose CV_32F or CV_8U.
1171
     *  @details if @p crop is true, input image is resized so one side after resize is equal to corresponding
1172
     *  dimension in @p size and another one is equal or larger. Then, crop from the center is performed.
1173
     *  If @p crop is false, direct resize without cropping and preserving aspect ratio is performed.
1174
     *  @returns 4-dimensional Mat with NCHW dimensions order.
1175
     *
1176
     * @note
1177
     * The order and usage of `scalefactor` and `mean` are (input - mean) * scalefactor.
1178
     */
1179
    CV_EXPORTS_W Mat blobFromImages(InputArrayOfArrays images, double scalefactor=1.0,
1180
                                    Size size = Size(), const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false,
1181
                                    int ddepth=CV_32F);
1182
1183
    /** @brief Creates 4-dimensional blob from series of images.
1184
     *  @details This is an overloaded member function, provided for convenience.
1185
     *           It differs from the above function only in what argument(s) it accepts.
1186
     */
1187
    CV_EXPORTS void blobFromImages(InputArrayOfArrays images, OutputArray blob,
1188
                                   double scalefactor=1.0, Size size = Size(),
1189
                                   const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false,
1190
                                   int ddepth=CV_32F);
1191
1192
    /**
1193
     * @brief Enum of image processing mode.
1194
     * To facilitate the specialization pre-processing requirements of the dnn model.
1195
     * For example, the `letter box` often used in the Yolo series of models.
1196
     * @see Image2BlobParams
1197
     */
1198
    enum ImagePaddingMode
1199
    {
1200
        DNN_PMODE_NULL = 0,        // !< Default. Resize to required input size without extra processing.
1201
        DNN_PMODE_CROP_CENTER = 1, // !< Image will be cropped after resize.
1202
        DNN_PMODE_LETTERBOX = 2,   // !< Resize image to the desired size while preserving the aspect ratio of original image.
1203
    };
1204
1205
    /** @brief Processing params of image to blob.
1206
     *
1207
     * It includes all possible image processing operations and corresponding parameters.
1208
     *
1209
     * @see blobFromImageWithParams
1210
     *
1211
     * @note
1212
     * The order and usage of `scalefactor` and `mean` are (input - mean) * scalefactor.
1213
     * The order and usage of `scalefactor`, `size`, `mean`, `swapRB`, and `ddepth` are consistent
1214
     * with the function of @ref blobFromImage.
1215
    */
1216
    struct CV_EXPORTS_W_SIMPLE Image2BlobParams
1217
    {
1218
        CV_WRAP Image2BlobParams();
1219
        CV_WRAP Image2BlobParams(const Scalar& scalefactor, const Size& size = Size(), const Scalar& mean = Scalar(),
1220
                            bool swapRB = false, int ddepth = CV_32F, DataLayout datalayout = DNN_LAYOUT_NCHW,
1221
                            ImagePaddingMode mode = DNN_PMODE_NULL);
1222
1223
        CV_PROP_RW Scalar scalefactor; //!< scalefactor multiplier for input image values.
1224
        CV_PROP_RW Size size;    //!< Spatial size for output image.
1225
        CV_PROP_RW Scalar mean;  //!< Scalar with mean values which are subtracted from channels.
1226
        CV_PROP_RW bool swapRB;  //!< Flag which indicates that swap first and last channels
1227
        CV_PROP_RW int ddepth;   //!< Depth of output blob. Choose CV_32F or CV_8U.
1228
        CV_PROP_RW DataLayout datalayout; //!< Order of output dimensions. Choose DNN_LAYOUT_NCHW or DNN_LAYOUT_NHWC.
1229
        CV_PROP_RW ImagePaddingMode paddingmode;   //!< Image padding mode. @see ImagePaddingMode.
1230
    };
1231
1232
    /** @brief Creates 4-dimensional blob from image with given params.
1233
     *
1234
     *  @details This function is an extension of @ref blobFromImage to meet more image preprocess needs.
1235
     *  Given input image and preprocessing parameters, and function outputs the blob.
1236
     *
1237
     *  @param image input image (all with 1-, 3- or 4-channels).
1238
     *  @param param struct of Image2BlobParams, contains all parameters needed by processing of image to blob.
1239
     *  @return 4-dimensional Mat.
1240
     */
1241
    CV_EXPORTS_W Mat blobFromImageWithParams(InputArray image, const Image2BlobParams& param = Image2BlobParams());
1242
1243
    /** @overload */
1244
    CV_EXPORTS_W void blobFromImageWithParams(InputArray image, OutputArray blob, const Image2BlobParams& param = Image2BlobParams());
1245
1246
    /** @brief Creates 4-dimensional blob from series of images with given params.
1247
     *
1248
     *  @details This function is an extension of @ref blobFromImages to meet more image preprocess needs.
1249
     *  Given input image and preprocessing parameters, and function outputs the blob.
1250
     *
1251
     *  @param images input image (all with 1-, 3- or 4-channels).
1252
     *  @param param struct of Image2BlobParams, contains all parameters needed by processing of image to blob.
1253
     *  @returns 4-dimensional Mat.
1254
     */
1255
    CV_EXPORTS_W Mat blobFromImagesWithParams(InputArrayOfArrays images, const Image2BlobParams& param = Image2BlobParams());
1256
1257
    /** @overload */
1258
    CV_EXPORTS_W void blobFromImagesWithParams(InputArrayOfArrays images, OutputArray blob, const Image2BlobParams& param = Image2BlobParams());
1259
1260
    /** @brief Parse a 4D blob and output the images it contains as 2D arrays through a simpler data structure
1261
     *  (std::vector<cv::Mat>).
1262
     *  @param[in] blob_ 4 dimensional array (images, channels, height, width) in floating point precision (CV_32F) from
1263
     *  which you would like to extract the images.
1264
     *  @param[out] images_ array of 2D Mat containing the images extracted from the blob in floating point precision
1265
     *  (CV_32F). They are non normalized neither mean added. The number of returned images equals the first dimension
1266
     *  of the blob (batch size). Every image has a number of channels equals to the second dimension of the blob (depth).
1267
     */
1268
    CV_EXPORTS_W void imagesFromBlob(const cv::Mat& blob_, OutputArrayOfArrays images_);
1269
1270
    /** @brief Convert all weights of Caffe network to half precision floating point.
1271
     * @param src Path to origin model from Caffe framework contains single
1272
     *            precision floating point weights (usually has `.caffemodel` extension).
1273
     * @param dst Path to destination model with updated weights.
1274
     * @param layersTypes Set of layers types which parameters will be converted.
1275
     *                    By default, converts only Convolutional and Fully-Connected layers'
1276
     *                    weights.
1277
     *
1278
     * @note Shrinked model has no origin float32 weights so it can't be used
1279
     *       in origin Caffe framework anymore. However the structure of data
1280
     *       is taken from NVidia's Caffe fork: https://github.com/NVIDIA/caffe.
1281
     *       So the resulting model may be used there.
1282
     */
1283
    CV_EXPORTS_W void shrinkCaffeModel(const String& src, const String& dst,
1284
                                       const std::vector<String>& layersTypes = std::vector<String>());
1285
1286
    /** @brief Create a text representation for a binary network stored in protocol buffer format.
1287
     *  @param[in] model  A path to binary network.
1288
     *  @param[in] output A path to output text file to be created.
1289
     *
1290
     *  @note To reduce output file size, trained weights are not included.
1291
     */
1292
    CV_EXPORTS_W void writeTextGraph(const String& model, const String& output);
1293
1294
    /** @brief Performs non maximum suppression given boxes and corresponding scores.
1295
1296
     * @param bboxes a set of bounding boxes to apply NMS.
1297
     * @param scores a set of corresponding confidences.
1298
     * @param score_threshold a threshold used to filter boxes by score.
1299
     * @param nms_threshold a threshold used in non maximum suppression.
1300
     * @param indices the kept indices of bboxes after NMS.
1301
     * @param eta a coefficient in adaptive threshold formula: \f$nms\_threshold_{i+1}=eta\cdot nms\_threshold_i\f$.
1302
     * @param top_k if `>0`, keep at most @p top_k picked indices.
1303
     */
1304
    CV_EXPORTS void NMSBoxes(const std::vector<Rect>& bboxes, const std::vector<float>& scores,
1305
                               const float score_threshold, const float nms_threshold,
1306
                               CV_OUT std::vector<int>& indices,
1307
                               const float eta = 1.f, const int top_k = 0);
1308
1309
    CV_EXPORTS_W void NMSBoxes(const std::vector<Rect2d>& bboxes, const std::vector<float>& scores,
1310
                               const float score_threshold, const float nms_threshold,
1311
                               CV_OUT std::vector<int>& indices,
1312
                               const float eta = 1.f, const int top_k = 0);
1313
1314
    CV_EXPORTS_AS(NMSBoxesRotated) void NMSBoxes(const std::vector<RotatedRect>& bboxes, const std::vector<float>& scores,
1315
                             const float score_threshold, const float nms_threshold,
1316
                             CV_OUT std::vector<int>& indices,
1317
                             const float eta = 1.f, const int top_k = 0);
1318
1319
    /** @brief Performs batched non maximum suppression on given boxes and corresponding scores across different classes.
1320
1321
     * @param bboxes a set of bounding boxes to apply NMS.
1322
     * @param scores a set of corresponding confidences.
1323
     * @param class_ids a set of corresponding class ids. Ids are integer and usually start from 0.
1324
     * @param score_threshold a threshold used to filter boxes by score.
1325
     * @param nms_threshold a threshold used in non maximum suppression.
1326
     * @param indices the kept indices of bboxes after NMS.
1327
     * @param eta a coefficient in adaptive threshold formula: \f$nms\_threshold_{i+1}=eta\cdot nms\_threshold_i\f$.
1328
     * @param top_k if `>0`, keep at most @p top_k picked indices.
1329
     */
1330
    CV_EXPORTS void NMSBoxesBatched(const std::vector<Rect>& bboxes, const std::vector<float>& scores, const std::vector<int>& class_ids,
1331
                                    const float score_threshold, const float nms_threshold,
1332
                                    CV_OUT std::vector<int>& indices,
1333
                                    const float eta = 1.f, const int top_k = 0);
1334
1335
    CV_EXPORTS_W void NMSBoxesBatched(const std::vector<Rect2d>& bboxes, const std::vector<float>& scores, const std::vector<int>& class_ids,
1336
                                      const float score_threshold, const float nms_threshold,
1337
                                      CV_OUT std::vector<int>& indices,
1338
                                      const float eta = 1.f, const int top_k = 0);
1339
1340
    /**
1341
     * @brief Enum of Soft NMS methods.
1342
     * @see softNMSBoxes
1343
     */
1344
    enum class SoftNMSMethod
1345
    {
1346
        SOFTNMS_LINEAR = 1,
1347
        SOFTNMS_GAUSSIAN = 2
1348
    };
1349
1350
    /** @brief Performs soft non maximum suppression given boxes and corresponding scores.
1351
     * Reference: https://arxiv.org/abs/1704.04503
1352
     * @param bboxes a set of bounding boxes to apply Soft NMS.
1353
     * @param scores a set of corresponding confidences.
1354
     * @param updated_scores a set of corresponding updated confidences.
1355
     * @param score_threshold a threshold used to filter boxes by score.
1356
     * @param nms_threshold a threshold used in non maximum suppression.
1357
     * @param indices the kept indices of bboxes after NMS.
1358
     * @param top_k keep at most @p top_k picked indices.
1359
     * @param sigma parameter of Gaussian weighting.
1360
     * @param method Gaussian or linear.
1361
     * @see SoftNMSMethod
1362
     */
1363
    CV_EXPORTS_W void softNMSBoxes(const std::vector<Rect>& bboxes,
1364
                                   const std::vector<float>& scores,
1365
                                   CV_OUT std::vector<float>& updated_scores,
1366
                                   const float score_threshold,
1367
                                   const float nms_threshold,
1368
                                   CV_OUT std::vector<int>& indices,
1369
                                   size_t top_k = 0,
1370
                                   const float sigma = 0.5,
1371
                                   SoftNMSMethod method = SoftNMSMethod::SOFTNMS_GAUSSIAN);
1372
1373
1374
     /** @brief This class is presented high-level API for neural networks.
1375
      *
1376
      * Model allows to set params for preprocessing input image.
1377
      * Model creates net from file with trained weights and config,
1378
      * sets preprocessing input and runs forward pass.
1379
      */
1380
     class CV_EXPORTS_W_SIMPLE Model
1381
     {
1382
     public:
1383
         CV_DEPRECATED_EXTERNAL  // avoid using in C++ code, will be moved to "protected" (need to fix bindings first)
1384
         Model();
1385
1386
         Model(const Model&) = default;
1387
         Model(Model&&) = default;
1388
         Model& operator=(const Model&) = default;
1389
         Model& operator=(Model&&) = default;
1390
1391
         /**
1392
          * @brief Create model from deep learning network represented in one of the supported formats.
1393
          * An order of @p model and @p config arguments does not matter.
1394
          * @param[in] model Binary file contains trained weights.
1395
          * @param[in] config Text file contains network configuration.
1396
          */
1397
         CV_WRAP Model(const String& model, const String& config = "");
1398
1399
         /**
1400
          * @brief Create model from deep learning network.
1401
          * @param[in] network Net object.
1402
          */
1403
         CV_WRAP Model(const Net& network);
1404
1405
         /** @brief Set input size for frame.
1406
          *  @param[in] size New input size.
1407
          *  @note If shape of the new blob less than 0, then frame size not change.
1408
         */
1409
         CV_WRAP Model& setInputSize(const Size& size);
1410
1411
         /** @overload
1412
         *  @param[in] width New input width.
1413
         *  @param[in] height New input height.
1414
         */
1415
         CV_WRAP inline
1416
0
         Model& setInputSize(int width, int height) { return setInputSize(Size(width, height)); }
1417
1418
         /** @brief Set mean value for frame.
1419
          *  @param[in] mean Scalar with mean values which are subtracted from channels.
1420
         */
1421
         CV_WRAP Model& setInputMean(const Scalar& mean);
1422
1423
         /** @brief Set scalefactor value for frame.
1424
          *  @param[in] scale Multiplier for frame values.
1425
         */
1426
         CV_WRAP Model& setInputScale(const Scalar& scale);
1427
1428
         /** @brief Set flag crop for frame.
1429
          *  @param[in] crop Flag which indicates whether image will be cropped after resize or not.
1430
         */
1431
         CV_WRAP Model& setInputCrop(bool crop);
1432
1433
         /** @brief Set flag swapRB for frame.
1434
          *  @param[in] swapRB Flag which indicates that swap first and last channels.
1435
         */
1436
         CV_WRAP Model& setInputSwapRB(bool swapRB);
1437
1438
         /** @brief Set preprocessing parameters for frame.
1439
         *  @param[in] size New input size.
1440
         *  @param[in] mean Scalar with mean values which are subtracted from channels.
1441
         *  @param[in] scale Multiplier for frame values.
1442
         *  @param[in] swapRB Flag which indicates that swap first and last channels.
1443
         *  @param[in] crop Flag which indicates whether image will be cropped after resize or not.
1444
         *  blob(n, c, y, x) = scale * resize( frame(y, x, c) ) - mean(c) )
1445
         */
1446
         CV_WRAP void setInputParams(double scale = 1.0, const Size& size = Size(),
1447
                                     const Scalar& mean = Scalar(), bool swapRB = false, bool crop = false);
1448
1449
         /** @brief Given the @p input frame, create input blob, run net and return the output @p blobs.
1450
          *  @param[in]  frame  The input image.
1451
          *  @param[out] outs Allocated output blobs, which will store results of the computation.
1452
          */
1453
         CV_WRAP void predict(InputArray frame, OutputArrayOfArrays outs) const;
1454
1455
1456
         // ============================== Net proxy methods ==============================
1457
         // Never expose methods with network implementation details, like:
1458
         // - addLayer, addLayerToPrev, connect, setInputsNames, setInputShape, setParam, getParam
1459
         // - getLayer*, getUnconnectedOutLayers, getUnconnectedOutLayersNames, getLayersShapes
1460
         // - forward* methods, setInput
1461
1462
         /// @sa Net::setPreferableBackend
1463
         CV_WRAP Model& setPreferableBackend(dnn::Backend backendId);
1464
         /// @sa Net::setPreferableTarget
1465
         CV_WRAP Model& setPreferableTarget(dnn::Target targetId);
1466
1467
         CV_DEPRECATED_EXTERNAL
1468
0
         operator Net&() const { return getNetwork_(); }
1469
1470
     //protected: - internal/tests usage only
1471
         Net& getNetwork_() const;
1472
0
         inline Net& getNetwork_() { return const_cast<const Model*>(this)->getNetwork_(); }
1473
1474
         struct Impl;
1475
0
         inline Impl* getImpl() const { return impl.get(); }
1476
0
         inline Impl& getImplRef() const { CV_DbgAssert(impl); return *impl.get(); }
1477
     protected:
1478
         Ptr<Impl> impl;
1479
     };
1480
1481
     /** @brief This class represents high-level API for classification models.
1482
      *
1483
      * ClassificationModel allows to set params for preprocessing input image.
1484
      * ClassificationModel creates net from file with trained weights and config,
1485
      * sets preprocessing input, runs forward pass and return top-1 prediction.
1486
      */
1487
     class CV_EXPORTS_W_SIMPLE ClassificationModel : public Model
1488
     {
1489
     public:
1490
         CV_DEPRECATED_EXTERNAL  // avoid using in C++ code, will be moved to "protected" (need to fix bindings first)
1491
         ClassificationModel();
1492
1493
         /**
1494
          * @brief Create classification model from network represented in one of the supported formats.
1495
          * An order of @p model and @p config arguments does not matter.
1496
          * @param[in] model Binary file contains trained weights.
1497
          * @param[in] config Text file contains network configuration.
1498
          */
1499
          CV_WRAP ClassificationModel(const String& model, const String& config = "");
1500
1501
         /**
1502
          * @brief Create model from deep learning network.
1503
          * @param[in] network Net object.
1504
          */
1505
         CV_WRAP ClassificationModel(const Net& network);
1506
1507
         /**
1508
          * @brief Set enable/disable softmax post processing option.
1509
          *
1510
          * If this option is true, softmax is applied after forward inference within the classify() function
1511
          * to convert the confidences range to [0.0-1.0].
1512
          * This function allows you to toggle this behavior.
1513
          * Please turn true when not contain softmax layer in model.
1514
          * @param[in] enable Set enable softmax post processing within the classify() function.
1515
          */
1516
         CV_WRAP ClassificationModel& setEnableSoftmaxPostProcessing(bool enable);
1517
1518
         /**
1519
          * @brief Get enable/disable softmax post processing option.
1520
          *
1521
          * This option defaults to false, softmax post processing is not applied within the classify() function.
1522
          */
1523
         CV_WRAP bool getEnableSoftmaxPostProcessing() const;
1524
1525
         /** @brief Given the @p input frame, create input blob, run net and return top-1 prediction.
1526
          *  @param[in]  frame  The input image.
1527
          */
1528
         std::pair<int, float> classify(InputArray frame);
1529
1530
         /** @overload */
1531
         CV_WRAP void classify(InputArray frame, CV_OUT int& classId, CV_OUT float& conf);
1532
     };
1533
1534
     /** @brief This class represents high-level API for keypoints models
1535
      *
1536
      * KeypointsModel allows to set params for preprocessing input image.
1537
      * KeypointsModel creates net from file with trained weights and config,
1538
      * sets preprocessing input, runs forward pass and returns the x and y coordinates of each detected keypoint
1539
      */
1540
     class CV_EXPORTS_W_SIMPLE KeypointsModel: public Model
1541
     {
1542
     public:
1543
         /**
1544
          * @brief Create keypoints model from network represented in one of the supported formats.
1545
          * An order of @p model and @p config arguments does not matter.
1546
          * @param[in] model Binary file contains trained weights.
1547
          * @param[in] config Text file contains network configuration.
1548
          */
1549
          CV_WRAP KeypointsModel(const String& model, const String& config = "");
1550
1551
         /**
1552
          * @brief Create model from deep learning network.
1553
          * @param[in] network Net object.
1554
          */
1555
         CV_WRAP KeypointsModel(const Net& network);
1556
1557
         /** @brief Given the @p input frame, create input blob, run net
1558
          *  @param[in]  frame  The input image.
1559
          *  @param thresh minimum confidence threshold to select a keypoint
1560
          *  @returns a vector holding the x and y coordinates of each detected keypoint
1561
          *
1562
          */
1563
         CV_WRAP std::vector<Point2f> estimate(InputArray frame, float thresh=0.5);
1564
     };
1565
1566
     /** @brief This class represents high-level API for segmentation  models
1567
      *
1568
      * SegmentationModel allows to set params for preprocessing input image.
1569
      * SegmentationModel creates net from file with trained weights and config,
1570
      * sets preprocessing input, runs forward pass and returns the class prediction for each pixel.
1571
      */
1572
     class CV_EXPORTS_W_SIMPLE SegmentationModel: public Model
1573
     {
1574
     public:
1575
         /**
1576
          * @brief Create segmentation model from network represented in one of the supported formats.
1577
          * An order of @p model and @p config arguments does not matter.
1578
          * @param[in] model Binary file contains trained weights.
1579
          * @param[in] config Text file contains network configuration.
1580
          */
1581
          CV_WRAP SegmentationModel(const String& model, const String& config = "");
1582
1583
         /**
1584
          * @brief Create model from deep learning network.
1585
          * @param[in] network Net object.
1586
          */
1587
         CV_WRAP SegmentationModel(const Net& network);
1588
1589
         /** @brief Given the @p input frame, create input blob, run net
1590
          *  @param[in]  frame  The input image.
1591
          *  @param[out] mask Allocated class prediction for each pixel
1592
          */
1593
         CV_WRAP void segment(InputArray frame, OutputArray mask);
1594
     };
1595
1596
     /** @brief This class represents high-level API for object detection networks.
1597
      *
1598
      * DetectionModel allows to set params for preprocessing input image.
1599
      * DetectionModel creates net from file with trained weights and config,
1600
      * sets preprocessing input, runs forward pass and return result detections.
1601
      * For DetectionModel SSD, Faster R-CNN, YOLO topologies are supported.
1602
      */
1603
     class CV_EXPORTS_W_SIMPLE DetectionModel : public Model
1604
     {
1605
     public:
1606
         /**
1607
          * @brief Create detection model from network represented in one of the supported formats.
1608
          * An order of @p model and @p config arguments does not matter.
1609
          * @param[in] model Binary file contains trained weights.
1610
          * @param[in] config Text file contains network configuration.
1611
          */
1612
         CV_WRAP DetectionModel(const String& model, const String& config = "");
1613
1614
         /**
1615
          * @brief Create model from deep learning network.
1616
          * @param[in] network Net object.
1617
          */
1618
         CV_WRAP DetectionModel(const Net& network);
1619
1620
         CV_DEPRECATED_EXTERNAL  // avoid using in C++ code (need to fix bindings first)
1621
         DetectionModel();
1622
1623
         /**
1624
          * @brief nmsAcrossClasses defaults to false,
1625
          * such that when non max suppression is used during the detect() function, it will do so per-class.
1626
          * This function allows you to toggle this behaviour.
1627
          * @param[in] value The new value for nmsAcrossClasses
1628
          */
1629
         CV_WRAP DetectionModel& setNmsAcrossClasses(bool value);
1630
1631
         /**
1632
          * @brief Getter for nmsAcrossClasses. This variable defaults to false,
1633
          * such that when non max suppression is used during the detect() function, it will do so only per-class
1634
          */
1635
         CV_WRAP bool getNmsAcrossClasses();
1636
1637
         /** @brief Given the @p input frame, create input blob, run net and return result detections.
1638
          *  @param[in]  frame  The input image.
1639
          *  @param[out] classIds Class indexes in result detection.
1640
          *  @param[out] confidences A set of corresponding confidences.
1641
          *  @param[out] boxes A set of bounding boxes.
1642
          *  @param[in] confThreshold A threshold used to filter boxes by confidences.
1643
          *  @param[in] nmsThreshold A threshold used in non maximum suppression.
1644
          */
1645
         CV_WRAP void detect(InputArray frame, CV_OUT std::vector<int>& classIds,
1646
                             CV_OUT std::vector<float>& confidences, CV_OUT std::vector<Rect>& boxes,
1647
                             float confThreshold = 0.5f, float nmsThreshold = 0.0f);
1648
     };
1649
1650
1651
/** @brief This class represents high-level API for text recognition networks.
1652
 *
1653
 * TextRecognitionModel allows to set params for preprocessing input image.
1654
 * TextRecognitionModel creates net from file with trained weights and config,
1655
 * sets preprocessing input, runs forward pass and return recognition result.
1656
 * For TextRecognitionModel, CRNN-CTC is supported.
1657
 */
1658
class CV_EXPORTS_W_SIMPLE TextRecognitionModel : public Model
1659
{
1660
public:
1661
    CV_DEPRECATED_EXTERNAL  // avoid using in C++ code, will be moved to "protected" (need to fix bindings first)
1662
    TextRecognitionModel();
1663
1664
    /**
1665
     * @brief Create Text Recognition model from deep learning network
1666
     * Call setDecodeType() and setVocabulary() after constructor to initialize the decoding method
1667
     * @param[in] network Net object
1668
     */
1669
    CV_WRAP TextRecognitionModel(const Net& network);
1670
1671
    /**
1672
     * @brief Create text recognition model from network represented in one of the supported formats
1673
     * Call setDecodeType() and setVocabulary() after constructor to initialize the decoding method
1674
     * @param[in] model Binary file contains trained weights
1675
     * @param[in] config Text file contains network configuration
1676
     */
1677
    CV_WRAP inline
1678
    TextRecognitionModel(const std::string& model, const std::string& config = "")
1679
0
        : TextRecognitionModel(readNet(model, config)) { /* nothing */ }
1680
1681
    /**
1682
     * @brief Set the decoding method of translating the network output into string
1683
     * @param[in] decodeType The decoding method of translating the network output into string, currently supported type:
1684
     *    - `"CTC-greedy"` greedy decoding for the output of CTC-based methods
1685
     *    - `"CTC-prefix-beam-search"` Prefix beam search decoding for the output of CTC-based methods
1686
     */
1687
    CV_WRAP
1688
    TextRecognitionModel& setDecodeType(const std::string& decodeType);
1689
1690
    /**
1691
     * @brief Get the decoding method
1692
     * @return the decoding method
1693
     */
1694
    CV_WRAP
1695
    const std::string& getDecodeType() const;
1696
1697
    /**
1698
     * @brief Set the decoding method options for `"CTC-prefix-beam-search"` decode usage
1699
     * @param[in] beamSize Beam size for search
1700
     * @param[in] vocPruneSize Parameter to optimize big vocabulary search,
1701
     * only take top @p vocPruneSize tokens in each search step, @p vocPruneSize <= 0 stands for disable this prune.
1702
     */
1703
    CV_WRAP
1704
    TextRecognitionModel& setDecodeOptsCTCPrefixBeamSearch(int beamSize, int vocPruneSize = 0);
1705
1706
    /**
1707
     * @brief Set the vocabulary for recognition.
1708
     * @param[in] vocabulary the associated vocabulary of the network.
1709
     */
1710
    CV_WRAP
1711
    TextRecognitionModel& setVocabulary(const std::vector<std::string>& vocabulary);
1712
1713
    /**
1714
     * @brief Get the vocabulary for recognition.
1715
     * @return vocabulary the associated vocabulary
1716
     */
1717
    CV_WRAP
1718
    const std::vector<std::string>& getVocabulary() const;
1719
1720
    /**
1721
     * @brief Given the @p input frame, create input blob, run net and return recognition result
1722
     * @param[in] frame The input image
1723
     * @return The text recognition result
1724
     */
1725
    CV_WRAP
1726
    std::string recognize(InputArray frame) const;
1727
1728
    /**
1729
     * @brief Given the @p input frame, create input blob, run net and return recognition result
1730
     * @param[in] frame The input image
1731
     * @param[in] roiRects List of text detection regions of interest (cv::Rect, CV_32SC4). ROIs is be cropped as the network inputs
1732
     * @param[out] results A set of text recognition results.
1733
     */
1734
    CV_WRAP
1735
    void recognize(InputArray frame, InputArrayOfArrays roiRects, CV_OUT std::vector<std::string>& results) const;
1736
};
1737
1738
1739
/** @brief Base class for text detection networks
1740
 */
1741
class CV_EXPORTS_W_SIMPLE TextDetectionModel : public Model
1742
{
1743
protected:
1744
    CV_DEPRECATED_EXTERNAL  // avoid using in C++ code, will be moved to "protected" (need to fix bindings first)
1745
    TextDetectionModel();
1746
1747
public:
1748
1749
    /** @brief Performs detection
1750
     *
1751
     * Given the input @p frame, prepare network input, run network inference, post-process network output and return result detections.
1752
     *
1753
     * Each result is quadrangle's 4 points in this order:
1754
     * - bottom-left
1755
     * - top-left
1756
     * - top-right
1757
     * - bottom-right
1758
     *
1759
     * Use cv::getPerspectiveTransform function to retrieve image region without perspective transformations.
1760
     *
1761
     * @note If DL model doesn't support that kind of output then result may be derived from detectTextRectangles() output.
1762
     *
1763
     * @param[in] frame The input image
1764
     * @param[out] detections array with detections' quadrangles (4 points per result)
1765
     * @param[out] confidences array with detection confidences
1766
     */
1767
    CV_WRAP
1768
    void detect(
1769
            InputArray frame,
1770
            CV_OUT std::vector< std::vector<Point> >& detections,
1771
            CV_OUT std::vector<float>& confidences
1772
    ) const;
1773
1774
    /** @overload */
1775
    CV_WRAP
1776
    void detect(
1777
            InputArray frame,
1778
            CV_OUT std::vector< std::vector<Point> >& detections
1779
    ) const;
1780
1781
    /** @brief Performs detection
1782
     *
1783
     * Given the input @p frame, prepare network input, run network inference, post-process network output and return result detections.
1784
     *
1785
     * Each result is rotated rectangle.
1786
     *
1787
     * @note Result may be inaccurate in case of strong perspective transformations.
1788
     *
1789
     * @param[in] frame the input image
1790
     * @param[out] detections array with detections' RotationRect results
1791
     * @param[out] confidences array with detection confidences
1792
     */
1793
    CV_WRAP
1794
    void detectTextRectangles(
1795
            InputArray frame,
1796
            CV_OUT std::vector<cv::RotatedRect>& detections,
1797
            CV_OUT std::vector<float>& confidences
1798
    ) const;
1799
1800
    /** @overload */
1801
    CV_WRAP
1802
    void detectTextRectangles(
1803
            InputArray frame,
1804
            CV_OUT std::vector<cv::RotatedRect>& detections
1805
    ) const;
1806
};
1807
1808
/** @brief This class represents high-level API for text detection DL networks compatible with EAST model.
1809
 *
1810
 * Configurable parameters:
1811
 * - (float) confThreshold - used to filter boxes by confidences, default: 0.5f
1812
 * - (float) nmsThreshold - used in non maximum suppression, default: 0.0f
1813
 */
1814
class CV_EXPORTS_W_SIMPLE TextDetectionModel_EAST : public TextDetectionModel
1815
{
1816
public:
1817
    CV_DEPRECATED_EXTERNAL  // avoid using in C++ code, will be moved to "protected" (need to fix bindings first)
1818
    TextDetectionModel_EAST();
1819
1820
    /**
1821
     * @brief Create text detection algorithm from deep learning network
1822
     * @param[in] network Net object
1823
     */
1824
    CV_WRAP TextDetectionModel_EAST(const Net& network);
1825
1826
    /**
1827
     * @brief Create text detection model from network represented in one of the supported formats.
1828
     * An order of @p model and @p config arguments does not matter.
1829
     * @param[in] model Binary file contains trained weights.
1830
     * @param[in] config Text file contains network configuration.
1831
     */
1832
    CV_WRAP inline
1833
    TextDetectionModel_EAST(const std::string& model, const std::string& config = "")
1834
0
        : TextDetectionModel_EAST(readNet(model, config)) { /* nothing */ }
1835
1836
    /**
1837
     * @brief Set the detection confidence threshold
1838
     * @param[in] confThreshold A threshold used to filter boxes by confidences
1839
     */
1840
    CV_WRAP
1841
    TextDetectionModel_EAST& setConfidenceThreshold(float confThreshold);
1842
1843
    /**
1844
     * @brief Get the detection confidence threshold
1845
     */
1846
    CV_WRAP
1847
    float getConfidenceThreshold() const;
1848
1849
    /**
1850
     * @brief Set the detection NMS filter threshold
1851
     * @param[in] nmsThreshold A threshold used in non maximum suppression
1852
     */
1853
    CV_WRAP
1854
    TextDetectionModel_EAST& setNMSThreshold(float nmsThreshold);
1855
1856
    /**
1857
     * @brief Get the detection confidence threshold
1858
     */
1859
    CV_WRAP
1860
    float getNMSThreshold() const;
1861
};
1862
1863
/** @brief This class represents high-level API for text detection DL networks compatible with DB model.
1864
 *
1865
 * Related publications: @cite liao2020real
1866
 * Paper: https://arxiv.org/abs/1911.08947
1867
 * For more information about the hyper-parameters setting, please refer to https://github.com/MhLiao/DB
1868
 *
1869
 * Configurable parameters:
1870
 * - (float) binaryThreshold - The threshold of the binary map. It is usually set to 0.3.
1871
 * - (float) polygonThreshold - The threshold of text polygons. It is usually set to 0.5, 0.6, and 0.7. Default is 0.5f
1872
 * - (double) unclipRatio - The unclip ratio of the detected text region, which determines the output size. It is usually set to 2.0.
1873
 * - (int) maxCandidates - The max number of the output results.
1874
 */
1875
class CV_EXPORTS_W_SIMPLE TextDetectionModel_DB : public TextDetectionModel
1876
{
1877
public:
1878
    CV_DEPRECATED_EXTERNAL  // avoid using in C++ code, will be moved to "protected" (need to fix bindings first)
1879
    TextDetectionModel_DB();
1880
1881
    /**
1882
     * @brief Create text detection algorithm from deep learning network.
1883
     * @param[in] network Net object.
1884
     */
1885
    CV_WRAP TextDetectionModel_DB(const Net& network);
1886
1887
    /**
1888
     * @brief Create text detection model from network represented in one of the supported formats.
1889
     * An order of @p model and @p config arguments does not matter.
1890
     * @param[in] model Binary file contains trained weights.
1891
     * @param[in] config Text file contains network configuration.
1892
     */
1893
    CV_WRAP inline
1894
    TextDetectionModel_DB(const std::string& model, const std::string& config = "")
1895
0
        : TextDetectionModel_DB(readNet(model, config)) { /* nothing */ }
1896
1897
    CV_WRAP TextDetectionModel_DB& setBinaryThreshold(float binaryThreshold);
1898
    CV_WRAP float getBinaryThreshold() const;
1899
1900
    CV_WRAP TextDetectionModel_DB& setPolygonThreshold(float polygonThreshold);
1901
    CV_WRAP float getPolygonThreshold() const;
1902
1903
    CV_WRAP TextDetectionModel_DB& setUnclipRatio(double unclipRatio);
1904
    CV_WRAP double getUnclipRatio() const;
1905
1906
    CV_WRAP TextDetectionModel_DB& setMaxCandidates(int maxCandidates);
1907
    CV_WRAP int getMaxCandidates() const;
1908
};
1909
1910
//! @}
1911
CV__DNN_INLINE_NS_END
1912
}
1913
}
1914
1915
#include <opencv2/dnn/layer.hpp>
1916
#include <opencv2/dnn/dnn.inl.hpp>
1917
1918
/// @deprecated Include this header directly from application. Automatic inclusion will be removed
1919
#include <opencv2/dnn/utils/inference_engine.hpp>
1920
1921
#endif  /* OPENCV_DNN_DNN_HPP */