dnn.hpp 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  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_v19 {
  48. #define CV__DNN_EXPERIMENTAL_NS_END }
  49. namespace cv { namespace dnn { namespace experimental_dnn_34_v19 { } using namespace experimental_dnn_34_v19; }}
  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. CV_PROP String name; //!< Name of the layer instance, can be used for logging or other internal purposes.
  315. CV_PROP String type; //!< Type name which was used for creating layer by layer factory.
  316. CV_PROP int preferableTarget; //!< prefer target for layer forwarding
  317. Layer();
  318. explicit Layer(const LayerParams &params); //!< Initializes only #name, #type and #blobs fields.
  319. void setParamsFrom(const LayerParams &params); //!< Initializes only #name, #type and #blobs fields.
  320. virtual ~Layer();
  321. };
  322. /** @brief This class allows to create and manipulate comprehensive artificial neural networks.
  323. *
  324. * Neural network is presented as directed acyclic graph (DAG), where vertices are Layer instances,
  325. * and edges specify relationships between layers inputs and outputs.
  326. *
  327. * Each network layer has unique integer id and unique string name inside its network.
  328. * LayerId can store either layer name or layer id.
  329. *
  330. * This class supports reference counting of its instances, i. e. copies point to the same instance.
  331. */
  332. class CV_EXPORTS_W_SIMPLE Net
  333. {
  334. public:
  335. CV_WRAP Net(); //!< Default constructor.
  336. CV_WRAP ~Net(); //!< Destructor frees the net only if there aren't references to the net anymore.
  337. /** @brief Create a network from Intel's Model Optimizer intermediate representation (IR).
  338. * @param[in] xml XML configuration file with network's topology.
  339. * @param[in] bin Binary file with trained weights.
  340. * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine
  341. * backend.
  342. */
  343. CV_WRAP static Net readFromModelOptimizer(const String& xml, const String& bin);
  344. /** @brief Create a network from Intel's Model Optimizer in-memory buffers with intermediate representation (IR).
  345. * @param[in] bufferModelConfig buffer with model's configuration.
  346. * @param[in] bufferWeights buffer with model's trained weights.
  347. * @returns Net object.
  348. */
  349. CV_WRAP static
  350. Net readFromModelOptimizer(const std::vector<uchar>& bufferModelConfig, const std::vector<uchar>& bufferWeights);
  351. /** @brief Create a network from Intel's Model Optimizer in-memory buffers with intermediate representation (IR).
  352. * @param[in] bufferModelConfigPtr buffer pointer of model's configuration.
  353. * @param[in] bufferModelConfigSize buffer size of model's configuration.
  354. * @param[in] bufferWeightsPtr buffer pointer of model's trained weights.
  355. * @param[in] bufferWeightsSize buffer size of model's trained weights.
  356. * @returns Net object.
  357. */
  358. static
  359. Net readFromModelOptimizer(const uchar* bufferModelConfigPtr, size_t bufferModelConfigSize,
  360. const uchar* bufferWeightsPtr, size_t bufferWeightsSize);
  361. /** Returns true if there are no layers in the network. */
  362. CV_WRAP bool empty() const;
  363. /** @brief Dump net to String
  364. * @returns String with structure, hyperparameters, backend, target and fusion
  365. * Call method after setInput(). To see correct backend, target and fusion run after forward().
  366. */
  367. CV_WRAP String dump();
  368. /** @brief Dump net structure, hyperparameters, backend, target and fusion to dot file
  369. * @param path path to output file with .dot extension
  370. * @see dump()
  371. */
  372. CV_WRAP void dumpToFile(const String& path);
  373. /** @brief Adds new layer to the net.
  374. * @param name unique name of the adding layer.
  375. * @param type typename of the adding layer (type must be registered in LayerRegister).
  376. * @param params parameters which will be used to initialize the creating layer.
  377. * @returns unique identifier of created layer, or -1 if a failure will happen.
  378. */
  379. int addLayer(const String &name, const String &type, LayerParams &params);
  380. /** @brief Adds new layer and connects its first input to the first output of previously added layer.
  381. * @see addLayer()
  382. */
  383. int addLayerToPrev(const String &name, const String &type, LayerParams &params);
  384. /** @brief Converts string name of the layer to the integer identifier.
  385. * @returns id of the layer, or -1 if the layer wasn't found.
  386. */
  387. CV_WRAP int getLayerId(const String &layer);
  388. CV_WRAP std::vector<String> getLayerNames() const;
  389. /** @brief Container for strings and integers. */
  390. typedef DictValue LayerId;
  391. /** @brief Returns pointer to layer with specified id or name which the network use. */
  392. CV_WRAP Ptr<Layer> getLayer(LayerId layerId);
  393. /** @brief Returns pointers to input layers of specific layer. */
  394. std::vector<Ptr<Layer> > getLayerInputs(LayerId layerId); // FIXIT: CV_WRAP
  395. /** @brief Connects output of the first layer to input of the second layer.
  396. * @param outPin descriptor of the first layer output.
  397. * @param inpPin descriptor of the second layer input.
  398. *
  399. * Descriptors have the following template <DFN>&lt;layer_name&gt;[.input_number]</DFN>:
  400. * - the first part of the template <DFN>layer_name</DFN> is string name of the added layer.
  401. * If this part is empty then the network input pseudo layer will be used;
  402. * - the second optional part of the template <DFN>input_number</DFN>
  403. * is either number of the layer input, either label one.
  404. * If this part is omitted then the first layer input will be used.
  405. *
  406. * @see setNetInputs(), Layer::inputNameToIndex(), Layer::outputNameToIndex()
  407. */
  408. CV_WRAP void connect(String outPin, String inpPin);
  409. /** @brief Connects #@p outNum output of the first layer to #@p inNum input of the second layer.
  410. * @param outLayerId identifier of the first layer
  411. * @param outNum number of the first layer output
  412. * @param inpLayerId identifier of the second layer
  413. * @param inpNum number of the second layer input
  414. */
  415. void connect(int outLayerId, int outNum, int inpLayerId, int inpNum);
  416. /** @brief Sets outputs names of the network input pseudo layer.
  417. *
  418. * Each net always has special own the network input pseudo layer with id=0.
  419. * This layer stores the user blobs only and don't make any computations.
  420. * In fact, this layer provides the only way to pass user data into the network.
  421. * As any other layer, this layer can label its outputs and this function provides an easy way to do this.
  422. */
  423. CV_WRAP void setInputsNames(const std::vector<String> &inputBlobNames);
  424. /** @brief Specify shape of network input.
  425. */
  426. CV_WRAP void setInputShape(const String &inputName, const MatShape& shape);
  427. /** @brief Runs forward pass to compute output of layer with name @p outputName.
  428. * @param outputName name for layer which output is needed to get
  429. * @return blob for first output of specified layer.
  430. * @details By default runs forward pass for the whole network.
  431. */
  432. CV_WRAP Mat forward(const String& outputName = String());
  433. /** @brief Runs forward pass to compute output of layer with name @p outputName.
  434. * @param outputName name for layer which output is needed to get
  435. * @details By default runs forward pass for the whole network.
  436. *
  437. * This is an asynchronous version of forward(const String&).
  438. * dnn::DNN_BACKEND_INFERENCE_ENGINE backend is required.
  439. */
  440. CV_WRAP AsyncArray forwardAsync(const String& outputName = String());
  441. /** @brief Runs forward pass to compute output of layer with name @p outputName.
  442. * @param outputBlobs contains all output blobs for specified layer.
  443. * @param outputName name for layer which output is needed to get
  444. * @details If @p outputName is empty, runs forward pass for the whole network.
  445. */
  446. CV_WRAP void forward(OutputArrayOfArrays outputBlobs, const String& outputName = String());
  447. /** @brief Runs forward pass to compute outputs of layers listed in @p outBlobNames.
  448. * @param outputBlobs contains blobs for first outputs of specified layers.
  449. * @param outBlobNames names for layers which outputs are needed to get
  450. */
  451. CV_WRAP void forward(OutputArrayOfArrays outputBlobs,
  452. const std::vector<String>& outBlobNames);
  453. /** @brief Runs forward pass to compute outputs of layers listed in @p outBlobNames.
  454. * @param outputBlobs contains all output blobs for each layer specified in @p outBlobNames.
  455. * @param outBlobNames names for layers which outputs are needed to get
  456. */
  457. CV_WRAP_AS(forwardAndRetrieve) void forward(CV_OUT std::vector<std::vector<Mat> >& outputBlobs,
  458. const std::vector<String>& outBlobNames);
  459. /**
  460. * @brief Compile Halide layers.
  461. * @param[in] scheduler Path to YAML file with scheduling directives.
  462. * @see setPreferableBackend
  463. *
  464. * Schedule layers that support Halide backend. Then compile them for
  465. * specific target. For layers that not represented in scheduling file
  466. * or if no manual scheduling used at all, automatic scheduling will be applied.
  467. */
  468. CV_WRAP void setHalideScheduler(const String& scheduler);
  469. /**
  470. * @brief Ask network to use specific computation backend where it supported.
  471. * @param[in] backendId backend identifier.
  472. * @see Backend
  473. *
  474. * If OpenCV is compiled with Intel's Inference Engine library, DNN_BACKEND_DEFAULT
  475. * means DNN_BACKEND_INFERENCE_ENGINE. Otherwise it equals to DNN_BACKEND_OPENCV.
  476. */
  477. CV_WRAP void setPreferableBackend(int backendId);
  478. /**
  479. * @brief Ask network to make computations on specific target device.
  480. * @param[in] targetId target identifier.
  481. * @see Target
  482. *
  483. * List of supported combinations backend / target:
  484. * | | DNN_BACKEND_OPENCV | DNN_BACKEND_INFERENCE_ENGINE | DNN_BACKEND_HALIDE |
  485. * |------------------------|--------------------|------------------------------|--------------------|
  486. * | DNN_TARGET_CPU | + | + | + |
  487. * | DNN_TARGET_OPENCL | + | + | + |
  488. * | DNN_TARGET_OPENCL_FP16 | + | + | |
  489. * | DNN_TARGET_MYRIAD | | + | |
  490. * | DNN_TARGET_FPGA | | + | |
  491. */
  492. CV_WRAP void setPreferableTarget(int targetId);
  493. /** @brief Sets the new input value for the network
  494. * @param blob A new blob. Should have CV_32F or CV_8U depth.
  495. * @param name A name of input layer.
  496. * @param scalefactor An optional normalization scale.
  497. * @param mean An optional mean subtraction values.
  498. * @see connect(String, String) to know format of the descriptor.
  499. *
  500. * If scale or mean values are specified, a final input blob is computed
  501. * as:
  502. * \f[input(n,c,h,w) = scalefactor \times (blob(n,c,h,w) - mean_c)\f]
  503. */
  504. CV_WRAP void setInput(InputArray blob, const String& name = "",
  505. double scalefactor = 1.0, const Scalar& mean = Scalar());
  506. /** @brief Sets the new value for the learned param of the layer.
  507. * @param layer name or id of the layer.
  508. * @param numParam index of the layer parameter in the Layer::blobs array.
  509. * @param blob the new value.
  510. * @see Layer::blobs
  511. * @note If shape of the new blob differs from the previous shape,
  512. * then the following forward pass may fail.
  513. */
  514. CV_WRAP void setParam(LayerId layer, int numParam, const Mat &blob);
  515. /** @brief Returns parameter blob of the layer.
  516. * @param layer name or id of the layer.
  517. * @param numParam index of the layer parameter in the Layer::blobs array.
  518. * @see Layer::blobs
  519. */
  520. CV_WRAP Mat getParam(LayerId layer, int numParam = 0);
  521. /** @brief Returns indexes of layers with unconnected outputs.
  522. */
  523. CV_WRAP std::vector<int> getUnconnectedOutLayers() const;
  524. /** @brief Returns names of layers with unconnected outputs.
  525. */
  526. CV_WRAP std::vector<String> getUnconnectedOutLayersNames() const;
  527. /** @brief Returns input and output shapes for all layers in loaded model;
  528. * preliminary inferencing isn't necessary.
  529. * @param netInputShapes shapes for all input blobs in net input layer.
  530. * @param layersIds output parameter for layer IDs.
  531. * @param inLayersShapes output parameter for input layers shapes;
  532. * order is the same as in layersIds
  533. * @param outLayersShapes output parameter for output layers shapes;
  534. * order is the same as in layersIds
  535. */
  536. CV_WRAP void getLayersShapes(const std::vector<MatShape>& netInputShapes,
  537. CV_OUT std::vector<int>& layersIds,
  538. CV_OUT std::vector<std::vector<MatShape> >& inLayersShapes,
  539. CV_OUT std::vector<std::vector<MatShape> >& outLayersShapes) const;
  540. /** @overload */
  541. CV_WRAP void getLayersShapes(const MatShape& netInputShape,
  542. CV_OUT std::vector<int>& layersIds,
  543. CV_OUT std::vector<std::vector<MatShape> >& inLayersShapes,
  544. CV_OUT std::vector<std::vector<MatShape> >& outLayersShapes) const;
  545. /** @brief Returns input and output shapes for layer with specified
  546. * id in loaded model; preliminary inferencing isn't necessary.
  547. * @param netInputShape shape input blob in net input layer.
  548. * @param layerId id for layer.
  549. * @param inLayerShapes output parameter for input layers shapes;
  550. * order is the same as in layersIds
  551. * @param outLayerShapes output parameter for output layers shapes;
  552. * order is the same as in layersIds
  553. */
  554. void getLayerShapes(const MatShape& netInputShape,
  555. const int layerId,
  556. CV_OUT std::vector<MatShape>& inLayerShapes,
  557. CV_OUT std::vector<MatShape>& outLayerShapes) const; // FIXIT: CV_WRAP
  558. /** @overload */
  559. void getLayerShapes(const std::vector<MatShape>& netInputShapes,
  560. const int layerId,
  561. CV_OUT std::vector<MatShape>& inLayerShapes,
  562. CV_OUT std::vector<MatShape>& outLayerShapes) const; // FIXIT: CV_WRAP
  563. /** @brief Computes FLOP for whole loaded model with specified input shapes.
  564. * @param netInputShapes vector of shapes for all net inputs.
  565. * @returns computed FLOP.
  566. */
  567. CV_WRAP int64 getFLOPS(const std::vector<MatShape>& netInputShapes) const;
  568. /** @overload */
  569. CV_WRAP int64 getFLOPS(const MatShape& netInputShape) const;
  570. /** @overload */
  571. CV_WRAP int64 getFLOPS(const int layerId,
  572. const std::vector<MatShape>& netInputShapes) const;
  573. /** @overload */
  574. CV_WRAP int64 getFLOPS(const int layerId,
  575. const MatShape& netInputShape) const;
  576. /** @brief Returns list of types for layer used in model.
  577. * @param layersTypes output parameter for returning types.
  578. */
  579. CV_WRAP void getLayerTypes(CV_OUT std::vector<String>& layersTypes) const;
  580. /** @brief Returns count of layers of specified type.
  581. * @param layerType type.
  582. * @returns count of layers
  583. */
  584. CV_WRAP int getLayersCount(const String& layerType) const;
  585. /** @brief Computes bytes number which are required to store
  586. * all weights and intermediate blobs for model.
  587. * @param netInputShapes vector of shapes for all net inputs.
  588. * @param weights output parameter to store resulting bytes for weights.
  589. * @param blobs output parameter to store resulting bytes for intermediate blobs.
  590. */
  591. void getMemoryConsumption(const std::vector<MatShape>& netInputShapes,
  592. CV_OUT size_t& weights, CV_OUT size_t& blobs) const; // FIXIT: CV_WRAP
  593. /** @overload */
  594. CV_WRAP void getMemoryConsumption(const MatShape& netInputShape,
  595. CV_OUT size_t& weights, CV_OUT size_t& blobs) const;
  596. /** @overload */
  597. CV_WRAP void getMemoryConsumption(const int layerId,
  598. const std::vector<MatShape>& netInputShapes,
  599. CV_OUT size_t& weights, CV_OUT size_t& blobs) const;
  600. /** @overload */
  601. CV_WRAP void getMemoryConsumption(const int layerId,
  602. const MatShape& netInputShape,
  603. CV_OUT size_t& weights, CV_OUT size_t& blobs) const;
  604. /** @brief Computes bytes number which are required to store
  605. * all weights and intermediate blobs for each layer.
  606. * @param netInputShapes vector of shapes for all net inputs.
  607. * @param layerIds output vector to save layer IDs.
  608. * @param weights output parameter to store resulting bytes for weights.
  609. * @param blobs output parameter to store resulting bytes for intermediate blobs.
  610. */
  611. void getMemoryConsumption(const std::vector<MatShape>& netInputShapes,
  612. CV_OUT std::vector<int>& layerIds,
  613. CV_OUT std::vector<size_t>& weights,
  614. CV_OUT std::vector<size_t>& blobs) const; // FIXIT: CV_WRAP
  615. /** @overload */
  616. void getMemoryConsumption(const MatShape& netInputShape,
  617. CV_OUT std::vector<int>& layerIds,
  618. CV_OUT std::vector<size_t>& weights,
  619. CV_OUT std::vector<size_t>& blobs) const; // FIXIT: CV_WRAP
  620. /** @brief Enables or disables layer fusion in the network.
  621. * @param fusion true to enable the fusion, false to disable. The fusion is enabled by default.
  622. */
  623. CV_WRAP void enableFusion(bool fusion);
  624. /** @brief Returns overall time for inference and timings (in ticks) for layers.
  625. * Indexes in returned vector correspond to layers ids. Some layers can be fused with others,
  626. * in this case zero ticks count will be return for that skipped layers.
  627. * @param timings vector for tick timings for all layers.
  628. * @return overall ticks for model inference.
  629. */
  630. CV_WRAP int64 getPerfProfile(CV_OUT std::vector<double>& timings);
  631. private:
  632. struct Impl;
  633. Ptr<Impl> impl;
  634. };
  635. /** @brief Reads a network model stored in <a href="https://pjreddie.com/darknet/">Darknet</a> model files.
  636. * @param cfgFile path to the .cfg file with text description of the network architecture.
  637. * @param darknetModel path to the .weights file with learned network.
  638. * @returns Network object that ready to do forward, throw an exception in failure cases.
  639. * @returns Net object.
  640. */
  641. CV_EXPORTS_W Net readNetFromDarknet(const String &cfgFile, const String &darknetModel = String());
  642. /** @brief Reads a network model stored in <a href="https://pjreddie.com/darknet/">Darknet</a> model files.
  643. * @param bufferCfg A buffer contains a content of .cfg file with text description of the network architecture.
  644. * @param bufferModel A buffer contains a content of .weights file with learned network.
  645. * @returns Net object.
  646. */
  647. CV_EXPORTS_W Net readNetFromDarknet(const std::vector<uchar>& bufferCfg,
  648. const std::vector<uchar>& bufferModel = std::vector<uchar>());
  649. /** @brief Reads a network model stored in <a href="https://pjreddie.com/darknet/">Darknet</a> model files.
  650. * @param bufferCfg A buffer contains a content of .cfg file with text description of the network architecture.
  651. * @param lenCfg Number of bytes to read from bufferCfg
  652. * @param bufferModel A buffer contains a content of .weights file with learned network.
  653. * @param lenModel Number of bytes to read from bufferModel
  654. * @returns Net object.
  655. */
  656. CV_EXPORTS Net readNetFromDarknet(const char *bufferCfg, size_t lenCfg,
  657. const char *bufferModel = NULL, size_t lenModel = 0);
  658. /** @brief Reads a network model stored in <a href="http://caffe.berkeleyvision.org">Caffe</a> framework's format.
  659. * @param prototxt path to the .prototxt file with text description of the network architecture.
  660. * @param caffeModel path to the .caffemodel file with learned network.
  661. * @returns Net object.
  662. */
  663. CV_EXPORTS_W Net readNetFromCaffe(const String &prototxt, const String &caffeModel = String());
  664. /** @brief Reads a network model stored in Caffe model in memory.
  665. * @param bufferProto buffer containing the content of the .prototxt file
  666. * @param bufferModel buffer containing the content of the .caffemodel file
  667. * @returns Net object.
  668. */
  669. CV_EXPORTS_W Net readNetFromCaffe(const std::vector<uchar>& bufferProto,
  670. const std::vector<uchar>& bufferModel = std::vector<uchar>());
  671. /** @brief Reads a network model stored in Caffe model in memory.
  672. * @details This is an overloaded member function, provided for convenience.
  673. * It differs from the above function only in what argument(s) it accepts.
  674. * @param bufferProto buffer containing the content of the .prototxt file
  675. * @param lenProto length of bufferProto
  676. * @param bufferModel buffer containing the content of the .caffemodel file
  677. * @param lenModel length of bufferModel
  678. * @returns Net object.
  679. */
  680. CV_EXPORTS Net readNetFromCaffe(const char *bufferProto, size_t lenProto,
  681. const char *bufferModel = NULL, size_t lenModel = 0);
  682. /** @brief Reads a network model stored in <a href="https://www.tensorflow.org/">TensorFlow</a> framework's format.
  683. * @param model path to the .pb file with binary protobuf description of the network architecture
  684. * @param config path to the .pbtxt file that contains text graph definition in protobuf format.
  685. * Resulting Net object is built by text graph using weights from a binary one that
  686. * let us make it more flexible.
  687. * @returns Net object.
  688. */
  689. CV_EXPORTS_W Net readNetFromTensorflow(const String &model, const String &config = String());
  690. /** @brief Reads a network model stored in <a href="https://www.tensorflow.org/">TensorFlow</a> framework's format.
  691. * @param bufferModel buffer containing the content of the pb file
  692. * @param bufferConfig buffer containing the content of the pbtxt file
  693. * @returns Net object.
  694. */
  695. CV_EXPORTS_W Net readNetFromTensorflow(const std::vector<uchar>& bufferModel,
  696. const std::vector<uchar>& bufferConfig = std::vector<uchar>());
  697. /** @brief Reads a network model stored in <a href="https://www.tensorflow.org/">TensorFlow</a> framework's format.
  698. * @details This is an overloaded member function, provided for convenience.
  699. * It differs from the above function only in what argument(s) it accepts.
  700. * @param bufferModel buffer containing the content of the pb file
  701. * @param lenModel length of bufferModel
  702. * @param bufferConfig buffer containing the content of the pbtxt file
  703. * @param lenConfig length of bufferConfig
  704. */
  705. CV_EXPORTS Net readNetFromTensorflow(const char *bufferModel, size_t lenModel,
  706. const char *bufferConfig = NULL, size_t lenConfig = 0);
  707. /**
  708. * @brief Reads a network model stored in <a href="http://torch.ch">Torch7</a> framework's format.
  709. * @param model path to the file, dumped from Torch by using torch.save() function.
  710. * @param isBinary specifies whether the network was serialized in ascii mode or binary.
  711. * @param evaluate specifies testing phase of network. If true, it's similar to evaluate() method in Torch.
  712. * @returns Net object.
  713. *
  714. * @note Ascii mode of Torch serializer is more preferable, because binary mode extensively use `long` type of C language,
  715. * which has various bit-length on different systems.
  716. *
  717. * The loading file must contain serialized <a href="https://github.com/torch/nn/blob/master/doc/module.md">nn.Module</a> object
  718. * with importing network. Try to eliminate a custom objects from serialazing data to avoid importing errors.
  719. *
  720. * List of supported layers (i.e. object instances derived from Torch nn.Module class):
  721. * - nn.Sequential
  722. * - nn.Parallel
  723. * - nn.Concat
  724. * - nn.Linear
  725. * - nn.SpatialConvolution
  726. * - nn.SpatialMaxPooling, nn.SpatialAveragePooling
  727. * - nn.ReLU, nn.TanH, nn.Sigmoid
  728. * - nn.Reshape
  729. * - nn.SoftMax, nn.LogSoftMax
  730. *
  731. * Also some equivalents of these classes from cunn, cudnn, and fbcunn may be successfully imported.
  732. */
  733. CV_EXPORTS_W Net readNetFromTorch(const String &model, bool isBinary = true, bool evaluate = true);
  734. /**
  735. * @brief Read deep learning network represented in one of the supported formats.
  736. * @param[in] model Binary file contains trained weights. The following file
  737. * extensions are expected for models from different frameworks:
  738. * * `*.caffemodel` (Caffe, http://caffe.berkeleyvision.org/)
  739. * * `*.pb` (TensorFlow, https://www.tensorflow.org/)
  740. * * `*.t7` | `*.net` (Torch, http://torch.ch/)
  741. * * `*.weights` (Darknet, https://pjreddie.com/darknet/)
  742. * * `*.bin` (DLDT, https://software.intel.com/openvino-toolkit)
  743. * * `*.onnx` (ONNX, https://onnx.ai/)
  744. * @param[in] config Text file contains network configuration. It could be a
  745. * file with the following extensions:
  746. * * `*.prototxt` (Caffe, http://caffe.berkeleyvision.org/)
  747. * * `*.pbtxt` (TensorFlow, https://www.tensorflow.org/)
  748. * * `*.cfg` (Darknet, https://pjreddie.com/darknet/)
  749. * * `*.xml` (DLDT, https://software.intel.com/openvino-toolkit)
  750. * @param[in] framework Explicit framework name tag to determine a format.
  751. * @returns Net object.
  752. *
  753. * This function automatically detects an origin framework of trained model
  754. * and calls an appropriate function such @ref readNetFromCaffe, @ref readNetFromTensorflow,
  755. * @ref readNetFromTorch or @ref readNetFromDarknet. An order of @p model and @p config
  756. * arguments does not matter.
  757. */
  758. CV_EXPORTS_W Net readNet(const String& model, const String& config = "", const String& framework = "");
  759. /**
  760. * @brief Read deep learning network represented in one of the supported formats.
  761. * @details This is an overloaded member function, provided for convenience.
  762. * It differs from the above function only in what argument(s) it accepts.
  763. * @param[in] framework Name of origin framework.
  764. * @param[in] bufferModel A buffer with a content of binary file with weights
  765. * @param[in] bufferConfig A buffer with a content of text file contains network configuration.
  766. * @returns Net object.
  767. */
  768. CV_EXPORTS_W Net readNet(const String& framework, const std::vector<uchar>& bufferModel,
  769. const std::vector<uchar>& bufferConfig = std::vector<uchar>());
  770. /** @brief Loads blob which was serialized as torch.Tensor object of Torch7 framework.
  771. * @warning This function has the same limitations as readNetFromTorch().
  772. */
  773. CV_EXPORTS_W Mat readTorchBlob(const String &filename, bool isBinary = true);
  774. /** @brief Load a network from Intel's Model Optimizer intermediate representation.
  775. * @param[in] xml XML configuration file with network's topology.
  776. * @param[in] bin Binary file with trained weights.
  777. * @returns Net object.
  778. * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine
  779. * backend.
  780. */
  781. CV_EXPORTS_W
  782. Net readNetFromModelOptimizer(const String &xml, const String &bin);
  783. /** @brief Load a network from Intel's Model Optimizer intermediate representation.
  784. * @param[in] bufferModelConfig Buffer contains XML configuration with network's topology.
  785. * @param[in] bufferWeights Buffer contains binary data with trained weights.
  786. * @returns Net object.
  787. * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine
  788. * backend.
  789. */
  790. CV_EXPORTS_W
  791. Net readNetFromModelOptimizer(const std::vector<uchar>& bufferModelConfig, const std::vector<uchar>& bufferWeights);
  792. /** @brief Load a network from Intel's Model Optimizer intermediate representation.
  793. * @param[in] bufferModelConfigPtr Pointer to buffer which contains XML configuration with network's topology.
  794. * @param[in] bufferModelConfigSize Binary size of XML configuration data.
  795. * @param[in] bufferWeightsPtr Pointer to buffer which contains binary data with trained weights.
  796. * @param[in] bufferWeightsSize Binary size of trained weights data.
  797. * @returns Net object.
  798. * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine
  799. * backend.
  800. */
  801. CV_EXPORTS
  802. Net readNetFromModelOptimizer(const uchar* bufferModelConfigPtr, size_t bufferModelConfigSize,
  803. const uchar* bufferWeightsPtr, size_t bufferWeightsSize);
  804. /** @brief Reads a network model <a href="https://onnx.ai/">ONNX</a>.
  805. * @param onnxFile path to the .onnx file with text description of the network architecture.
  806. * @returns Network object that ready to do forward, throw an exception in failure cases.
  807. */
  808. CV_EXPORTS_W Net readNetFromONNX(const String &onnxFile);
  809. /** @brief Reads a network model from <a href="https://onnx.ai/">ONNX</a>
  810. * in-memory buffer.
  811. * @param buffer memory address of the first byte of the buffer.
  812. * @param sizeBuffer size of the buffer.
  813. * @returns Network object that ready to do forward, throw an exception
  814. * in failure cases.
  815. */
  816. CV_EXPORTS Net readNetFromONNX(const char* buffer, size_t sizeBuffer);
  817. /** @brief Reads a network model from <a href="https://onnx.ai/">ONNX</a>
  818. * in-memory buffer.
  819. * @param buffer in-memory buffer that stores the ONNX model bytes.
  820. * @returns Network object that ready to do forward, throw an exception
  821. * in failure cases.
  822. */
  823. CV_EXPORTS_W Net readNetFromONNX(const std::vector<uchar>& buffer);
  824. /** @brief Creates blob from .pb file.
  825. * @param path to the .pb file with input tensor.
  826. * @returns Mat.
  827. */
  828. CV_EXPORTS_W Mat readTensorFromONNX(const String& path);
  829. /** @brief Creates 4-dimensional blob from image. Optionally resizes and crops @p image from center,
  830. * subtract @p mean values, scales values by @p scalefactor, swap Blue and Red channels.
  831. * @param image input image (with 1-, 3- or 4-channels).
  832. * @param size spatial size for output image
  833. * @param mean scalar with mean values which are subtracted from channels. Values are intended
  834. * to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true.
  835. * @param scalefactor multiplier for @p image values.
  836. * @param swapRB flag which indicates that swap first and last channels
  837. * in 3-channel image is necessary.
  838. * @param crop flag which indicates whether image will be cropped after resize or not
  839. * @param ddepth Depth of output blob. Choose CV_32F or CV_8U.
  840. * @details if @p crop is true, input image is resized so one side after resize is equal to corresponding
  841. * dimension in @p size and another one is equal or larger. Then, crop from the center is performed.
  842. * If @p crop is false, direct resize without cropping and preserving aspect ratio is performed.
  843. * @returns 4-dimensional Mat with NCHW dimensions order.
  844. */
  845. CV_EXPORTS_W Mat blobFromImage(InputArray image, double scalefactor=1.0, const Size& size = Size(),
  846. const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false,
  847. int ddepth=CV_32F);
  848. /** @brief Creates 4-dimensional blob from image.
  849. * @details This is an overloaded member function, provided for convenience.
  850. * It differs from the above function only in what argument(s) it accepts.
  851. */
  852. CV_EXPORTS void blobFromImage(InputArray image, OutputArray blob, double scalefactor=1.0,
  853. const Size& size = Size(), const Scalar& mean = Scalar(),
  854. bool swapRB=false, bool crop=false, int ddepth=CV_32F);
  855. /** @brief Creates 4-dimensional blob from series of images. Optionally resizes and
  856. * crops @p images from center, subtract @p mean values, scales values by @p scalefactor,
  857. * swap Blue and Red channels.
  858. * @param images input images (all with 1-, 3- or 4-channels).
  859. * @param size spatial size for output image
  860. * @param mean scalar with mean values which are subtracted from channels. Values are intended
  861. * to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true.
  862. * @param scalefactor multiplier for @p images values.
  863. * @param swapRB flag which indicates that swap first and last channels
  864. * in 3-channel image is necessary.
  865. * @param crop flag which indicates whether image will be cropped after resize or not
  866. * @param ddepth Depth of output blob. Choose CV_32F or CV_8U.
  867. * @details if @p crop is true, input image is resized so one side after resize is equal to corresponding
  868. * dimension in @p size and another one is equal or larger. Then, crop from the center is performed.
  869. * If @p crop is false, direct resize without cropping and preserving aspect ratio is performed.
  870. * @returns 4-dimensional Mat with NCHW dimensions order.
  871. */
  872. CV_EXPORTS_W Mat blobFromImages(InputArrayOfArrays images, double scalefactor=1.0,
  873. Size size = Size(), const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false,
  874. int ddepth=CV_32F);
  875. /** @brief Creates 4-dimensional blob from series of images.
  876. * @details This is an overloaded member function, provided for convenience.
  877. * It differs from the above function only in what argument(s) it accepts.
  878. */
  879. CV_EXPORTS void blobFromImages(InputArrayOfArrays images, OutputArray blob,
  880. double scalefactor=1.0, Size size = Size(),
  881. const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false,
  882. int ddepth=CV_32F);
  883. /** @brief Parse a 4D blob and output the images it contains as 2D arrays through a simpler data structure
  884. * (std::vector<cv::Mat>).
  885. * @param[in] blob_ 4 dimensional array (images, channels, height, width) in floating point precision (CV_32F) from
  886. * which you would like to extract the images.
  887. * @param[out] images_ array of 2D Mat containing the images extracted from the blob in floating point precision
  888. * (CV_32F). They are non normalized neither mean added. The number of returned images equals the first dimension
  889. * of the blob (batch size). Every image has a number of channels equals to the second dimension of the blob (depth).
  890. */
  891. CV_EXPORTS_W void imagesFromBlob(const cv::Mat& blob_, OutputArrayOfArrays images_);
  892. /** @brief Convert all weights of Caffe network to half precision floating point.
  893. * @param src Path to origin model from Caffe framework contains single
  894. * precision floating point weights (usually has `.caffemodel` extension).
  895. * @param dst Path to destination model with updated weights.
  896. * @param layersTypes Set of layers types which parameters will be converted.
  897. * By default, converts only Convolutional and Fully-Connected layers'
  898. * weights.
  899. *
  900. * @note Shrinked model has no origin float32 weights so it can't be used
  901. * in origin Caffe framework anymore. However the structure of data
  902. * is taken from NVidia's Caffe fork: https://github.com/NVIDIA/caffe.
  903. * So the resulting model may be used there.
  904. */
  905. CV_EXPORTS_W void shrinkCaffeModel(const String& src, const String& dst,
  906. const std::vector<String>& layersTypes = std::vector<String>());
  907. /** @brief Create a text representation for a binary network stored in protocol buffer format.
  908. * @param[in] model A path to binary network.
  909. * @param[in] output A path to output text file to be created.
  910. *
  911. * @note To reduce output file size, trained weights are not included.
  912. */
  913. CV_EXPORTS_W void writeTextGraph(const String& model, const String& output);
  914. /** @brief Performs non maximum suppression given boxes and corresponding scores.
  915. * @param bboxes a set of bounding boxes to apply NMS.
  916. * @param scores a set of corresponding confidences.
  917. * @param score_threshold a threshold used to filter boxes by score.
  918. * @param nms_threshold a threshold used in non maximum suppression.
  919. * @param indices the kept indices of bboxes after NMS.
  920. * @param eta a coefficient in adaptive threshold formula: \f$nms\_threshold_{i+1}=eta\cdot nms\_threshold_i\f$.
  921. * @param top_k if `>0`, keep at most @p top_k picked indices.
  922. */
  923. CV_EXPORTS void NMSBoxes(const std::vector<Rect>& bboxes, const std::vector<float>& scores,
  924. const float score_threshold, const float nms_threshold,
  925. CV_OUT std::vector<int>& indices,
  926. const float eta = 1.f, const int top_k = 0);
  927. CV_EXPORTS_W void NMSBoxes(const std::vector<Rect2d>& bboxes, const std::vector<float>& scores,
  928. const float score_threshold, const float nms_threshold,
  929. CV_OUT std::vector<int>& indices,
  930. const float eta = 1.f, const int top_k = 0);
  931. CV_EXPORTS_AS(NMSBoxesRotated) void NMSBoxes(const std::vector<RotatedRect>& bboxes, const std::vector<float>& scores,
  932. const float score_threshold, const float nms_threshold,
  933. CV_OUT std::vector<int>& indices,
  934. const float eta = 1.f, const int top_k = 0);
  935. //! @}
  936. CV__DNN_EXPERIMENTAL_NS_END
  937. }
  938. }
  939. #include <opencv2/dnn/layer.hpp>
  940. #include <opencv2/dnn/dnn.inl.hpp>
  941. /// @deprecated Include this header directly from application. Automatic inclusion will be removed
  942. #include <opencv2/dnn/utils/inference_engine.hpp>
  943. #endif /* OPENCV_DNN_DNN_HPP */