a0eca0a2526462dddcf9da965fac2e9799b1827f
[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
48 #if !defined CV_DOXYGEN && !defined CV_DNN_DONT_ADD_EXPERIMENTAL_NS
49 #define CV__DNN_EXPERIMENTAL_NS_BEGIN namespace experimental_dnn_v3 {
50 #define CV__DNN_EXPERIMENTAL_NS_END }
51 namespace cv { namespace dnn { namespace experimental_dnn_v3 { } using namespace experimental_dnn_v3; }}
52 #else
53 #define CV__DNN_EXPERIMENTAL_NS_BEGIN
54 #define CV__DNN_EXPERIMENTAL_NS_END
55 #endif
56
57 #include <opencv2/dnn/dict.hpp>
58
59 namespace cv {
60 namespace dnn {
61 CV__DNN_EXPERIMENTAL_NS_BEGIN
62 //! @addtogroup dnn
63 //! @{
64
65     typedef std::vector<int> MatShape;
66
67     /**
68      * @brief Enum of computation backends supported by layers.
69      */
70     enum Backend
71     {
72         DNN_BACKEND_DEFAULT,
73         DNN_BACKEND_HALIDE
74     };
75
76     /**
77      * @brief Enum of target devices for computations.
78      */
79     enum Target
80     {
81         DNN_TARGET_CPU,
82         DNN_TARGET_OPENCL
83     };
84
85     /** @brief This class provides all data needed to initialize layer.
86      *
87      * It includes dictionary with scalar params (which can be readed by using Dict interface),
88      * blob params #blobs and optional meta information: #name and #type of layer instance.
89     */
90     class CV_EXPORTS LayerParams : public Dict
91     {
92     public:
93         //TODO: Add ability to name blob params
94         std::vector<Mat> blobs; //!< List of learned parameters stored as blobs.
95
96         String name; //!< Name of the layer instance (optional, can be used internal purposes).
97         String type; //!< Type name which was used for creating layer by layer factory (optional).
98     };
99
100    /**
101     * @brief Derivatives of this class encapsulates functions of certain backends.
102     */
103     class BackendNode
104     {
105     public:
106         BackendNode(int backendId);
107
108         virtual ~BackendNode(); //!< Virtual destructor to make polymorphism.
109
110         int backendId; //!< Backend identifier.
111     };
112
113     /**
114      * @brief Derivatives of this class wraps cv::Mat for different backends and targets.
115      */
116     class BackendWrapper
117     {
118     public:
119         BackendWrapper(int backendId, int targetId);
120
121         /**
122          * @brief Wrap cv::Mat for specific backend and target.
123          * @param[in] targetId Target identifier.
124          * @param[in] m cv::Mat for wrapping.
125          *
126          * Make CPU->GPU data transfer if it's require for the target.
127          */
128         BackendWrapper(int targetId, const cv::Mat& m);
129
130         /**
131          * @brief Make wrapper for reused cv::Mat.
132          * @param[in] base Wrapper of cv::Mat that will be reused.
133          * @param[in] shape Specific shape.
134          *
135          * Initialize wrapper from another one. It'll wrap the same host CPU
136          * memory and mustn't allocate memory on device(i.e. GPU). It might
137          * has different shape. Use in case of CPU memory reusing for reuse
138          * associented memory on device too.
139          */
140         BackendWrapper(const Ptr<BackendWrapper>& base, const MatShape& shape);
141
142         virtual ~BackendWrapper(); //!< Virtual destructor to make polymorphism.
143
144         /**
145          * @brief Transfer data to CPU host memory.
146          */
147         virtual void copyToHost() = 0;
148
149         /**
150          * @brief Indicate that an actual data is on CPU.
151          */
152         virtual void setHostDirty() = 0;
153
154         int backendId;  //!< Backend identifier.
155         int targetId;   //!< Target identifier.
156     };
157
158     class CV_EXPORTS ActivationLayer;
159     class CV_EXPORTS BatchNormLayer;
160     class CV_EXPORTS ScaleLayer;
161
162     /** @brief This interface class allows to build new Layers - are building blocks of networks.
163      *
164      * Each class, derived from Layer, must implement allocate() methods to declare own outputs and forward() to compute outputs.
165      * Also before using the new layer into networks you must register your layer by using one of @ref dnnLayerFactory "LayerFactory" macros.
166      */
167     class CV_EXPORTS_W Layer : public Algorithm
168     {
169     public:
170
171         //! List of learned parameters must be stored here to allow read them by using Net::getParam().
172         CV_PROP_RW std::vector<Mat> blobs;
173
174         /** @brief Computes and sets internal parameters according to inputs, outputs and blobs.
175          *  @param[in]  input  vector of already allocated input blobs
176          *  @param[out] output vector of already allocated output blobs
177          *
178          * If this method is called after network has allocated all memory for input and output blobs
179          * and before inferencing.
180          */
181         virtual void finalize(const std::vector<Mat*> &input, std::vector<Mat> &output);
182
183         /** @brief Given the @p input blobs, computes the output @p blobs.
184          *  @param[in]  input  the input blobs.
185          *  @param[out] output allocated output blobs, which will store results of the computation.
186          *  @param[out] internals allocated internal blobs
187          */
188         virtual void forward(std::vector<Mat*> &input, std::vector<Mat> &output, std::vector<Mat> &internals) = 0;
189
190         /** @brief Given the @p input blobs, computes the output @p blobs.
191          *  @param[in]  inputs  the input blobs.
192          *  @param[out] outputs allocated output blobs, which will store results of the computation.
193          *  @param[out] internals allocated internal blobs
194          */
195         virtual void forward(InputArrayOfArrays inputs, OutputArrayOfArrays outputs, OutputArrayOfArrays internals) = 0;
196
197         /** @brief Given the @p input blobs, computes the output @p blobs.
198          *  @param[in]  inputs  the input blobs.
199          *  @param[out] outputs allocated output blobs, which will store results of the computation.
200          *  @param[out] internals allocated internal blobs
201          */
202         void forward_fallback(InputArrayOfArrays inputs, OutputArrayOfArrays outputs, OutputArrayOfArrays internals);
203
204         /** @brief @overload */
205         CV_WRAP void finalize(const std::vector<Mat> &inputs, CV_OUT std::vector<Mat> &outputs);
206
207         /** @brief @overload */
208         CV_WRAP std::vector<Mat> finalize(const std::vector<Mat> &inputs);
209
210         /** @brief Allocates layer and computes output. */
211         CV_WRAP void run(const std::vector<Mat> &inputs, CV_OUT std::vector<Mat> &outputs,
212                          CV_IN_OUT std::vector<Mat> &internals);
213
214         /** @brief Returns index of input blob into the input array.
215          *  @param inputName label of input blob
216          *
217          * Each layer input and output can be labeled to easily identify them using "%<layer_name%>[.output_name]" notation.
218          * This method maps label of input blob to its index into input vector.
219          */
220         virtual int inputNameToIndex(String inputName);
221         /** @brief Returns index of output blob in output array.
222          *  @see inputNameToIndex()
223          */
224         virtual int outputNameToIndex(String outputName);
225
226         /**
227          * @brief Ask layer if it support specific backend for doing computations.
228          * @param[in] backendId computation backend identifier.
229          * @see Backend
230          */
231         virtual bool supportBackend(int backendId);
232
233         /**
234          * @brief Returns Halide backend node.
235          * @param[in] inputs Input Halide buffers.
236          * @see BackendNode, BackendWrapper
237          *
238          * Input buffers should be exactly the same that will be used in forward invocations.
239          * Despite we can use Halide::ImageParam based on input shape only,
240          * it helps prevent some memory management issues (if something wrong,
241          * Halide tests will be failed).
242          */
243         virtual Ptr<BackendNode> initHalide(const std::vector<Ptr<BackendWrapper> > &inputs);
244
245        /**
246         * @brief Automatic Halide scheduling based on layer hyper-parameters.
247         * @param[in] node Backend node with Halide functions.
248         * @param[in] inputs Blobs that will be used in forward invocations.
249         * @param[in] outputs Blobs that will be used in forward invocations.
250         * @param[in] targetId Target identifier
251         * @see BackendNode, Target
252         *
253         * Layer don't use own Halide::Func members because we can have applied
254         * layers fusing. In this way the fused function should be scheduled.
255         */
256         virtual void applyHalideScheduler(Ptr<BackendNode>& node,
257                                           const std::vector<Mat*> &inputs,
258                                           const std::vector<Mat> &outputs,
259                                           int targetId) const;
260
261         /**
262          * @brief Implement layers fusing.
263          * @param[in] node Backend node of bottom layer.
264          * @see BackendNode
265          *
266          * Actual for graph-based backends. If layer attached successfully,
267          * returns non-empty cv::Ptr to node of the same backend.
268          * Fuse only over the last function.
269          */
270         virtual Ptr<BackendNode> tryAttach(const Ptr<BackendNode>& node);
271
272         /**
273          * @brief Tries to attach to the layer the subsequent activation layer, i.e. do the layer fusion in a partial case.
274          * @param[in] layer The subsequent activation layer.
275          *
276          * Returns true if the activation layer has been attached successfully.
277          */
278         virtual bool setActivation(const Ptr<ActivationLayer>& layer);
279
280         /**
281          * @brief Tries to attach to the layer the subsequent batch normalization layer, i.e. do the layer fusion in a partial case.
282          * @param[in] layer The subsequent batch normalization layer.
283          *
284          * Returns true if the batch normalization layer has been attached successfully.
285          */
286         virtual bool setBatchNorm(const Ptr<BatchNormLayer>& layer);
287
288         /**
289          * @brief Tries to attach to the layer the subsequent scaling layer, i.e. do the layer fusion in a partial case.
290          * @param[in] layer The subsequent scaling layer.
291          *
292          * Returns true if the scaling layer has been attached successfully.
293          */
294         virtual bool setScale(const Ptr<ScaleLayer>& layer);
295
296         /**
297          * @brief "Deattaches" all the layers, attached to particular layer.
298          */
299         virtual void unsetAttached();
300
301         virtual bool getMemoryShapes(const std::vector<MatShape> &inputs,
302                                      const int requiredOutputs,
303                                      std::vector<MatShape> &outputs,
304                                      std::vector<MatShape> &internals) const;
305         virtual int64 getFLOPS(const std::vector<MatShape> &inputs,
306                                const std::vector<MatShape> &outputs) const {(void)inputs; (void)outputs; return 0;}
307
308         CV_PROP String name; //!< Name of the layer instance, can be used for logging or other internal purposes.
309         CV_PROP String type; //!< Type name which was used for creating layer by layer factory.
310         CV_PROP int preferableTarget; //!< prefer target for layer forwarding
311
312         Layer();
313         explicit Layer(const LayerParams &params);      //!< Initializes only #name, #type and #blobs fields.
314         void setParamsFrom(const LayerParams &params);  //!< Initializes only #name, #type and #blobs fields.
315         virtual ~Layer();
316     };
317
318     /** @brief This class allows to create and manipulate comprehensive artificial neural networks.
319      *
320      * Neural network is presented as directed acyclic graph (DAG), where vertices are Layer instances,
321      * and edges specify relationships between layers inputs and outputs.
322      *
323      * Each network layer has unique integer id and unique string name inside its network.
324      * LayerId can store either layer name or layer id.
325      *
326      * This class supports reference counting of its instances, i. e. copies point to the same instance.
327      */
328     class CV_EXPORTS_W_SIMPLE Net
329     {
330     public:
331
332         CV_WRAP Net();  //!< Default constructor.
333         CV_WRAP ~Net(); //!< Destructor frees the net only if there aren't references to the net anymore.
334
335         /** Returns true if there are no layers in the network. */
336         CV_WRAP bool empty() const;
337
338         /** @brief Adds new layer to the net.
339          *  @param name   unique name of the adding layer.
340          *  @param type   typename of the adding layer (type must be registered in LayerRegister).
341          *  @param params parameters which will be used to initialize the creating layer.
342          *  @returns unique identifier of created layer, or -1 if a failure will happen.
343          */
344         int addLayer(const String &name, const String &type, LayerParams &params);
345         /** @brief Adds new layer and connects its first input to the first output of previously added layer.
346          *  @see addLayer()
347          */
348         int addLayerToPrev(const String &name, const String &type, LayerParams &params);
349
350         /** @brief Converts string name of the layer to the integer identifier.
351          *  @returns id of the layer, or -1 if the layer wasn't found.
352          */
353         CV_WRAP int getLayerId(const String &layer);
354
355         CV_WRAP std::vector<String> getLayerNames() const;
356
357         /** @brief Container for strings and integers. */
358         typedef DictValue LayerId;
359
360         /** @brief Returns pointer to layer with specified id or name which the network use. */
361         CV_WRAP Ptr<Layer> getLayer(LayerId layerId);
362
363         /** @brief Returns pointers to input layers of specific layer. */
364         std::vector<Ptr<Layer> > getLayerInputs(LayerId layerId); // FIXIT: CV_WRAP
365
366         /** @brief Delete layer for the network (not implemented yet) */
367         CV_WRAP void deleteLayer(LayerId layer);
368
369         /** @brief Connects output of the first layer to input of the second layer.
370          *  @param outPin descriptor of the first layer output.
371          *  @param inpPin descriptor of the second layer input.
372          *
373          * Descriptors have the following template <DFN>&lt;layer_name&gt;[.input_number]</DFN>:
374          * - the first part of the template <DFN>layer_name</DFN> is sting name of the added layer.
375          *   If this part is empty then the network input pseudo layer will be used;
376          * - the second optional part of the template <DFN>input_number</DFN>
377          *   is either number of the layer input, either label one.
378          *   If this part is omitted then the first layer input will be used.
379          *
380          *  @see setNetInputs(), Layer::inputNameToIndex(), Layer::outputNameToIndex()
381          */
382         CV_WRAP void connect(String outPin, String inpPin);
383
384         /** @brief Connects #@p outNum output of the first layer to #@p inNum input of the second layer.
385          *  @param outLayerId identifier of the first layer
386          *  @param inpLayerId identifier of the second layer
387          *  @param outNum number of the first layer output
388          *  @param inpNum number of the second layer input
389          */
390         void connect(int outLayerId, int outNum, int inpLayerId, int inpNum);
391
392         /** @brief Sets outputs names of the network input pseudo layer.
393          *
394          * Each net always has special own the network input pseudo layer with id=0.
395          * This layer stores the user blobs only and don't make any computations.
396          * In fact, this layer provides the only way to pass user data into the network.
397          * As any other layer, this layer can label its outputs and this function provides an easy way to do this.
398          */
399         CV_WRAP void setInputsNames(const std::vector<String> &inputBlobNames);
400
401         /** @brief Runs forward pass to compute output of layer with name @p outputName.
402          *  @param outputName name for layer which output is needed to get
403          *  @return blob for first output of specified layer.
404          *  @details By default runs forward pass for the whole network.
405          */
406         CV_WRAP Mat forward(const String& outputName = String());
407
408         /** @brief Runs forward pass to compute output of layer with name @p outputName.
409          *  @param outputBlobs contains all output blobs for specified layer.
410          *  @param outputName name for layer which output is needed to get
411          *  @details If @p outputName is empty, runs forward pass for the whole network.
412          */
413         CV_WRAP void forward(OutputArrayOfArrays outputBlobs, const String& outputName = String());
414
415         /** @brief Runs forward pass to compute outputs of layers listed in @p outBlobNames.
416          *  @param outputBlobs contains blobs for first outputs of specified layers.
417          *  @param outBlobNames names for layers which outputs are needed to get
418          */
419         CV_WRAP void forward(OutputArrayOfArrays outputBlobs,
420                              const std::vector<String>& outBlobNames);
421
422         /** @brief Runs forward pass to compute outputs of layers listed in @p outBlobNames.
423          *  @param outputBlobs contains all output blobs for each layer specified in @p outBlobNames.
424          *  @param outBlobNames names for layers which outputs are needed to get
425          */
426         CV_WRAP_AS(forwardAndRetrieve) void forward(CV_OUT std::vector<std::vector<Mat> >& outputBlobs,
427                                                     const std::vector<String>& outBlobNames);
428
429         //TODO:
430         /** @brief Optimized forward.
431          *  @warning Not implemented yet.
432          *  @details Makes forward only those layers which weren't changed after previous forward().
433          */
434         void forwardOpt(LayerId toLayer);
435         /** @overload */
436         void forwardOpt(const std::vector<LayerId> &toLayers);
437
438         /**
439          * @brief Compile Halide layers.
440          * @param[in] scheduler Path to YAML file with scheduling directives.
441          * @see setPreferableBackend
442          *
443          * Schedule layers that support Halide backend. Then compile them for
444          * specific target. For layers that not represented in scheduling file
445          * or if no manual scheduling used at all, automatic scheduling will be applied.
446          */
447         CV_WRAP void setHalideScheduler(const String& scheduler);
448
449         /**
450          * @brief Ask network to use specific computation backend where it supported.
451          * @param[in] backendId backend identifier.
452          * @see Backend
453          */
454         CV_WRAP void setPreferableBackend(int backendId);
455
456         /**
457          * @brief Ask network to make computations on specific target device.
458          * @param[in] targetId target identifier.
459          * @see Target
460          */
461         CV_WRAP void setPreferableTarget(int targetId);
462
463         /** @brief Sets the new value for the layer output blob
464          *  @param name descriptor of the updating layer output blob.
465          *  @param blob new blob.
466          *  @see connect(String, String) to know format of the descriptor.
467          *  @note If updating blob is not empty then @p blob must have the same shape,
468          *  because network reshaping is not implemented yet.
469          */
470         CV_WRAP void setInput(InputArray blob, const String& name = "");
471
472         /** @brief Sets the new value for the learned param of the layer.
473          *  @param layer name or id of the layer.
474          *  @param numParam index of the layer parameter in the Layer::blobs array.
475          *  @param blob the new value.
476          *  @see Layer::blobs
477          *  @note If shape of the new blob differs from the previous shape,
478          *  then the following forward pass may fail.
479         */
480         CV_WRAP void setParam(LayerId layer, int numParam, const Mat &blob);
481
482         /** @brief Returns parameter blob of the layer.
483          *  @param layer name or id of the layer.
484          *  @param numParam index of the layer parameter in the Layer::blobs array.
485          *  @see Layer::blobs
486          */
487         CV_WRAP Mat getParam(LayerId layer, int numParam = 0);
488
489         /** @brief Returns indexes of layers with unconnected outputs.
490          */
491         CV_WRAP std::vector<int> getUnconnectedOutLayers() const;
492         /** @brief Returns input and output shapes for all layers in loaded model;
493          *  preliminary inferencing isn't necessary.
494          *  @param netInputShapes shapes for all input blobs in net input layer.
495          *  @param layersIds output parameter for layer IDs.
496          *  @param inLayersShapes output parameter for input layers shapes;
497          * order is the same as in layersIds
498          *  @param outLayersShapes output parameter for output layers shapes;
499          * order is the same as in layersIds
500          */
501         CV_WRAP void getLayersShapes(const std::vector<MatShape>& netInputShapes,
502                                      CV_OUT std::vector<int>& layersIds,
503                                      CV_OUT std::vector<std::vector<MatShape> >& inLayersShapes,
504                                      CV_OUT std::vector<std::vector<MatShape> >& outLayersShapes) const;
505
506         /** @overload */
507         CV_WRAP void getLayersShapes(const MatShape& netInputShape,
508                                      CV_OUT std::vector<int>& layersIds,
509                                      CV_OUT std::vector<std::vector<MatShape> >& inLayersShapes,
510                                      CV_OUT std::vector<std::vector<MatShape> >& outLayersShapes) const;
511
512         /** @brief Returns input and output shapes for layer with specified
513          * id in loaded model; preliminary inferencing isn't necessary.
514          *  @param netInputShape shape input blob in net input layer.
515          *  @param layerId id for layer.
516          *  @param inLayerShapes output parameter for input layers shapes;
517          * order is the same as in layersIds
518          *  @param outLayerShapes output parameter for output layers shapes;
519          * order is the same as in layersIds
520          */
521         void getLayerShapes(const MatShape& netInputShape,
522                                     const int layerId,
523                                     CV_OUT std::vector<MatShape>& inLayerShapes,
524                                     CV_OUT std::vector<MatShape>& outLayerShapes) const; // FIXIT: CV_WRAP
525
526         /** @overload */
527         void getLayerShapes(const std::vector<MatShape>& netInputShapes,
528                                     const int layerId,
529                                     CV_OUT std::vector<MatShape>& inLayerShapes,
530                                     CV_OUT std::vector<MatShape>& outLayerShapes) const; // FIXIT: CV_WRAP
531
532         /** @brief Computes FLOP for whole loaded model with specified input shapes.
533          * @param netInputShapes vector of shapes for all net inputs.
534          * @returns computed FLOP.
535          */
536         CV_WRAP int64 getFLOPS(const std::vector<MatShape>& netInputShapes) const;
537         /** @overload */
538         CV_WRAP int64 getFLOPS(const MatShape& netInputShape) const;
539         /** @overload */
540         CV_WRAP int64 getFLOPS(const int layerId,
541                                const std::vector<MatShape>& netInputShapes) const;
542         /** @overload */
543         CV_WRAP int64 getFLOPS(const int layerId,
544                                const MatShape& netInputShape) const;
545
546         /** @brief Returns list of types for layer used in model.
547          * @param layersTypes output parameter for returning types.
548          */
549         CV_WRAP void getLayerTypes(CV_OUT std::vector<String>& layersTypes) const;
550
551         /** @brief Returns count of layers of specified type.
552          * @param layerType type.
553          * @returns count of layers
554          */
555         CV_WRAP int getLayersCount(const String& layerType) const;
556
557         /** @brief Computes bytes number which are requered to store
558          * all weights and intermediate blobs for model.
559          * @param netInputShapes vector of shapes for all net inputs.
560          * @param weights output parameter to store resulting bytes for weights.
561          * @param blobs output parameter to store resulting bytes for intermediate blobs.
562          */
563         void getMemoryConsumption(const std::vector<MatShape>& netInputShapes,
564                                           CV_OUT size_t& weights, CV_OUT size_t& blobs) const; // FIXIT: CV_WRAP
565         /** @overload */
566         CV_WRAP void getMemoryConsumption(const MatShape& netInputShape,
567                                           CV_OUT size_t& weights, CV_OUT size_t& blobs) const;
568         /** @overload */
569         CV_WRAP void getMemoryConsumption(const int layerId,
570                                           const std::vector<MatShape>& netInputShapes,
571                                           CV_OUT size_t& weights, CV_OUT size_t& blobs) const;
572         /** @overload */
573         CV_WRAP void getMemoryConsumption(const int layerId,
574                                           const MatShape& netInputShape,
575                                           CV_OUT size_t& weights, CV_OUT size_t& blobs) const;
576
577         /** @brief Computes bytes number which are requered to store
578          * all weights and intermediate blobs for each layer.
579          * @param netInputShapes vector of shapes for all net inputs.
580          * @param layerIds output vector to save layer IDs.
581          * @param weights output parameter to store resulting bytes for weights.
582          * @param blobs output parameter to store resulting bytes for intermediate blobs.
583          */
584         void getMemoryConsumption(const std::vector<MatShape>& netInputShapes,
585                                           CV_OUT std::vector<int>& layerIds,
586                                           CV_OUT std::vector<size_t>& weights,
587                                           CV_OUT std::vector<size_t>& blobs) const; // FIXIT: CV_WRAP
588         /** @overload */
589         void getMemoryConsumption(const MatShape& netInputShape,
590                                           CV_OUT std::vector<int>& layerIds,
591                                           CV_OUT std::vector<size_t>& weights,
592                                           CV_OUT std::vector<size_t>& blobs) const; // FIXIT: CV_WRAP
593
594         /** @brief Enables or disables layer fusion in the network.
595          * @param fusion true to enable the fusion, false to disable. The fusion is enabled by default.
596          */
597         CV_WRAP void enableFusion(bool fusion);
598
599         /** @brief Returns overall time for inference and timings (in ticks) for layers.
600          * Indexes in returned vector correspond to layers ids. Some layers can be fused with others,
601          * in this case zero ticks count will be return for that skipped layers.
602          * @param timings vector for tick timings for all layers.
603          * @return overall ticks for model inference.
604          */
605         CV_WRAP int64 getPerfProfile(CV_OUT std::vector<double>& timings);
606
607     private:
608         struct Impl;
609         Ptr<Impl> impl;
610     };
611
612     /**
613      * @deprecated Deprecated as external interface. Will be for internal needs only.
614      * @brief Small interface class for loading trained serialized models of different dnn-frameworks. */
615     class CV_EXPORTS_W Importer : public Algorithm
616     {
617     public:
618
619         /** @brief Adds loaded layers into the @p net and sets connections between them. */
620         CV_DEPRECATED CV_WRAP virtual void populateNet(Net net) = 0;
621
622         virtual ~Importer();
623     };
624
625     /** @brief Reads a network model stored in <a href="https://pjreddie.com/darknet/">Darknet</a> model files.
626     *  @param cfgFile      path to the .cfg file with text description of the network architecture.
627     *  @param darknetModel path to the .weights file with learned network.
628     *  @returns Network object that ready to do forward, throw an exception in failure cases.
629     * @details This is shortcut consisting from DarknetImporter and Net::populateNet calls.
630     */
631     CV_EXPORTS_W Net readNetFromDarknet(const String &cfgFile, const String &darknetModel = String());
632
633     /**
634      *  @deprecated Use @ref readNetFromCaffe instead.
635      *  @brief Creates the importer of <a href="http://caffe.berkeleyvision.org">Caffe</a> framework network.
636      *  @param prototxt   path to the .prototxt file with text description of the network architecture.
637      *  @param caffeModel path to the .caffemodel file with learned network.
638      *  @returns Pointer to the created importer, NULL in failure cases.
639      */
640     CV_DEPRECATED CV_EXPORTS_W Ptr<Importer> createCaffeImporter(const String &prototxt, const String &caffeModel = String());
641
642     /** @brief Reads a network model stored in Caffe model files.
643       * @details This is shortcut consisting from createCaffeImporter and Net::populateNet calls.
644       */
645     CV_EXPORTS_W Net readNetFromCaffe(const String &prototxt, const String &caffeModel = String());
646
647     /** @brief Reads a network model stored in Caffe model in memory.
648       * @details This is an overloaded member function, provided for convenience.
649       * It differs from the above function only in what argument(s) it accepts.
650       * @param bufferProto buffer containing the content of the .prototxt file
651       * @param lenProto length of bufferProto
652       * @param bufferModel buffer containing the content of the .caffemodel file
653       * @param lenModel length of bufferModel
654       */
655     CV_EXPORTS Net readNetFromCaffe(const char *bufferProto, size_t lenProto,
656                                     const char *bufferModel = NULL, size_t lenModel = 0);
657
658     /** @brief Reads a network model stored in Tensorflow model file.
659       * @details This is shortcut consisting from createTensorflowImporter and Net::populateNet calls.
660       */
661     CV_EXPORTS_W Net readNetFromTensorflow(const String &model, const String &config = String());
662
663     /** @brief Reads a network model stored in Tensorflow model in memory.
664       * @details This is an overloaded member function, provided for convenience.
665       * It differs from the above function only in what argument(s) it accepts.
666       * @param bufferModel buffer containing the content of the pb file
667       * @param lenModel length of bufferModel
668       * @param bufferConfig buffer containing the content of the pbtxt file
669       * @param lenConfig length of bufferConfig
670       */
671     CV_EXPORTS Net readNetFromTensorflow(const char *bufferModel, size_t lenModel,
672                                          const char *bufferConfig = NULL, size_t lenConfig = 0);
673
674     /** @brief Reads a network model stored in Torch model file.
675       * @details This is shortcut consisting from createTorchImporter and Net::populateNet calls.
676       */
677     CV_EXPORTS_W Net readNetFromTorch(const String &model, bool isBinary = true);
678
679     /**
680      *  @deprecated Use @ref readNetFromTensorflow instead.
681      *  @brief Creates the importer of <a href="http://www.tensorflow.org">TensorFlow</a> framework network.
682      *  @param model   path to the .pb file with binary protobuf description of the network architecture.
683      *  @returns Pointer to the created importer, NULL in failure cases.
684      */
685     CV_DEPRECATED CV_EXPORTS_W Ptr<Importer> createTensorflowImporter(const String &model);
686
687     /**
688      *  @deprecated Use @ref readNetFromTorch instead.
689      *  @brief Creates the importer of <a href="http://torch.ch">Torch7</a> framework network.
690      *  @param filename path to the file, dumped from Torch by using torch.save() function.
691      *  @param isBinary specifies whether the network was serialized in ascii mode or binary.
692      *  @returns Pointer to the created importer, NULL in failure cases.
693      *
694      *  @warning Torch7 importer is experimental now, you need explicitly set CMake `opencv_dnn_BUILD_TORCH_IMPORTER` flag to compile its.
695      *
696      *  @note Ascii mode of Torch serializer is more preferable, because binary mode extensively use `long` type of C language,
697      *  which has various bit-length on different systems.
698      *
699      * The loading file must contain serialized <a href="https://github.com/torch/nn/blob/master/doc/module.md">nn.Module</a> object
700      * with importing network. Try to eliminate a custom objects from serialazing data to avoid importing errors.
701      *
702      * List of supported layers (i.e. object instances derived from Torch nn.Module class):
703      * - nn.Sequential
704      * - nn.Parallel
705      * - nn.Concat
706      * - nn.Linear
707      * - nn.SpatialConvolution
708      * - nn.SpatialMaxPooling, nn.SpatialAveragePooling
709      * - nn.ReLU, nn.TanH, nn.Sigmoid
710      * - nn.Reshape
711      * - nn.SoftMax, nn.LogSoftMax
712      *
713      * Also some equivalents of these classes from cunn, cudnn, and fbcunn may be successfully imported.
714      */
715     CV_DEPRECATED CV_EXPORTS_W Ptr<Importer> createTorchImporter(const String &filename, bool isBinary = true);
716
717     /** @brief Loads blob which was serialized as torch.Tensor object of Torch7 framework.
718      *  @warning This function has the same limitations as createTorchImporter().
719      */
720     CV_EXPORTS_W Mat readTorchBlob(const String &filename, bool isBinary = true);
721     /** @brief Creates 4-dimensional blob from image. Optionally resizes and crops @p image from center,
722      *  subtract @p mean values, scales values by @p scalefactor, swap Blue and Red channels.
723      *  @param image input image (with 1-, 3- or 4-channels).
724      *  @param size spatial size for output image
725      *  @param mean scalar with mean values which are subtracted from channels. Values are intended
726      *  to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true.
727      *  @param scalefactor multiplier for @p image values.
728      *  @param swapRB flag which indicates that swap first and last channels
729      *  in 3-channel image is necessary.
730      *  @param crop flag which indicates whether image will be cropped after resize or not
731      *  @details if @p crop is true, input image is resized so one side after resize is equal to corresponing
732      *  dimension in @p size and another one is equal or larger. Then, crop from the center is performed.
733      *  If @p crop is false, direct resize without cropping and preserving aspect ratio is performed.
734      *  @returns 4-dimansional Mat with NCHW dimensions order.
735      */
736     CV_EXPORTS_W Mat blobFromImage(InputArray image, double scalefactor=1.0, const Size& size = Size(),
737                                    const Scalar& mean = Scalar(), bool swapRB=true, bool crop=true);
738     /** @brief Creates 4-dimensional blob from series of images. Optionally resizes and
739      *  crops @p images from center, subtract @p mean values, scales values by @p scalefactor,
740      *  swap Blue and Red channels.
741      *  @param images input images (all with 1-, 3- or 4-channels).
742      *  @param size spatial size for output image
743      *  @param mean scalar with mean values which are subtracted from channels. Values are intended
744      *  to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true.
745      *  @param scalefactor multiplier for @p images values.
746      *  @param swapRB flag which indicates that swap first and last channels
747      *  in 3-channel image is necessary.
748      *  @param crop flag which indicates whether image will be cropped after resize or not
749      *  @details if @p crop is true, input image is resized so one side after resize is equal to corresponing
750      *  dimension in @p size and another one is equal or larger. Then, crop from the center is performed.
751      *  If @p crop is false, direct resize without cropping and preserving aspect ratio is performed.
752      *  @returns 4-dimansional Mat with NCHW dimensions order.
753      */
754     CV_EXPORTS_W Mat blobFromImages(const std::vector<Mat>& images, double scalefactor=1.0,
755                                     Size size = Size(), const Scalar& mean = Scalar(), bool swapRB=true, bool crop=true);
756
757     /** @brief Convert all weights of Caffe network to half precision floating point.
758      * @param src Path to origin model from Caffe framework contains single
759      *            precision floating point weights (usually has `.caffemodel` extension).
760      * @param dst Path to destination model with updated weights.
761      * @param layersTypes Set of layers types which parameters will be converted.
762      *                    By default, converts only Convolutional and Fully-Connected layers'
763      *                    weights.
764      *
765      * @note Shrinked model has no origin float32 weights so it can't be used
766      *       in origin Caffe framework anymore. However the structure of data
767      *       is taken from NVidia's Caffe fork: https://github.com/NVIDIA/caffe.
768      *       So the resulting model may be used there.
769      */
770     CV_EXPORTS_W void shrinkCaffeModel(const String& src, const String& dst,
771                                        const std::vector<String>& layersTypes = std::vector<String>());
772
773     /** @brief Performs non maximum suppression given boxes and corresponding scores.
774
775      * @param bboxes a set of bounding boxes to apply NMS.
776      * @param scores a set of corresponding confidences.
777      * @param score_threshold a threshold used to filter boxes by score.
778      * @param nms_threshold a threshold used in non maximum suppression.
779      * @param indices the kept indices of bboxes after NMS.
780      * @param eta a coefficient in adaptive threshold formula: \f$nms\_threshold_{i+1}=eta\cdot nms\_threshold_i\f$.
781      * @param top_k if `>0`, keep at most @p top_k picked indices.
782      */
783     CV_EXPORTS_W void NMSBoxes(const std::vector<Rect>& bboxes, const std::vector<float>& scores,
784                                const float score_threshold, const float nms_threshold,
785                                CV_OUT std::vector<int>& indices,
786                                const float eta = 1.f, const int top_k = 0);
787
788
789 //! @}
790 CV__DNN_EXPERIMENTAL_NS_END
791 }
792 }
793
794 #include <opencv2/dnn/layer.hpp>
795 #include <opencv2/dnn/dnn.inl.hpp>
796
797 #endif  /* OPENCV_DNN_DNN_HPP */