dnn.hpp 39 KB

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