dnn.hpp 43 KB

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