dnn.hpp 52 KB

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