dnn.hpp 49 KB

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