Merge pull request #14827 from YashasSamaga:cuda4dnn-csl-low
[platform/upstream/opencv.git] / modules / dnn / include / opencv2 / dnn / dnn.hpp
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 CV__DNN_INLINE_NS_BEGIN
56 //! @addtogroup dnn
57 //! @{
58
59     typedef std::vector<int> MatShape;
60
61     /**
62      * @brief Enum of computation backends supported by layers.
63      * @see Net::setPreferableBackend
64      */
65     enum Backend
66     {
67         //! DNN_BACKEND_DEFAULT equals to DNN_BACKEND_INFERENCE_ENGINE if
68         //! OpenCV is built with Intel's Inference Engine library or
69         //! DNN_BACKEND_OPENCV otherwise.
70         DNN_BACKEND_DEFAULT,
71         DNN_BACKEND_HALIDE,
72         DNN_BACKEND_INFERENCE_ENGINE,  //!< Intel's Inference Engine computational backend.
73         DNN_BACKEND_OPENCV,
74         DNN_BACKEND_VKCOM,
75         DNN_BACKEND_CUDA
76     };
77
78     /**
79      * @brief Enum of target devices for computations.
80      * @see Net::setPreferableTarget
81      */
82     enum Target
83     {
84         DNN_TARGET_CPU,
85         DNN_TARGET_OPENCL,
86         DNN_TARGET_OPENCL_FP16,
87         DNN_TARGET_MYRIAD,
88         DNN_TARGET_VULKAN,
89         DNN_TARGET_FPGA,  //!< FPGA device with CPU fallbacks using Inference Engine's Heterogeneous plugin.
90         DNN_TARGET_CUDA,
91         DNN_TARGET_CUDA_FP16
92     };
93
94     CV_EXPORTS std::vector< std::pair<Backend, Target> > getAvailableBackends();
95     CV_EXPORTS std::vector<Target> getAvailableTargets(Backend be);
96
97     /** @brief This class provides all data needed to initialize layer.
98      *
99      * It includes dictionary with scalar params (which can be read by using Dict interface),
100      * blob params #blobs and optional meta information: #name and #type of layer instance.
101     */
102     class CV_EXPORTS LayerParams : public Dict
103     {
104     public:
105         //TODO: Add ability to name blob params
106         std::vector<Mat> blobs; //!< List of learned parameters stored as blobs.
107
108         String name; //!< Name of the layer instance (optional, can be used internal purposes).
109         String type; //!< Type name which was used for creating layer by layer factory (optional).
110     };
111
112    /**
113     * @brief Derivatives of this class encapsulates functions of certain backends.
114     */
115     class BackendNode
116     {
117     public:
118         BackendNode(int backendId);
119
120         virtual ~BackendNode(); //!< Virtual destructor to make polymorphism.
121
122         int backendId; //!< Backend identifier.
123     };
124
125     /**
126      * @brief Derivatives of this class wraps cv::Mat for different backends and targets.
127      */
128     class BackendWrapper
129     {
130     public:
131         BackendWrapper(int backendId, int targetId);
132
133         /**
134          * @brief Wrap cv::Mat for specific backend and target.
135          * @param[in] targetId Target identifier.
136          * @param[in] m cv::Mat for wrapping.
137          *
138          * Make CPU->GPU data transfer if it's require for the target.
139          */
140         BackendWrapper(int targetId, const cv::Mat& m);
141
142         /**
143          * @brief Make wrapper for reused cv::Mat.
144          * @param[in] base Wrapper of cv::Mat that will be reused.
145          * @param[in] shape Specific shape.
146          *
147          * Initialize wrapper from another one. It'll wrap the same host CPU
148          * memory and mustn't allocate memory on device(i.e. GPU). It might
149          * has different shape. Use in case of CPU memory reusing for reuse
150          * associated memory on device too.
151          */
152         BackendWrapper(const Ptr<BackendWrapper>& base, const MatShape& shape);
153
154         virtual ~BackendWrapper(); //!< Virtual destructor to make polymorphism.
155
156         /**
157          * @brief Transfer data to CPU host memory.
158          */
159         virtual void copyToHost() = 0;
160
161         /**
162          * @brief Indicate that an actual data is on CPU.
163          */
164         virtual void setHostDirty() = 0;
165
166         int backendId;  //!< Backend identifier.
167         int targetId;   //!< Target identifier.
168     };
169
170     class CV_EXPORTS ActivationLayer;
171
172     /** @brief This interface class allows to build new Layers - are building blocks of networks.
173      *
174      * Each class, derived from Layer, must implement allocate() methods to declare own outputs and forward() to compute outputs.
175      * Also before using the new layer into networks you must register your layer by using one of @ref dnnLayerFactory "LayerFactory" macros.
176      */
177     class CV_EXPORTS_W Layer : public Algorithm
178     {
179     public:
180
181         //! List of learned parameters must be stored here to allow read them by using Net::getParam().
182         CV_PROP_RW std::vector<Mat> blobs;
183
184         /** @brief Computes and sets internal parameters according to inputs, outputs and blobs.
185          *  @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead
186          *  @param[in]  input  vector of already allocated input blobs
187          *  @param[out] output vector of already allocated output blobs
188          *
189          * If this method is called after network has allocated all memory for input and output blobs
190          * and before inferencing.
191          */
192         CV_DEPRECATED_EXTERNAL
193         virtual void finalize(const std::vector<Mat*> &input, std::vector<Mat> &output);
194
195         /** @brief Computes and sets internal parameters according to inputs, outputs and blobs.
196          *  @param[in]  inputs  vector of already allocated input blobs
197          *  @param[out] outputs vector of already allocated output blobs
198          *
199          * If this method is called after network has allocated all memory for input and output blobs
200          * and before inferencing.
201          */
202         CV_WRAP virtual void finalize(InputArrayOfArrays inputs, OutputArrayOfArrays outputs);
203
204         /** @brief Given the @p input blobs, computes the output @p blobs.
205          *  @deprecated Use Layer::forward(InputArrayOfArrays, OutputArrayOfArrays, OutputArrayOfArrays) instead
206          *  @param[in]  input  the input blobs.
207          *  @param[out] output allocated output blobs, which will store results of the computation.
208          *  @param[out] internals allocated internal blobs
209          */
210         CV_DEPRECATED_EXTERNAL
211         virtual void forward(std::vector<Mat*> &input, std::vector<Mat> &output, std::vector<Mat> &internals);
212
213         /** @brief Given the @p input blobs, computes the output @p blobs.
214          *  @param[in]  inputs  the input blobs.
215          *  @param[out] outputs allocated output blobs, which will store results of the computation.
216          *  @param[out] internals allocated internal blobs
217          */
218         virtual void forward(InputArrayOfArrays inputs, OutputArrayOfArrays outputs, OutputArrayOfArrays internals);
219
220         /** @brief Given the @p input blobs, computes the output @p blobs.
221          *  @param[in]  inputs  the input blobs.
222          *  @param[out] outputs allocated output blobs, which will store results of the computation.
223          *  @param[out] internals allocated internal blobs
224          */
225         void forward_fallback(InputArrayOfArrays inputs, OutputArrayOfArrays outputs, OutputArrayOfArrays internals);
226
227         /** @brief
228          * @overload
229          * @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead
230          */
231         CV_DEPRECATED_EXTERNAL
232         void finalize(const std::vector<Mat> &inputs, CV_OUT std::vector<Mat> &outputs);
233
234         /** @brief
235          * @overload
236          * @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead
237          */
238         CV_DEPRECATED std::vector<Mat> finalize(const std::vector<Mat> &inputs);
239
240         /** @brief Allocates layer and computes output.
241          *  @deprecated This method will be removed in the future release.
242          */
243         CV_DEPRECATED CV_WRAP void run(const std::vector<Mat> &inputs, CV_OUT std::vector<Mat> &outputs,
244                                        CV_IN_OUT std::vector<Mat> &internals);
245
246         /** @brief Returns index of input blob into the input array.
247          *  @param inputName label of input blob
248          *
249          * Each layer input and output can be labeled to easily identify them using "%<layer_name%>[.output_name]" notation.
250          * This method maps label of input blob to its index into input vector.
251          */
252         virtual int inputNameToIndex(String inputName);
253         /** @brief Returns index of output blob in output array.
254          *  @see inputNameToIndex()
255          */
256         CV_WRAP virtual int outputNameToIndex(const String& outputName);
257
258         /**
259          * @brief Ask layer if it support specific backend for doing computations.
260          * @param[in] backendId computation backend identifier.
261          * @see Backend
262          */
263         virtual bool supportBackend(int backendId);
264
265         /**
266          * @brief Returns Halide backend node.
267          * @param[in] inputs Input Halide buffers.
268          * @see BackendNode, BackendWrapper
269          *
270          * Input buffers should be exactly the same that will be used in forward invocations.
271          * Despite we can use Halide::ImageParam based on input shape only,
272          * it helps prevent some memory management issues (if something wrong,
273          * Halide tests will be failed).
274          */
275         virtual Ptr<BackendNode> initHalide(const std::vector<Ptr<BackendWrapper> > &inputs);
276
277         virtual Ptr<BackendNode> initInfEngine(const std::vector<Ptr<BackendWrapper> > &inputs);
278
279         virtual Ptr<BackendNode> initVkCom(const std::vector<Ptr<BackendWrapper> > &inputs);
280
281         /**
282          * @brief Returns a CUDA backend node
283          *
284          * @param   context  void pointer to CSLContext object
285          * @param   inputs   layer inputs
286          * @param   outputs  layer outputs
287          */
288         virtual Ptr<BackendNode> initCUDA(
289             void *context,
290             const std::vector<Ptr<BackendWrapper>>& inputs,
291             const std::vector<Ptr<BackendWrapper>>& outputs
292         );
293
294        /**
295         * @brief Automatic Halide scheduling based on layer hyper-parameters.
296         * @param[in] node Backend node with Halide functions.
297         * @param[in] inputs Blobs that will be used in forward invocations.
298         * @param[in] outputs Blobs that will be used in forward invocations.
299         * @param[in] targetId Target identifier
300         * @see BackendNode, Target
301         *
302         * Layer don't use own Halide::Func members because we can have applied
303         * layers fusing. In this way the fused function should be scheduled.
304         */
305         virtual void applyHalideScheduler(Ptr<BackendNode>& node,
306                                           const std::vector<Mat*> &inputs,
307                                           const std::vector<Mat> &outputs,
308                                           int targetId) const;
309
310         /**
311          * @brief Implement layers fusing.
312          * @param[in] node Backend node of bottom layer.
313          * @see BackendNode
314          *
315          * Actual for graph-based backends. If layer attached successfully,
316          * returns non-empty cv::Ptr to node of the same backend.
317          * Fuse only over the last function.
318          */
319         virtual Ptr<BackendNode> tryAttach(const Ptr<BackendNode>& node);
320
321         /**
322          * @brief Tries to attach to the layer the subsequent activation layer, i.e. do the layer fusion in a partial case.
323          * @param[in] layer The subsequent activation layer.
324          *
325          * Returns true if the activation layer has been attached successfully.
326          */
327         virtual bool setActivation(const Ptr<ActivationLayer>& layer);
328
329         /**
330          * @brief Try to fuse current layer with a next one
331          * @param[in] top Next layer to be fused.
332          * @returns True if fusion was performed.
333          */
334         virtual bool tryFuse(Ptr<Layer>& top);
335
336         /**
337          * @brief Returns parameters of layers with channel-wise multiplication and addition.
338          * @param[out] scale Channel-wise multipliers. Total number of values should
339          *                   be equal to number of channels.
340          * @param[out] shift Channel-wise offsets. Total number of values should
341          *                   be equal to number of channels.
342          *
343          * Some layers can fuse their transformations with further layers.
344          * In example, convolution + batch normalization. This way base layer
345          * use weights from layer after it. Fused layer is skipped.
346          * By default, @p scale and @p shift are empty that means layer has no
347          * element-wise multiplications or additions.
348          */
349         virtual void getScaleShift(Mat& scale, Mat& shift) const;
350
351         /**
352          * @brief "Deattaches" all the layers, attached to particular layer.
353          */
354         virtual void unsetAttached();
355
356         virtual bool getMemoryShapes(const std::vector<MatShape> &inputs,
357                                      const int requiredOutputs,
358                                      std::vector<MatShape> &outputs,
359                                      std::vector<MatShape> &internals) const;
360         virtual int64 getFLOPS(const std::vector<MatShape> &inputs,
361                                const std::vector<MatShape> &outputs) const {CV_UNUSED(inputs); CV_UNUSED(outputs); return 0;}
362
363         CV_PROP String name; //!< Name of the layer instance, can be used for logging or other internal purposes.
364         CV_PROP String type; //!< Type name which was used for creating layer by layer factory.
365         CV_PROP int preferableTarget; //!< prefer target for layer forwarding
366
367         Layer();
368         explicit Layer(const LayerParams &params);      //!< Initializes only #name, #type and #blobs fields.
369         void setParamsFrom(const LayerParams &params);  //!< Initializes only #name, #type and #blobs fields.
370         virtual ~Layer();
371     };
372
373     /** @brief This class allows to create and manipulate comprehensive artificial neural networks.
374      *
375      * Neural network is presented as directed acyclic graph (DAG), where vertices are Layer instances,
376      * and edges specify relationships between layers inputs and outputs.
377      *
378      * Each network layer has unique integer id and unique string name inside its network.
379      * LayerId can store either layer name or layer id.
380      *
381      * This class supports reference counting of its instances, i. e. copies point to the same instance.
382      */
383     class CV_EXPORTS_W_SIMPLE Net
384     {
385     public:
386
387         CV_WRAP Net();  //!< Default constructor.
388         CV_WRAP ~Net(); //!< Destructor frees the net only if there aren't references to the net anymore.
389
390         /** @brief Create a network from Intel's Model Optimizer intermediate representation.
391          *  @param[in] xml XML configuration file with network's topology.
392          *  @param[in] bin Binary file with trained weights.
393          *  Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine
394          *  backend.
395          */
396         CV_WRAP static Net readFromModelOptimizer(const String& xml, const String& bin);
397
398         /** Returns true if there are no layers in the network. */
399         CV_WRAP bool empty() const;
400
401         /** @brief Dump net to String
402          *  @returns String with structure, hyperparameters, backend, target and fusion
403          *  Call method after setInput(). To see correct backend, target and fusion run after forward().
404          */
405         CV_WRAP String dump();
406         /** @brief Dump net structure, hyperparameters, backend, target and fusion to dot file
407          *  @param path   path to output file with .dot extension
408          *  @see dump()
409          */
410         CV_WRAP void dumpToFile(const String& path);
411         /** @brief Adds new layer to the net.
412          *  @param name   unique name of the adding layer.
413          *  @param type   typename of the adding layer (type must be registered in LayerRegister).
414          *  @param params parameters which will be used to initialize the creating layer.
415          *  @returns unique identifier of created layer, or -1 if a failure will happen.
416          */
417         int addLayer(const String &name, const String &type, LayerParams &params);
418         /** @brief Adds new layer and connects its first input to the first output of previously added layer.
419          *  @see addLayer()
420          */
421         int addLayerToPrev(const String &name, const String &type, LayerParams &params);
422
423         /** @brief Converts string name of the layer to the integer identifier.
424          *  @returns id of the layer, or -1 if the layer wasn't found.
425          */
426         CV_WRAP int getLayerId(const String &layer);
427
428         CV_WRAP std::vector<String> getLayerNames() const;
429
430         /** @brief Container for strings and integers. */
431         typedef DictValue LayerId;
432
433         /** @brief Returns pointer to layer with specified id or name which the network use. */
434         CV_WRAP Ptr<Layer> getLayer(LayerId layerId);
435
436         /** @brief Returns pointers to input layers of specific layer. */
437         std::vector<Ptr<Layer> > getLayerInputs(LayerId layerId); // FIXIT: CV_WRAP
438
439         /** @brief Connects output of the first layer to input of the second layer.
440          *  @param outPin descriptor of the first layer output.
441          *  @param inpPin descriptor of the second layer input.
442          *
443          * Descriptors have the following template <DFN>&lt;layer_name&gt;[.input_number]</DFN>:
444          * - the first part of the template <DFN>layer_name</DFN> is string name of the added layer.
445          *   If this part is empty then the network input pseudo layer will be used;
446          * - the second optional part of the template <DFN>input_number</DFN>
447          *   is either number of the layer input, either label one.
448          *   If this part is omitted then the first layer input will be used.
449          *
450          *  @see setNetInputs(), Layer::inputNameToIndex(), Layer::outputNameToIndex()
451          */
452         CV_WRAP void connect(String outPin, String inpPin);
453
454         /** @brief Connects #@p outNum output of the first layer to #@p inNum input of the second layer.
455          *  @param outLayerId identifier of the first layer
456          *  @param outNum number of the first layer output
457          *  @param inpLayerId identifier of the second layer
458          *  @param inpNum number of the second layer input
459          */
460         void connect(int outLayerId, int outNum, int inpLayerId, int inpNum);
461
462         /** @brief Sets outputs names of the network input pseudo layer.
463          *
464          * Each net always has special own the network input pseudo layer with id=0.
465          * This layer stores the user blobs only and don't make any computations.
466          * In fact, this layer provides the only way to pass user data into the network.
467          * As any other layer, this layer can label its outputs and this function provides an easy way to do this.
468          */
469         CV_WRAP void setInputsNames(const std::vector<String> &inputBlobNames);
470
471         /** @brief Runs forward pass to compute output of layer with name @p outputName.
472          *  @param outputName name for layer which output is needed to get
473          *  @return blob for first output of specified layer.
474          *  @details By default runs forward pass for the whole network.
475          */
476         CV_WRAP Mat forward(const String& outputName = String());
477
478         /** @brief Runs forward pass to compute output of layer with name @p outputName.
479          *  @param outputName name for layer which output is needed to get
480          *  @details By default runs forward pass for the whole network.
481          *
482          *  This is an asynchronous version of forward(const String&).
483          *  dnn::DNN_BACKEND_INFERENCE_ENGINE backend is required.
484          */
485         CV_WRAP AsyncArray forwardAsync(const String& outputName = String());
486
487         /** @brief Runs forward pass to compute output of layer with name @p outputName.
488          *  @param outputBlobs contains all output blobs for specified layer.
489          *  @param outputName name for layer which output is needed to get
490          *  @details If @p outputName is empty, runs forward pass for the whole network.
491          */
492         CV_WRAP void forward(OutputArrayOfArrays outputBlobs, const String& outputName = String());
493
494         /** @brief Runs forward pass to compute outputs of layers listed in @p outBlobNames.
495          *  @param outputBlobs contains blobs for first outputs of specified layers.
496          *  @param outBlobNames names for layers which outputs are needed to get
497          */
498         CV_WRAP void forward(OutputArrayOfArrays outputBlobs,
499                              const std::vector<String>& outBlobNames);
500
501         /** @brief Runs forward pass to compute outputs of layers listed in @p outBlobNames.
502          *  @param outputBlobs contains all output blobs for each layer specified in @p outBlobNames.
503          *  @param outBlobNames names for layers which outputs are needed to get
504          */
505         CV_WRAP_AS(forwardAndRetrieve) void forward(CV_OUT std::vector<std::vector<Mat> >& outputBlobs,
506                                                     const std::vector<String>& outBlobNames);
507
508         /**
509          * @brief Compile Halide layers.
510          * @param[in] scheduler Path to YAML file with scheduling directives.
511          * @see setPreferableBackend
512          *
513          * Schedule layers that support Halide backend. Then compile them for
514          * specific target. For layers that not represented in scheduling file
515          * or if no manual scheduling used at all, automatic scheduling will be applied.
516          */
517         CV_WRAP void setHalideScheduler(const String& scheduler);
518
519         /**
520          * @brief Ask network to use specific computation backend where it supported.
521          * @param[in] backendId backend identifier.
522          * @see Backend
523          *
524          * If OpenCV is compiled with Intel's Inference Engine library, DNN_BACKEND_DEFAULT
525          * means DNN_BACKEND_INFERENCE_ENGINE. Otherwise it equals to DNN_BACKEND_OPENCV.
526          */
527         CV_WRAP void setPreferableBackend(int backendId);
528
529         /**
530          * @brief Ask network to make computations on specific target device.
531          * @param[in] targetId target identifier.
532          * @see Target
533          *
534          * List of supported combinations backend / target:
535          * |                        | DNN_BACKEND_OPENCV | DNN_BACKEND_INFERENCE_ENGINE | DNN_BACKEND_HALIDE |  DNN_BACKEND_CUDA |
536          * |------------------------|--------------------|------------------------------|--------------------|-------------------|
537          * | DNN_TARGET_CPU         |                  + |                            + |                  + |                   |
538          * | DNN_TARGET_OPENCL      |                  + |                            + |                  + |                   |
539          * | DNN_TARGET_OPENCL_FP16 |                  + |                            + |                    |                   |
540          * | DNN_TARGET_MYRIAD      |                    |                            + |                    |                   |
541          * | DNN_TARGET_FPGA        |                    |                            + |                    |                   |
542          * | DNN_TARGET_CUDA        |                    |                              |                    |                 + |
543          * | DNN_TARGET_CUDA_FP16   |                    |                              |                    |                 + |
544          */
545         CV_WRAP void setPreferableTarget(int targetId);
546
547         /** @brief Sets the new input value for the network
548          *  @param blob        A new blob. Should have CV_32F or CV_8U depth.
549          *  @param name        A name of input layer.
550          *  @param scalefactor An optional normalization scale.
551          *  @param mean        An optional mean subtraction values.
552          *  @see connect(String, String) to know format of the descriptor.
553          *
554          *  If scale or mean values are specified, a final input blob is computed
555          *  as:
556          * \f[input(n,c,h,w) = scalefactor \times (blob(n,c,h,w) - mean_c)\f]
557          */
558         CV_WRAP void setInput(InputArray blob, const String& name = "",
559                               double scalefactor = 1.0, const Scalar& mean = Scalar());
560
561         /** @brief Sets the new value for the learned param of the layer.
562          *  @param layer name or id of the layer.
563          *  @param numParam index of the layer parameter in the Layer::blobs array.
564          *  @param blob the new value.
565          *  @see Layer::blobs
566          *  @note If shape of the new blob differs from the previous shape,
567          *  then the following forward pass may fail.
568         */
569         CV_WRAP void setParam(LayerId layer, int numParam, const Mat &blob);
570
571         /** @brief Returns parameter blob of the layer.
572          *  @param layer name or id of the layer.
573          *  @param numParam index of the layer parameter in the Layer::blobs array.
574          *  @see Layer::blobs
575          */
576         CV_WRAP Mat getParam(LayerId layer, int numParam = 0);
577
578         /** @brief Returns indexes of layers with unconnected outputs.
579          */
580         CV_WRAP std::vector<int> getUnconnectedOutLayers() const;
581
582         /** @brief Returns names of layers with unconnected outputs.
583          */
584         CV_WRAP std::vector<String> getUnconnectedOutLayersNames() const;
585
586         /** @brief Returns input and output shapes for all layers in loaded model;
587          *  preliminary inferencing isn't necessary.
588          *  @param netInputShapes shapes for all input blobs in net input layer.
589          *  @param layersIds output parameter for layer IDs.
590          *  @param inLayersShapes output parameter for input layers shapes;
591          * order is the same as in layersIds
592          *  @param outLayersShapes output parameter for output layers shapes;
593          * order is the same as in layersIds
594          */
595         CV_WRAP void getLayersShapes(const std::vector<MatShape>& netInputShapes,
596                                      CV_OUT std::vector<int>& layersIds,
597                                      CV_OUT std::vector<std::vector<MatShape> >& inLayersShapes,
598                                      CV_OUT std::vector<std::vector<MatShape> >& outLayersShapes) const;
599
600         /** @overload */
601         CV_WRAP void getLayersShapes(const MatShape& netInputShape,
602                                      CV_OUT std::vector<int>& layersIds,
603                                      CV_OUT std::vector<std::vector<MatShape> >& inLayersShapes,
604                                      CV_OUT std::vector<std::vector<MatShape> >& outLayersShapes) const;
605
606         /** @brief Returns input and output shapes for layer with specified
607          * id in loaded model; preliminary inferencing isn't necessary.
608          *  @param netInputShape shape input blob in net input layer.
609          *  @param layerId id for layer.
610          *  @param inLayerShapes output parameter for input layers shapes;
611          * order is the same as in layersIds
612          *  @param outLayerShapes output parameter for output layers shapes;
613          * order is the same as in layersIds
614          */
615         void getLayerShapes(const MatShape& netInputShape,
616                                     const int layerId,
617                                     CV_OUT std::vector<MatShape>& inLayerShapes,
618                                     CV_OUT std::vector<MatShape>& outLayerShapes) const; // FIXIT: CV_WRAP
619
620         /** @overload */
621         void getLayerShapes(const std::vector<MatShape>& netInputShapes,
622                                     const int layerId,
623                                     CV_OUT std::vector<MatShape>& inLayerShapes,
624                                     CV_OUT std::vector<MatShape>& outLayerShapes) const; // FIXIT: CV_WRAP
625
626         /** @brief Computes FLOP for whole loaded model with specified input shapes.
627          * @param netInputShapes vector of shapes for all net inputs.
628          * @returns computed FLOP.
629          */
630         CV_WRAP int64 getFLOPS(const std::vector<MatShape>& netInputShapes) const;
631         /** @overload */
632         CV_WRAP int64 getFLOPS(const MatShape& netInputShape) const;
633         /** @overload */
634         CV_WRAP int64 getFLOPS(const int layerId,
635                                const std::vector<MatShape>& netInputShapes) const;
636         /** @overload */
637         CV_WRAP int64 getFLOPS(const int layerId,
638                                const MatShape& netInputShape) const;
639
640         /** @brief Returns list of types for layer used in model.
641          * @param layersTypes output parameter for returning types.
642          */
643         CV_WRAP void getLayerTypes(CV_OUT std::vector<String>& layersTypes) const;
644
645         /** @brief Returns count of layers of specified type.
646          * @param layerType type.
647          * @returns count of layers
648          */
649         CV_WRAP int getLayersCount(const String& layerType) const;
650
651         /** @brief Computes bytes number which are required to store
652          * all weights and intermediate blobs for model.
653          * @param netInputShapes vector of shapes for all net inputs.
654          * @param weights output parameter to store resulting bytes for weights.
655          * @param blobs output parameter to store resulting bytes for intermediate blobs.
656          */
657         void getMemoryConsumption(const std::vector<MatShape>& netInputShapes,
658                                           CV_OUT size_t& weights, CV_OUT size_t& blobs) const; // FIXIT: CV_WRAP
659         /** @overload */
660         CV_WRAP void getMemoryConsumption(const MatShape& netInputShape,
661                                           CV_OUT size_t& weights, CV_OUT size_t& blobs) const;
662         /** @overload */
663         CV_WRAP void getMemoryConsumption(const int layerId,
664                                           const std::vector<MatShape>& netInputShapes,
665                                           CV_OUT size_t& weights, CV_OUT size_t& blobs) const;
666         /** @overload */
667         CV_WRAP void getMemoryConsumption(const int layerId,
668                                           const MatShape& netInputShape,
669                                           CV_OUT size_t& weights, CV_OUT size_t& blobs) const;
670
671         /** @brief Computes bytes number which are required to store
672          * all weights and intermediate blobs for each layer.
673          * @param netInputShapes vector of shapes for all net inputs.
674          * @param layerIds output vector to save layer IDs.
675          * @param weights output parameter to store resulting bytes for weights.
676          * @param blobs output parameter to store resulting bytes for intermediate blobs.
677          */
678         void getMemoryConsumption(const std::vector<MatShape>& netInputShapes,
679                                           CV_OUT std::vector<int>& layerIds,
680                                           CV_OUT std::vector<size_t>& weights,
681                                           CV_OUT std::vector<size_t>& blobs) const; // FIXIT: CV_WRAP
682         /** @overload */
683         void getMemoryConsumption(const MatShape& netInputShape,
684                                           CV_OUT std::vector<int>& layerIds,
685                                           CV_OUT std::vector<size_t>& weights,
686                                           CV_OUT std::vector<size_t>& blobs) const; // FIXIT: CV_WRAP
687
688         /** @brief Enables or disables layer fusion in the network.
689          * @param fusion true to enable the fusion, false to disable. The fusion is enabled by default.
690          */
691         CV_WRAP void enableFusion(bool fusion);
692
693         /** @brief Returns overall time for inference and timings (in ticks) for layers.
694          * Indexes in returned vector correspond to layers ids. Some layers can be fused with others,
695          * in this case zero ticks count will be return for that skipped layers.
696          * @param timings vector for tick timings for all layers.
697          * @return overall ticks for model inference.
698          */
699         CV_WRAP int64 getPerfProfile(CV_OUT std::vector<double>& timings);
700
701     private:
702         struct Impl;
703         Ptr<Impl> impl;
704     };
705
706     /** @brief Reads a network model stored in <a href="https://pjreddie.com/darknet/">Darknet</a> model files.
707     *  @param cfgFile      path to the .cfg file with text description of the network architecture.
708     *  @param darknetModel path to the .weights file with learned network.
709     *  @returns Network object that ready to do forward, throw an exception in failure cases.
710     *  @returns Net object.
711     */
712     CV_EXPORTS_W Net readNetFromDarknet(const String &cfgFile, const String &darknetModel = String());
713
714     /** @brief Reads a network model stored in <a href="https://pjreddie.com/darknet/">Darknet</a> model files.
715      *  @param bufferCfg   A buffer contains a content of .cfg file with text description of the network architecture.
716      *  @param bufferModel A buffer contains a content of .weights file with learned network.
717      *  @returns Net object.
718      */
719     CV_EXPORTS_W Net readNetFromDarknet(const std::vector<uchar>& bufferCfg,
720                                         const std::vector<uchar>& bufferModel = std::vector<uchar>());
721
722     /** @brief Reads a network model stored in <a href="https://pjreddie.com/darknet/">Darknet</a> model files.
723      *  @param bufferCfg   A buffer contains a content of .cfg file with text description of the network architecture.
724      *  @param lenCfg      Number of bytes to read from bufferCfg
725      *  @param bufferModel A buffer contains a content of .weights file with learned network.
726      *  @param lenModel    Number of bytes to read from bufferModel
727      *  @returns Net object.
728      */
729     CV_EXPORTS Net readNetFromDarknet(const char *bufferCfg, size_t lenCfg,
730                                       const char *bufferModel = NULL, size_t lenModel = 0);
731
732     /** @brief Reads a network model stored in <a href="http://caffe.berkeleyvision.org">Caffe</a> framework's format.
733       * @param prototxt   path to the .prototxt file with text description of the network architecture.
734       * @param caffeModel path to the .caffemodel file with learned network.
735       * @returns Net object.
736       */
737     CV_EXPORTS_W Net readNetFromCaffe(const String &prototxt, const String &caffeModel = String());
738
739     /** @brief Reads a network model stored in Caffe model in memory.
740       * @param bufferProto buffer containing the content of the .prototxt file
741       * @param bufferModel buffer containing the content of the .caffemodel file
742       * @returns Net object.
743       */
744     CV_EXPORTS_W Net readNetFromCaffe(const std::vector<uchar>& bufferProto,
745                                       const std::vector<uchar>& bufferModel = std::vector<uchar>());
746
747     /** @brief Reads a network model stored in Caffe model in memory.
748       * @details This is an overloaded member function, provided for convenience.
749       * It differs from the above function only in what argument(s) it accepts.
750       * @param bufferProto buffer containing the content of the .prototxt file
751       * @param lenProto length of bufferProto
752       * @param bufferModel buffer containing the content of the .caffemodel file
753       * @param lenModel length of bufferModel
754       * @returns Net object.
755       */
756     CV_EXPORTS Net readNetFromCaffe(const char *bufferProto, size_t lenProto,
757                                     const char *bufferModel = NULL, size_t lenModel = 0);
758
759     /** @brief Reads a network model stored in <a href="https://www.tensorflow.org/">TensorFlow</a> framework's format.
760       * @param model  path to the .pb file with binary protobuf description of the network architecture
761       * @param config path to the .pbtxt file that contains text graph definition in protobuf format.
762       *               Resulting Net object is built by text graph using weights from a binary one that
763       *               let us make it more flexible.
764       * @returns Net object.
765       */
766     CV_EXPORTS_W Net readNetFromTensorflow(const String &model, const String &config = String());
767
768     /** @brief Reads a network model stored in <a href="https://www.tensorflow.org/">TensorFlow</a> framework's format.
769       * @param bufferModel buffer containing the content of the pb file
770       * @param bufferConfig buffer containing the content of the pbtxt file
771       * @returns Net object.
772       */
773     CV_EXPORTS_W Net readNetFromTensorflow(const std::vector<uchar>& bufferModel,
774                                            const std::vector<uchar>& bufferConfig = std::vector<uchar>());
775
776     /** @brief Reads a network model stored in <a href="https://www.tensorflow.org/">TensorFlow</a> framework's format.
777       * @details This is an overloaded member function, provided for convenience.
778       * It differs from the above function only in what argument(s) it accepts.
779       * @param bufferModel buffer containing the content of the pb file
780       * @param lenModel length of bufferModel
781       * @param bufferConfig buffer containing the content of the pbtxt file
782       * @param lenConfig length of bufferConfig
783       */
784     CV_EXPORTS Net readNetFromTensorflow(const char *bufferModel, size_t lenModel,
785                                          const char *bufferConfig = NULL, size_t lenConfig = 0);
786
787     /**
788      *  @brief Reads a network model stored in <a href="http://torch.ch">Torch7</a> framework's format.
789      *  @param model    path to the file, dumped from Torch by using torch.save() function.
790      *  @param isBinary specifies whether the network was serialized in ascii mode or binary.
791      *  @param evaluate specifies testing phase of network. If true, it's similar to evaluate() method in Torch.
792      *  @returns Net object.
793      *
794      *  @note Ascii mode of Torch serializer is more preferable, because binary mode extensively use `long` type of C language,
795      *  which has various bit-length on different systems.
796      *
797      * The loading file must contain serialized <a href="https://github.com/torch/nn/blob/master/doc/module.md">nn.Module</a> object
798      * with importing network. Try to eliminate a custom objects from serialazing data to avoid importing errors.
799      *
800      * List of supported layers (i.e. object instances derived from Torch nn.Module class):
801      * - nn.Sequential
802      * - nn.Parallel
803      * - nn.Concat
804      * - nn.Linear
805      * - nn.SpatialConvolution
806      * - nn.SpatialMaxPooling, nn.SpatialAveragePooling
807      * - nn.ReLU, nn.TanH, nn.Sigmoid
808      * - nn.Reshape
809      * - nn.SoftMax, nn.LogSoftMax
810      *
811      * Also some equivalents of these classes from cunn, cudnn, and fbcunn may be successfully imported.
812      */
813      CV_EXPORTS_W Net readNetFromTorch(const String &model, bool isBinary = true, bool evaluate = true);
814
815      /**
816       * @brief Read deep learning network represented in one of the supported formats.
817       * @param[in] model Binary file contains trained weights. The following file
818       *                  extensions are expected for models from different frameworks:
819       *                  * `*.caffemodel` (Caffe, http://caffe.berkeleyvision.org/)
820       *                  * `*.pb` (TensorFlow, https://www.tensorflow.org/)
821       *                  * `*.t7` | `*.net` (Torch, http://torch.ch/)
822       *                  * `*.weights` (Darknet, https://pjreddie.com/darknet/)
823       *                  * `*.bin` (DLDT, https://software.intel.com/openvino-toolkit)
824       *                  * `*.onnx` (ONNX, https://onnx.ai/)
825       * @param[in] config Text file contains network configuration. It could be a
826       *                   file with the following extensions:
827       *                  * `*.prototxt` (Caffe, http://caffe.berkeleyvision.org/)
828       *                  * `*.pbtxt` (TensorFlow, https://www.tensorflow.org/)
829       *                  * `*.cfg` (Darknet, https://pjreddie.com/darknet/)
830       *                  * `*.xml` (DLDT, https://software.intel.com/openvino-toolkit)
831       * @param[in] framework Explicit framework name tag to determine a format.
832       * @returns Net object.
833       *
834       * This function automatically detects an origin framework of trained model
835       * and calls an appropriate function such @ref readNetFromCaffe, @ref readNetFromTensorflow,
836       * @ref readNetFromTorch or @ref readNetFromDarknet. An order of @p model and @p config
837       * arguments does not matter.
838       */
839      CV_EXPORTS_W Net readNet(const String& model, const String& config = "", const String& framework = "");
840
841      /**
842       * @brief Read deep learning network represented in one of the supported formats.
843       * @details This is an overloaded member function, provided for convenience.
844       *          It differs from the above function only in what argument(s) it accepts.
845       * @param[in] framework    Name of origin framework.
846       * @param[in] bufferModel  A buffer with a content of binary file with weights
847       * @param[in] bufferConfig A buffer with a content of text file contains network configuration.
848       * @returns Net object.
849       */
850      CV_EXPORTS_W Net readNet(const String& framework, const std::vector<uchar>& bufferModel,
851                               const std::vector<uchar>& bufferConfig = std::vector<uchar>());
852
853     /** @brief Loads blob which was serialized as torch.Tensor object of Torch7 framework.
854      *  @warning This function has the same limitations as readNetFromTorch().
855      */
856     CV_EXPORTS_W Mat readTorchBlob(const String &filename, bool isBinary = true);
857
858     /** @brief Load a network from Intel's Model Optimizer intermediate representation.
859      *  @param[in] xml XML configuration file with network's topology.
860      *  @param[in] bin Binary file with trained weights.
861      *  @returns Net object.
862      *  Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine
863      *  backend.
864      */
865     CV_EXPORTS_W Net readNetFromModelOptimizer(const String &xml, const String &bin);
866
867     /** @brief Reads a network model <a href="https://onnx.ai/">ONNX</a>.
868      *  @param onnxFile path to the .onnx file with text description of the network architecture.
869      *  @returns Network object that ready to do forward, throw an exception in failure cases.
870      */
871     CV_EXPORTS_W Net readNetFromONNX(const String &onnxFile);
872
873     /** @brief Reads a network model from <a href="https://onnx.ai/">ONNX</a>
874      *         in-memory buffer.
875      *  @param buffer memory address of the first byte of the buffer.
876      *  @param sizeBuffer size of the buffer.
877      *  @returns Network object that ready to do forward, throw an exception
878      *        in failure cases.
879      */
880     CV_EXPORTS Net readNetFromONNX(const char* buffer, size_t sizeBuffer);
881
882     /** @brief Reads a network model from <a href="https://onnx.ai/">ONNX</a>
883      *         in-memory buffer.
884      *  @param buffer in-memory buffer that stores the ONNX model bytes.
885      *  @returns Network object that ready to do forward, throw an exception
886      *        in failure cases.
887      */
888     CV_EXPORTS_W Net readNetFromONNX(const std::vector<uchar>& buffer);
889
890     /** @brief Creates blob from .pb file.
891      *  @param path to the .pb file with input tensor.
892      *  @returns Mat.
893      */
894     CV_EXPORTS_W Mat readTensorFromONNX(const String& path);
895
896     /** @brief Creates 4-dimensional blob from image. Optionally resizes and crops @p image from center,
897      *  subtract @p mean values, scales values by @p scalefactor, swap Blue and Red channels.
898      *  @param image input image (with 1-, 3- or 4-channels).
899      *  @param size spatial size for output image
900      *  @param mean scalar with mean values which are subtracted from channels. Values are intended
901      *  to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true.
902      *  @param scalefactor multiplier for @p image values.
903      *  @param swapRB flag which indicates that swap first and last channels
904      *  in 3-channel image is necessary.
905      *  @param crop flag which indicates whether image will be cropped after resize or not
906      *  @param ddepth Depth of output blob. Choose CV_32F or CV_8U.
907      *  @details if @p crop is true, input image is resized so one side after resize is equal to corresponding
908      *  dimension in @p size and another one is equal or larger. Then, crop from the center is performed.
909      *  If @p crop is false, direct resize without cropping and preserving aspect ratio is performed.
910      *  @returns 4-dimensional Mat with NCHW dimensions order.
911      */
912     CV_EXPORTS_W Mat blobFromImage(InputArray image, double scalefactor=1.0, const Size& size = Size(),
913                                    const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false,
914                                    int ddepth=CV_32F);
915
916     /** @brief Creates 4-dimensional blob from image.
917      *  @details This is an overloaded member function, provided for convenience.
918      *           It differs from the above function only in what argument(s) it accepts.
919      */
920     CV_EXPORTS void blobFromImage(InputArray image, OutputArray blob, double scalefactor=1.0,
921                                   const Size& size = Size(), const Scalar& mean = Scalar(),
922                                   bool swapRB=false, bool crop=false, int ddepth=CV_32F);
923
924
925     /** @brief Creates 4-dimensional blob from series of images. Optionally resizes and
926      *  crops @p images from center, subtract @p mean values, scales values by @p scalefactor,
927      *  swap Blue and Red channels.
928      *  @param images input images (all with 1-, 3- or 4-channels).
929      *  @param size spatial size for output image
930      *  @param mean scalar with mean values which are subtracted from channels. Values are intended
931      *  to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true.
932      *  @param scalefactor multiplier for @p images values.
933      *  @param swapRB flag which indicates that swap first and last channels
934      *  in 3-channel image is necessary.
935      *  @param crop flag which indicates whether image will be cropped after resize or not
936      *  @param ddepth Depth of output blob. Choose CV_32F or CV_8U.
937      *  @details if @p crop is true, input image is resized so one side after resize is equal to corresponding
938      *  dimension in @p size and another one is equal or larger. Then, crop from the center is performed.
939      *  If @p crop is false, direct resize without cropping and preserving aspect ratio is performed.
940      *  @returns 4-dimensional Mat with NCHW dimensions order.
941      */
942     CV_EXPORTS_W Mat blobFromImages(InputArrayOfArrays images, double scalefactor=1.0,
943                                     Size size = Size(), const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false,
944                                     int ddepth=CV_32F);
945
946     /** @brief Creates 4-dimensional blob from series of images.
947      *  @details This is an overloaded member function, provided for convenience.
948      *           It differs from the above function only in what argument(s) it accepts.
949      */
950     CV_EXPORTS void blobFromImages(InputArrayOfArrays images, OutputArray blob,
951                                    double scalefactor=1.0, Size size = Size(),
952                                    const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false,
953                                    int ddepth=CV_32F);
954
955     /** @brief Parse a 4D blob and output the images it contains as 2D arrays through a simpler data structure
956      *  (std::vector<cv::Mat>).
957      *  @param[in] blob_ 4 dimensional array (images, channels, height, width) in floating point precision (CV_32F) from
958      *  which you would like to extract the images.
959      *  @param[out] images_ array of 2D Mat containing the images extracted from the blob in floating point precision
960      *  (CV_32F). They are non normalized neither mean added. The number of returned images equals the first dimension
961      *  of the blob (batch size). Every image has a number of channels equals to the second dimension of the blob (depth).
962      */
963     CV_EXPORTS_W void imagesFromBlob(const cv::Mat& blob_, OutputArrayOfArrays images_);
964
965     /** @brief Convert all weights of Caffe network to half precision floating point.
966      * @param src Path to origin model from Caffe framework contains single
967      *            precision floating point weights (usually has `.caffemodel` extension).
968      * @param dst Path to destination model with updated weights.
969      * @param layersTypes Set of layers types which parameters will be converted.
970      *                    By default, converts only Convolutional and Fully-Connected layers'
971      *                    weights.
972      *
973      * @note Shrinked model has no origin float32 weights so it can't be used
974      *       in origin Caffe framework anymore. However the structure of data
975      *       is taken from NVidia's Caffe fork: https://github.com/NVIDIA/caffe.
976      *       So the resulting model may be used there.
977      */
978     CV_EXPORTS_W void shrinkCaffeModel(const String& src, const String& dst,
979                                        const std::vector<String>& layersTypes = std::vector<String>());
980
981     /** @brief Create a text representation for a binary network stored in protocol buffer format.
982      *  @param[in] model  A path to binary network.
983      *  @param[in] output A path to output text file to be created.
984      *
985      *  @note To reduce output file size, trained weights are not included.
986      */
987     CV_EXPORTS_W void writeTextGraph(const String& model, const String& output);
988
989     /** @brief Performs non maximum suppression given boxes and corresponding scores.
990
991      * @param bboxes a set of bounding boxes to apply NMS.
992      * @param scores a set of corresponding confidences.
993      * @param score_threshold a threshold used to filter boxes by score.
994      * @param nms_threshold a threshold used in non maximum suppression.
995      * @param indices the kept indices of bboxes after NMS.
996      * @param eta a coefficient in adaptive threshold formula: \f$nms\_threshold_{i+1}=eta\cdot nms\_threshold_i\f$.
997      * @param top_k if `>0`, keep at most @p top_k picked indices.
998      */
999     CV_EXPORTS_W void NMSBoxes(const std::vector<Rect>& bboxes, const std::vector<float>& scores,
1000                                const float score_threshold, const float nms_threshold,
1001                                CV_OUT std::vector<int>& indices,
1002                                const float eta = 1.f, const int top_k = 0);
1003
1004     CV_EXPORTS_W void NMSBoxes(const std::vector<Rect2d>& bboxes, const std::vector<float>& scores,
1005                                const float score_threshold, const float nms_threshold,
1006                                CV_OUT std::vector<int>& indices,
1007                                const float eta = 1.f, const int top_k = 0);
1008
1009     CV_EXPORTS_AS(NMSBoxesRotated) void NMSBoxes(const std::vector<RotatedRect>& bboxes, const std::vector<float>& scores,
1010                              const float score_threshold, const float nms_threshold,
1011                              CV_OUT std::vector<int>& indices,
1012                              const float eta = 1.f, const int top_k = 0);
1013
1014
1015      /** @brief This class is presented high-level API for neural networks.
1016       *
1017       * Model allows to set params for preprocessing input image.
1018       * Model creates net from file with trained weights and config,
1019       * sets preprocessing input and runs forward pass.
1020       */
1021      class CV_EXPORTS_W_SIMPLE Model : public Net
1022      {
1023      public:
1024          /**
1025           * @brief Default constructor.
1026           */
1027          Model();
1028
1029          /**
1030           * @brief Create model from deep learning network represented in one of the supported formats.
1031           * An order of @p model and @p config arguments does not matter.
1032           * @param[in] model Binary file contains trained weights.
1033           * @param[in] config Text file contains network configuration.
1034           */
1035          CV_WRAP Model(const String& model, const String& config = "");
1036
1037          /**
1038           * @brief Create model from deep learning network.
1039           * @param[in] network Net object.
1040           */
1041          CV_WRAP Model(const Net& network);
1042
1043          /** @brief Set input size for frame.
1044           *  @param[in] size New input size.
1045           *  @note If shape of the new blob less than 0, then frame size not change.
1046          */
1047          CV_WRAP Model& setInputSize(const Size& size);
1048
1049          /** @brief Set input size for frame.
1050          *  @param[in] width New input width.
1051          *  @param[in] height New input height.
1052          *  @note If shape of the new blob less than 0,
1053          *  then frame size not change.
1054          */
1055          CV_WRAP Model& setInputSize(int width, int height);
1056
1057          /** @brief Set mean value for frame.
1058           *  @param[in] mean Scalar with mean values which are subtracted from channels.
1059          */
1060          CV_WRAP Model& setInputMean(const Scalar& mean);
1061
1062          /** @brief Set scalefactor value for frame.
1063           *  @param[in] scale Multiplier for frame values.
1064          */
1065          CV_WRAP Model& setInputScale(double scale);
1066
1067          /** @brief Set flag crop for frame.
1068           *  @param[in] crop Flag which indicates whether image will be cropped after resize or not.
1069          */
1070          CV_WRAP Model& setInputCrop(bool crop);
1071
1072          /** @brief Set flag swapRB for frame.
1073           *  @param[in] swapRB Flag which indicates that swap first and last channels.
1074          */
1075          CV_WRAP Model& setInputSwapRB(bool swapRB);
1076
1077          /** @brief Set preprocessing parameters for frame.
1078          *  @param[in] size New input size.
1079          *  @param[in] mean Scalar with mean values which are subtracted from channels.
1080          *  @param[in] scale Multiplier for frame values.
1081          *  @param[in] swapRB Flag which indicates that swap first and last channels.
1082          *  @param[in] crop Flag which indicates whether image will be cropped after resize or not.
1083          *  blob(n, c, y, x) = scale * resize( frame(y, x, c) ) - mean(c) )
1084          */
1085          CV_WRAP void setInputParams(double scale = 1.0, const Size& size = Size(),
1086                                      const Scalar& mean = Scalar(), bool swapRB = false, bool crop = false);
1087
1088          /** @brief Given the @p input frame, create input blob, run net and return the output @p blobs.
1089           *  @param[in]  frame  The input image.
1090           *  @param[out] outs Allocated output blobs, which will store results of the computation.
1091           */
1092          CV_WRAP void predict(InputArray frame, OutputArrayOfArrays outs);
1093
1094      protected:
1095          struct Impl;
1096          Ptr<Impl> impl;
1097      };
1098
1099      /** @brief This class represents high-level API for classification models.
1100       *
1101       * ClassificationModel allows to set params for preprocessing input image.
1102       * ClassificationModel creates net from file with trained weights and config,
1103       * sets preprocessing input, runs forward pass and return top-1 prediction.
1104       */
1105      class CV_EXPORTS_W_SIMPLE ClassificationModel : public Model
1106      {
1107      public:
1108          /**
1109           * @brief Create classification model from network represented in one of the supported formats.
1110           * An order of @p model and @p config arguments does not matter.
1111           * @param[in] model Binary file contains trained weights.
1112           * @param[in] config Text file contains network configuration.
1113           */
1114           CV_WRAP ClassificationModel(const String& model, const String& config = "");
1115
1116          /**
1117           * @brief Create model from deep learning network.
1118           * @param[in] network Net object.
1119           */
1120          CV_WRAP ClassificationModel(const Net& network);
1121
1122          /** @brief Given the @p input frame, create input blob, run net and return top-1 prediction.
1123           *  @param[in]  frame  The input image.
1124           */
1125          std::pair<int, float> classify(InputArray frame);
1126
1127          /** @overload */
1128          CV_WRAP void classify(InputArray frame, CV_OUT int& classId, CV_OUT float& conf);
1129      };
1130
1131      /** @brief This class represents high-level API for segmentation  models
1132       *
1133       * SegmentationModel allows to set params for preprocessing input image.
1134       * SegmentationModel creates net from file with trained weights and config,
1135       * sets preprocessing input, runs forward pass and returns the class prediction for each pixel.
1136       */
1137      class CV_EXPORTS_W SegmentationModel: public Model
1138      {
1139      public:
1140          /**
1141           * @brief Create segmentation model from network represented in one of the supported formats.
1142           * An order of @p model and @p config arguments does not matter.
1143           * @param[in] model Binary file contains trained weights.
1144           * @param[in] config Text file contains network configuration.
1145           */
1146           CV_WRAP SegmentationModel(const String& model, const String& config = "");
1147
1148          /**
1149           * @brief Create model from deep learning network.
1150           * @param[in] network Net object.
1151           */
1152          CV_WRAP SegmentationModel(const Net& network);
1153
1154          /** @brief Given the @p input frame, create input blob, run net
1155           *  @param[in]  frame  The input image.
1156           *  @param[out] mask Allocated class prediction for each pixel
1157           */
1158          CV_WRAP void segment(InputArray frame, OutputArray mask);
1159      };
1160
1161      /** @brief This class represents high-level API for object detection networks.
1162       *
1163       * DetectionModel allows to set params for preprocessing input image.
1164       * DetectionModel creates net from file with trained weights and config,
1165       * sets preprocessing input, runs forward pass and return result detections.
1166       * For DetectionModel SSD, Faster R-CNN, YOLO topologies are supported.
1167       */
1168      class CV_EXPORTS_W_SIMPLE DetectionModel : public Model
1169      {
1170      public:
1171          /**
1172           * @brief Create detection model from network represented in one of the supported formats.
1173           * An order of @p model and @p config arguments does not matter.
1174           * @param[in] model Binary file contains trained weights.
1175           * @param[in] config Text file contains network configuration.
1176           */
1177          CV_WRAP DetectionModel(const String& model, const String& config = "");
1178
1179          /**
1180           * @brief Create model from deep learning network.
1181           * @param[in] network Net object.
1182           */
1183          CV_WRAP DetectionModel(const Net& network);
1184
1185          /** @brief Given the @p input frame, create input blob, run net and return result detections.
1186           *  @param[in]  frame  The input image.
1187           *  @param[out] classIds Class indexes in result detection.
1188           *  @param[out] confidences A set of corresponding confidences.
1189           *  @param[out] boxes A set of bounding boxes.
1190           *  @param[in] confThreshold A threshold used to filter boxes by confidences.
1191           *  @param[in] nmsThreshold A threshold used in non maximum suppression.
1192           */
1193          CV_WRAP void detect(InputArray frame, CV_OUT std::vector<int>& classIds,
1194                              CV_OUT std::vector<float>& confidences, CV_OUT std::vector<Rect>& boxes,
1195                              float confThreshold = 0.5f, float nmsThreshold = 0.0f);
1196      };
1197
1198 //! @}
1199 CV__DNN_INLINE_NS_END
1200 }
1201 }
1202
1203 #include <opencv2/dnn/layer.hpp>
1204 #include <opencv2/dnn/dnn.inl.hpp>
1205
1206 /// @deprecated Include this header directly from application. Automatic inclusion will be removed
1207 #include <opencv2/dnn/utils/inference_engine.hpp>
1208
1209 #endif  /* OPENCV_DNN_DNN_HPP */