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

Provided by KDAB

Privacy Policy
Update your C++ knowledge – Modern C++11/14/17 Training
Find out more

source code of opencv/modules/dnn/include/opencv2/dnn/dnn.hpp