dnn.hpp 55 KB

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