dnn.hpp 49 KB

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