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