dnn.hpp 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697
  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. #include "../dnn/version.hpp"
  47. #include <opencv2/dnn/dict.hpp>
  48. namespace cv {
  49. namespace dnn {
  50. CV__DNN_INLINE_NS_BEGIN
  51. //! @addtogroup dnn
  52. //! @{
  53. typedef std::vector<int> MatShape;
  54. /**
  55. * @brief Enum of computation backends supported by layers.
  56. * @see Net::setPreferableBackend
  57. */
  58. enum Backend
  59. {
  60. //! DNN_BACKEND_DEFAULT equals to DNN_BACKEND_INFERENCE_ENGINE if
  61. //! OpenCV is built with Intel's Inference Engine library or
  62. //! DNN_BACKEND_OPENCV otherwise.
  63. DNN_BACKEND_DEFAULT = 0,
  64. DNN_BACKEND_HALIDE,
  65. DNN_BACKEND_INFERENCE_ENGINE, //!< Intel's Inference Engine computational backend
  66. //!< @sa setInferenceEngineBackendType
  67. DNN_BACKEND_OPENCV,
  68. DNN_BACKEND_VKCOM,
  69. DNN_BACKEND_CUDA,
  70. DNN_BACKEND_WEBNN,
  71. #ifdef __OPENCV_BUILD
  72. DNN_BACKEND_INFERENCE_ENGINE_NGRAPH = 1000000, // internal - use DNN_BACKEND_INFERENCE_ENGINE + setInferenceEngineBackendType()
  73. DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019, // internal - use DNN_BACKEND_INFERENCE_ENGINE + setInferenceEngineBackendType()
  74. #endif
  75. };
  76. /**
  77. * @brief Enum of target devices for computations.
  78. * @see Net::setPreferableTarget
  79. */
  80. enum Target
  81. {
  82. DNN_TARGET_CPU = 0,
  83. DNN_TARGET_OPENCL,
  84. DNN_TARGET_OPENCL_FP16,
  85. DNN_TARGET_MYRIAD,
  86. DNN_TARGET_VULKAN,
  87. DNN_TARGET_FPGA, //!< FPGA device with CPU fallbacks using Inference Engine's Heterogeneous plugin.
  88. DNN_TARGET_CUDA,
  89. DNN_TARGET_CUDA_FP16,
  90. DNN_TARGET_HDDL
  91. };
  92. CV_EXPORTS std::vector< std::pair<Backend, Target> > getAvailableBackends();
  93. CV_EXPORTS_W std::vector<Target> getAvailableTargets(dnn::Backend be);
  94. /**
  95. * @brief Enables detailed logging of the DNN model loading with CV DNN API.
  96. * @param[in] isDiagnosticsMode Indicates whether diagnostic mode should be set.
  97. *
  98. * Diagnostic mode provides detailed logging of the model loading stage to explore
  99. * potential problems (ex.: not implemented layer type).
  100. *
  101. * @note In diagnostic mode series of assertions will be skipped, it can lead to the
  102. * expected application crash.
  103. */
  104. CV_EXPORTS void enableModelDiagnostics(bool isDiagnosticsMode);
  105. /** @brief This class provides all data needed to initialize layer.
  106. *
  107. * It includes dictionary with scalar params (which can be read by using Dict interface),
  108. * blob params #blobs and optional meta information: #name and #type of layer instance.
  109. */
  110. class CV_EXPORTS LayerParams : public Dict
  111. {
  112. public:
  113. //TODO: Add ability to name blob params
  114. std::vector<Mat> blobs; //!< List of learned parameters stored as blobs.
  115. String name; //!< Name of the layer instance (optional, can be used internal purposes).
  116. String type; //!< Type name which was used for creating layer by layer factory (optional).
  117. };
  118. /**
  119. * @brief Derivatives of this class encapsulates functions of certain backends.
  120. */
  121. class BackendNode
  122. {
  123. public:
  124. BackendNode(int backendId);
  125. virtual ~BackendNode(); //!< Virtual destructor to make polymorphism.
  126. int backendId; //!< Backend identifier.
  127. };
  128. /**
  129. * @brief Derivatives of this class wraps cv::Mat for different backends and targets.
  130. */
  131. class BackendWrapper
  132. {
  133. public:
  134. BackendWrapper(int backendId, int targetId);
  135. /**
  136. * @brief Wrap cv::Mat for specific backend and target.
  137. * @param[in] targetId Target identifier.
  138. * @param[in] m cv::Mat for wrapping.
  139. *
  140. * Make CPU->GPU data transfer if it's require for the target.
  141. */
  142. BackendWrapper(int targetId, const cv::Mat& m);
  143. /**
  144. * @brief Make wrapper for reused cv::Mat.
  145. * @param[in] base Wrapper of cv::Mat that will be reused.
  146. * @param[in] shape Specific shape.
  147. *
  148. * Initialize wrapper from another one. It'll wrap the same host CPU
  149. * memory and mustn't allocate memory on device(i.e. GPU). It might
  150. * has different shape. Use in case of CPU memory reusing for reuse
  151. * associated memory on device too.
  152. */
  153. BackendWrapper(const Ptr<BackendWrapper>& base, const MatShape& shape);
  154. virtual ~BackendWrapper(); //!< Virtual destructor to make polymorphism.
  155. /**
  156. * @brief Transfer data to CPU host memory.
  157. */
  158. virtual void copyToHost() = 0;
  159. /**
  160. * @brief Indicate that an actual data is on CPU.
  161. */
  162. virtual void setHostDirty() = 0;
  163. int backendId; //!< Backend identifier.
  164. int targetId; //!< Target identifier.
  165. };
  166. class CV_EXPORTS ActivationLayer;
  167. /** @brief This interface class allows to build new Layers - are building blocks of networks.
  168. *
  169. * Each class, derived from Layer, must implement allocate() methods to declare own outputs and forward() to compute outputs.
  170. * Also before using the new layer into networks you must register your layer by using one of @ref dnnLayerFactory "LayerFactory" macros.
  171. */
  172. class CV_EXPORTS_W Layer : public Algorithm
  173. {
  174. public:
  175. //! List of learned parameters must be stored here to allow read them by using Net::getParam().
  176. CV_PROP_RW std::vector<Mat> blobs;
  177. /** @brief Computes and sets internal parameters according to inputs, outputs and blobs.
  178. * @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead
  179. * @param[in] input vector of already allocated input blobs
  180. * @param[out] output 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_DEPRECATED_EXTERNAL
  186. virtual void finalize(const std::vector<Mat*> &input, std::vector<Mat> &output);
  187. /** @brief Computes and sets internal parameters according to inputs, outputs and blobs.
  188. * @param[in] inputs vector of already allocated input blobs
  189. * @param[out] outputs vector of already allocated output blobs
  190. *
  191. * If this method is called after network has allocated all memory for input and output blobs
  192. * and before inferencing.
  193. */
  194. CV_WRAP virtual void finalize(InputArrayOfArrays inputs, OutputArrayOfArrays outputs);
  195. /** @brief Given the @p input blobs, computes the output @p blobs.
  196. * @deprecated Use Layer::forward(InputArrayOfArrays, OutputArrayOfArrays, OutputArrayOfArrays) instead
  197. * @param[in] input the input blobs.
  198. * @param[out] output allocated output blobs, which will store results of the computation.
  199. * @param[out] internals allocated internal blobs
  200. */
  201. CV_DEPRECATED_EXTERNAL
  202. virtual void forward(std::vector<Mat*> &input, std::vector<Mat> &output, std::vector<Mat> &internals);
  203. /** @brief Given the @p input blobs, computes the output @p blobs.
  204. * @param[in] inputs the input blobs.
  205. * @param[out] outputs allocated output blobs, which will store results of the computation.
  206. * @param[out] internals allocated internal blobs
  207. */
  208. virtual void forward(InputArrayOfArrays inputs, OutputArrayOfArrays outputs, OutputArrayOfArrays internals);
  209. /** @brief Tries to quantize the given layer and compute the quantization parameters required for fixed point implementation.
  210. * @param[in] scales input and output scales.
  211. * @param[in] zeropoints input and output zeropoints.
  212. * @param[out] params Quantized parameters required for fixed point implementation of that layer.
  213. * @returns True if layer can be quantized.
  214. */
  215. virtual bool tryQuantize(const std::vector<std::vector<float> > &scales,
  216. const std::vector<std::vector<int> > &zeropoints, LayerParams& params);
  217. /** @brief Given the @p input blobs, computes the output @p blobs.
  218. * @param[in] inputs the input blobs.
  219. * @param[out] outputs allocated output blobs, which will store results of the computation.
  220. * @param[out] internals allocated internal blobs
  221. */
  222. void forward_fallback(InputArrayOfArrays inputs, OutputArrayOfArrays outputs, OutputArrayOfArrays internals);
  223. /** @brief
  224. * @overload
  225. * @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead
  226. */
  227. CV_DEPRECATED_EXTERNAL
  228. void finalize(const std::vector<Mat> &inputs, CV_OUT std::vector<Mat> &outputs);
  229. /** @brief
  230. * @overload
  231. * @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead
  232. */
  233. CV_DEPRECATED std::vector<Mat> finalize(const std::vector<Mat> &inputs);
  234. /** @brief Allocates layer and computes output.
  235. * @deprecated This method will be removed in the future release.
  236. */
  237. CV_DEPRECATED CV_WRAP void run(const std::vector<Mat> &inputs, CV_OUT std::vector<Mat> &outputs,
  238. CV_IN_OUT std::vector<Mat> &internals);
  239. /** @brief Returns index of input blob into the input array.
  240. * @param inputName label of input blob
  241. *
  242. * Each layer input and output can be labeled to easily identify them using "%<layer_name%>[.output_name]" notation.
  243. * This method maps label of input blob to its index into input vector.
  244. */
  245. virtual int inputNameToIndex(String inputName);
  246. /** @brief Returns index of output blob in output array.
  247. * @see inputNameToIndex()
  248. */
  249. CV_WRAP virtual int outputNameToIndex(const String& outputName);
  250. /**
  251. * @brief Ask layer if it support specific backend for doing computations.
  252. * @param[in] backendId computation backend identifier.
  253. * @see Backend
  254. */
  255. virtual bool supportBackend(int backendId);
  256. /**
  257. * @brief Returns Halide backend node.
  258. * @param[in] inputs Input Halide buffers.
  259. * @see BackendNode, BackendWrapper
  260. *
  261. * Input buffers should be exactly the same that will be used in forward invocations.
  262. * Despite we can use Halide::ImageParam based on input shape only,
  263. * it helps prevent some memory management issues (if something wrong,
  264. * Halide tests will be failed).
  265. */
  266. virtual Ptr<BackendNode> initHalide(const std::vector<Ptr<BackendWrapper> > &inputs);
  267. virtual Ptr<BackendNode> initInfEngine(const std::vector<Ptr<BackendWrapper> > &inputs);
  268. virtual Ptr<BackendNode> initNgraph(const std::vector<Ptr<BackendWrapper> > &inputs, const std::vector<Ptr<BackendNode> >& nodes);
  269. virtual Ptr<BackendNode> initVkCom(const std::vector<Ptr<BackendWrapper> > &inputs);
  270. virtual Ptr<BackendNode> initWebnn(const std::vector<Ptr<BackendWrapper> > &inputs, const std::vector<Ptr<BackendNode> >& nodes);
  271. /**
  272. * @brief Returns a CUDA backend node
  273. *
  274. * @param context void pointer to CSLContext object
  275. * @param inputs layer inputs
  276. * @param outputs layer outputs
  277. */
  278. virtual Ptr<BackendNode> initCUDA(
  279. void *context,
  280. const std::vector<Ptr<BackendWrapper>>& inputs,
  281. const std::vector<Ptr<BackendWrapper>>& outputs
  282. );
  283. /**
  284. * @brief Automatic Halide scheduling based on layer hyper-parameters.
  285. * @param[in] node Backend node with Halide functions.
  286. * @param[in] inputs Blobs that will be used in forward invocations.
  287. * @param[in] outputs Blobs that will be used in forward invocations.
  288. * @param[in] targetId Target identifier
  289. * @see BackendNode, Target
  290. *
  291. * Layer don't use own Halide::Func members because we can have applied
  292. * layers fusing. In this way the fused function should be scheduled.
  293. */
  294. virtual void applyHalideScheduler(Ptr<BackendNode>& node,
  295. const std::vector<Mat*> &inputs,
  296. const std::vector<Mat> &outputs,
  297. int targetId) const;
  298. /**
  299. * @brief Implement layers fusing.
  300. * @param[in] node Backend node of bottom layer.
  301. * @see BackendNode
  302. *
  303. * Actual for graph-based backends. If layer attached successfully,
  304. * returns non-empty cv::Ptr to node of the same backend.
  305. * Fuse only over the last function.
  306. */
  307. virtual Ptr<BackendNode> tryAttach(const Ptr<BackendNode>& node);
  308. /**
  309. * @brief Tries to attach to the layer the subsequent activation layer, i.e. do the layer fusion in a partial case.
  310. * @param[in] layer The subsequent activation layer.
  311. *
  312. * Returns true if the activation layer has been attached successfully.
  313. */
  314. virtual bool setActivation(const Ptr<ActivationLayer>& layer);
  315. /**
  316. * @brief Try to fuse current layer with a next one
  317. * @param[in] top Next layer to be fused.
  318. * @returns True if fusion was performed.
  319. */
  320. virtual bool tryFuse(Ptr<Layer>& top);
  321. /**
  322. * @brief Returns parameters of layers with channel-wise multiplication and addition.
  323. * @param[out] scale Channel-wise multipliers. Total number of values should
  324. * be equal to number of channels.
  325. * @param[out] shift Channel-wise offsets. Total number of values should
  326. * be equal to number of channels.
  327. *
  328. * Some layers can fuse their transformations with further layers.
  329. * In example, convolution + batch normalization. This way base layer
  330. * use weights from layer after it. Fused layer is skipped.
  331. * By default, @p scale and @p shift are empty that means layer has no
  332. * element-wise multiplications or additions.
  333. */
  334. virtual void getScaleShift(Mat& scale, Mat& shift) const;
  335. /**
  336. * @brief Returns scale and zeropoint of layers
  337. * @param[out] scale Output scale
  338. * @param[out] zeropoint Output zeropoint
  339. *
  340. * By default, @p scale is 1 and @p zeropoint is 0.
  341. */
  342. virtual void getScaleZeropoint(float& scale, int& zeropoint) const;
  343. /**
  344. * @brief "Deattaches" all the layers, attached to particular layer.
  345. */
  346. virtual void unsetAttached();
  347. virtual bool getMemoryShapes(const std::vector<MatShape> &inputs,
  348. const int requiredOutputs,
  349. std::vector<MatShape> &outputs,
  350. std::vector<MatShape> &internals) const;
  351. virtual int64 getFLOPS(const std::vector<MatShape> &inputs,
  352. const std::vector<MatShape> &outputs) const {CV_UNUSED(inputs); CV_UNUSED(outputs); return 0;}
  353. virtual bool updateMemoryShapes(const std::vector<MatShape> &inputs);
  354. CV_PROP String name; //!< Name of the layer instance, can be used for logging or other internal purposes.
  355. CV_PROP String type; //!< Type name which was used for creating layer by layer factory.
  356. CV_PROP int preferableTarget; //!< prefer target for layer forwarding
  357. Layer();
  358. explicit Layer(const LayerParams &params); //!< Initializes only #name, #type and #blobs fields.
  359. void setParamsFrom(const LayerParams &params); //!< Initializes only #name, #type and #blobs fields.
  360. virtual ~Layer();
  361. };
  362. /** @brief This class allows to create and manipulate comprehensive artificial neural networks.
  363. *
  364. * Neural network is presented as directed acyclic graph (DAG), where vertices are Layer instances,
  365. * and edges specify relationships between layers inputs and outputs.
  366. *
  367. * Each network layer has unique integer id and unique string name inside its network.
  368. * LayerId can store either layer name or layer id.
  369. *
  370. * This class supports reference counting of its instances, i. e. copies point to the same instance.
  371. */
  372. class CV_EXPORTS_W_SIMPLE Net
  373. {
  374. public:
  375. CV_WRAP Net(); //!< Default constructor.
  376. CV_WRAP ~Net(); //!< Destructor frees the net only if there aren't references to the net anymore.
  377. /** @brief Create a network from Intel's Model Optimizer intermediate representation (IR).
  378. * @param[in] xml XML configuration file with network's topology.
  379. * @param[in] bin Binary file with trained weights.
  380. * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine
  381. * backend.
  382. */
  383. CV_WRAP static Net readFromModelOptimizer(const String& xml, const String& bin);
  384. /** @brief Create a network from Intel's Model Optimizer in-memory buffers with intermediate representation (IR).
  385. * @param[in] bufferModelConfig buffer with model's configuration.
  386. * @param[in] bufferWeights buffer with model's trained weights.
  387. * @returns Net object.
  388. */
  389. CV_WRAP static
  390. Net readFromModelOptimizer(const std::vector<uchar>& bufferModelConfig, const std::vector<uchar>& bufferWeights);
  391. /** @brief Create a network from Intel's Model Optimizer in-memory buffers with intermediate representation (IR).
  392. * @param[in] bufferModelConfigPtr buffer pointer of model's configuration.
  393. * @param[in] bufferModelConfigSize buffer size of model's configuration.
  394. * @param[in] bufferWeightsPtr buffer pointer of model's trained weights.
  395. * @param[in] bufferWeightsSize buffer size of model's trained weights.
  396. * @returns Net object.
  397. */
  398. static
  399. Net readFromModelOptimizer(const uchar* bufferModelConfigPtr, size_t bufferModelConfigSize,
  400. const uchar* bufferWeightsPtr, size_t bufferWeightsSize);
  401. /** Returns true if there are no layers in the network. */
  402. CV_WRAP bool empty() const;
  403. /** @brief Dump net to String
  404. * @returns String with structure, hyperparameters, backend, target and fusion
  405. * Call method after setInput(). To see correct backend, target and fusion run after forward().
  406. */
  407. CV_WRAP String dump();
  408. /** @brief Dump net structure, hyperparameters, backend, target and fusion to dot file
  409. * @param path path to output file with .dot extension
  410. * @see dump()
  411. */
  412. CV_WRAP void dumpToFile(const String& path);
  413. /** @brief Adds new layer to the net.
  414. * @param name unique name of the adding layer.
  415. * @param type typename of the adding layer (type must be registered in LayerRegister).
  416. * @param dtype datatype of output blobs.
  417. * @param params parameters which will be used to initialize the creating layer.
  418. * @returns unique identifier of created layer, or -1 if a failure will happen.
  419. */
  420. int addLayer(const String &name, const String &type, const int &dtype, LayerParams &params);
  421. /** @overload Datatype of output blobs set to default CV_32F */
  422. int addLayer(const String &name, const String &type, LayerParams &params);
  423. /** @brief Adds new layer and connects its first input to the first output of previously added layer.
  424. * @see addLayer()
  425. */
  426. int addLayerToPrev(const String &name, const String &type, const int &dtype, LayerParams &params);
  427. /** @overload */
  428. int addLayerToPrev(const String &name, const String &type, LayerParams &params);
  429. /** @brief Converts string name of the layer to the integer identifier.
  430. * @returns id of the layer, or -1 if the layer wasn't found.
  431. */
  432. CV_WRAP int getLayerId(const String &layer);
  433. CV_WRAP std::vector<String> getLayerNames() const;
  434. /** @brief Container for strings and integers. */
  435. typedef DictValue LayerId;
  436. /** @brief Returns pointer to layer with specified id or name which the network use. */
  437. CV_WRAP Ptr<Layer> getLayer(LayerId layerId);
  438. /** @brief Returns pointers to input layers of specific layer. */
  439. std::vector<Ptr<Layer> > getLayerInputs(LayerId layerId); // FIXIT: CV_WRAP
  440. /** @brief Connects output of the first layer to input of the second layer.
  441. * @param outPin descriptor of the first layer output.
  442. * @param inpPin descriptor of the second layer input.
  443. *
  444. * Descriptors have the following template <DFN>&lt;layer_name&gt;[.input_number]</DFN>:
  445. * - the first part of the template <DFN>layer_name</DFN> is string name of the added layer.
  446. * If this part is empty then the network input pseudo layer will be used;
  447. * - the second optional part of the template <DFN>input_number</DFN>
  448. * is either number of the layer input, either label one.
  449. * If this part is omitted then the first layer input will be used.
  450. *
  451. * @see setNetInputs(), Layer::inputNameToIndex(), Layer::outputNameToIndex()
  452. */
  453. CV_WRAP void connect(String outPin, String inpPin);
  454. /** @brief Connects #@p outNum output of the first layer to #@p inNum input of the second layer.
  455. * @param outLayerId identifier of the first layer
  456. * @param outNum number of the first layer output
  457. * @param inpLayerId identifier of the second layer
  458. * @param inpNum number of the second layer input
  459. */
  460. void connect(int outLayerId, int outNum, int inpLayerId, int inpNum);
  461. /** @brief Sets outputs names of the network input pseudo layer.
  462. *
  463. * Each net always has special own the network input pseudo layer with id=0.
  464. * This layer stores the user blobs only and don't make any computations.
  465. * In fact, this layer provides the only way to pass user data into the network.
  466. * As any other layer, this layer can label its outputs and this function provides an easy way to do this.
  467. */
  468. CV_WRAP void setInputsNames(const std::vector<String> &inputBlobNames);
  469. /** @brief Specify shape of network input.
  470. */
  471. CV_WRAP void setInputShape(const String &inputName, const MatShape& shape);
  472. /** @brief Runs forward pass to compute output of layer with name @p outputName.
  473. * @param outputName name for layer which output is needed to get
  474. * @return blob for first output of specified layer.
  475. * @details By default runs forward pass for the whole network.
  476. */
  477. CV_WRAP Mat forward(const String& outputName = String());
  478. /** @brief Runs forward pass to compute output of layer with name @p outputName.
  479. * @param outputName name for layer which output is needed to get
  480. * @details By default runs forward pass for the whole network.
  481. *
  482. * This is an asynchronous version of forward(const String&).
  483. * dnn::DNN_BACKEND_INFERENCE_ENGINE backend is required.
  484. */
  485. CV_WRAP AsyncArray forwardAsync(const String& outputName = String());
  486. /** @brief Runs forward pass to compute output of layer with name @p outputName.
  487. * @param outputBlobs contains all output blobs for specified layer.
  488. * @param outputName name for layer which output is needed to get
  489. * @details If @p outputName is empty, runs forward pass for the whole network.
  490. */
  491. CV_WRAP void forward(OutputArrayOfArrays outputBlobs, const String& outputName = String());
  492. /** @brief Runs forward pass to compute outputs of layers listed in @p outBlobNames.
  493. * @param outputBlobs contains blobs for first outputs of specified layers.
  494. * @param outBlobNames names for layers which outputs are needed to get
  495. */
  496. CV_WRAP void forward(OutputArrayOfArrays outputBlobs,
  497. const std::vector<String>& outBlobNames);
  498. /** @brief Runs forward pass to compute outputs of layers listed in @p outBlobNames.
  499. * @param outputBlobs contains all output blobs for each layer specified in @p outBlobNames.
  500. * @param outBlobNames names for layers which outputs are needed to get
  501. */
  502. CV_WRAP_AS(forwardAndRetrieve) void forward(CV_OUT std::vector<std::vector<Mat> >& outputBlobs,
  503. const std::vector<String>& outBlobNames);
  504. /** @brief Returns a quantized Net from a floating-point Net.
  505. * @param calibData Calibration data to compute the quantization parameters.
  506. * @param inputsDtype Datatype of quantized net's inputs. Can be CV_32F or CV_8S.
  507. * @param outputsDtype Datatype of quantized net's outputs. Can be CV_32F or CV_8S.
  508. */
  509. CV_WRAP Net quantize(InputArrayOfArrays calibData, int inputsDtype, int outputsDtype);
  510. /** @brief Returns input scale and zeropoint for a quantized Net.
  511. * @param scales output parameter for returning input scales.
  512. * @param zeropoints output parameter for returning input zeropoints.
  513. */
  514. CV_WRAP void getInputDetails(CV_OUT std::vector<float>& scales, CV_OUT std::vector<int>& zeropoints) const;
  515. /** @brief Returns output scale and zeropoint for a quantized Net.
  516. * @param scales output parameter for returning output scales.
  517. * @param zeropoints output parameter for returning output zeropoints.
  518. */
  519. CV_WRAP void getOutputDetails(CV_OUT std::vector<float>& scales, CV_OUT std::vector<int>& zeropoints) const;
  520. /**
  521. * @brief Compile Halide layers.
  522. * @param[in] scheduler Path to YAML file with scheduling directives.
  523. * @see setPreferableBackend
  524. *
  525. * Schedule layers that support Halide backend. Then compile them for
  526. * specific target. For layers that not represented in scheduling file
  527. * or if no manual scheduling used at all, automatic scheduling will be applied.
  528. */
  529. CV_WRAP void setHalideScheduler(const String& scheduler);
  530. /**
  531. * @brief Ask network to use specific computation backend where it supported.
  532. * @param[in] backendId backend identifier.
  533. * @see Backend
  534. *
  535. * If OpenCV is compiled with Intel's Inference Engine library, DNN_BACKEND_DEFAULT
  536. * means DNN_BACKEND_INFERENCE_ENGINE. Otherwise it equals to DNN_BACKEND_OPENCV.
  537. */
  538. CV_WRAP void setPreferableBackend(int backendId);
  539. /**
  540. * @brief Ask network to make computations on specific target device.
  541. * @param[in] targetId target identifier.
  542. * @see Target
  543. *
  544. * List of supported combinations backend / target:
  545. * | | DNN_BACKEND_OPENCV | DNN_BACKEND_INFERENCE_ENGINE | DNN_BACKEND_HALIDE | DNN_BACKEND_CUDA |
  546. * |------------------------|--------------------|------------------------------|--------------------|-------------------|
  547. * | DNN_TARGET_CPU | + | + | + | |
  548. * | DNN_TARGET_OPENCL | + | + | + | |
  549. * | DNN_TARGET_OPENCL_FP16 | + | + | | |
  550. * | DNN_TARGET_MYRIAD | | + | | |
  551. * | DNN_TARGET_FPGA | | + | | |
  552. * | DNN_TARGET_CUDA | | | | + |
  553. * | DNN_TARGET_CUDA_FP16 | | | | + |
  554. * | DNN_TARGET_HDDL | | + | | |
  555. */
  556. CV_WRAP void setPreferableTarget(int targetId);
  557. /** @brief Sets the new input value for the network
  558. * @param blob A new blob. Should have CV_32F or CV_8U depth.
  559. * @param name A name of input layer.
  560. * @param scalefactor An optional normalization scale.
  561. * @param mean An optional mean subtraction values.
  562. * @see connect(String, String) to know format of the descriptor.
  563. *
  564. * If scale or mean values are specified, a final input blob is computed
  565. * as:
  566. * \f[input(n,c,h,w) = scalefactor \times (blob(n,c,h,w) - mean_c)\f]
  567. */
  568. CV_WRAP void setInput(InputArray blob, const String& name = "",
  569. double scalefactor = 1.0, const Scalar& mean = Scalar());
  570. /** @brief Sets the new value for the learned param of the layer.
  571. * @param layer name or id of the layer.
  572. * @param numParam index of the layer parameter in the Layer::blobs array.
  573. * @param blob the new value.
  574. * @see Layer::blobs
  575. * @note If shape of the new blob differs from the previous shape,
  576. * then the following forward pass may fail.
  577. */
  578. CV_WRAP void setParam(LayerId layer, int numParam, const Mat &blob);
  579. /** @brief Returns parameter blob of the layer.
  580. * @param layer name or id of the layer.
  581. * @param numParam index of the layer parameter in the Layer::blobs array.
  582. * @see Layer::blobs
  583. */
  584. CV_WRAP Mat getParam(LayerId layer, int numParam = 0);
  585. /** @brief Returns indexes of layers with unconnected outputs.
  586. */
  587. CV_WRAP std::vector<int> getUnconnectedOutLayers() const;
  588. /** @brief Returns names of layers with unconnected outputs.
  589. */
  590. CV_WRAP std::vector<String> getUnconnectedOutLayersNames() const;
  591. /** @brief Returns input and output shapes for all layers in loaded model;
  592. * preliminary inferencing isn't necessary.
  593. * @param netInputShapes shapes for all input blobs in net input layer.
  594. * @param layersIds output parameter for layer IDs.
  595. * @param inLayersShapes output parameter for input layers shapes;
  596. * order is the same as in layersIds
  597. * @param outLayersShapes output parameter for output layers shapes;
  598. * order is the same as in layersIds
  599. */
  600. CV_WRAP void getLayersShapes(const std::vector<MatShape>& netInputShapes,
  601. CV_OUT std::vector<int>& layersIds,
  602. CV_OUT std::vector<std::vector<MatShape> >& inLayersShapes,
  603. CV_OUT std::vector<std::vector<MatShape> >& outLayersShapes) const;
  604. /** @overload */
  605. CV_WRAP void getLayersShapes(const MatShape& netInputShape,
  606. CV_OUT std::vector<int>& layersIds,
  607. CV_OUT std::vector<std::vector<MatShape> >& inLayersShapes,
  608. CV_OUT std::vector<std::vector<MatShape> >& outLayersShapes) const;
  609. /** @brief Returns input and output shapes for layer with specified
  610. * id in loaded model; preliminary inferencing isn't necessary.
  611. * @param netInputShape shape input blob in net input layer.
  612. * @param layerId id for layer.
  613. * @param inLayerShapes output parameter for input layers shapes;
  614. * order is the same as in layersIds
  615. * @param outLayerShapes output parameter for output layers shapes;
  616. * order is the same as in layersIds
  617. */
  618. void getLayerShapes(const MatShape& netInputShape,
  619. const int layerId,
  620. CV_OUT std::vector<MatShape>& inLayerShapes,
  621. CV_OUT std::vector<MatShape>& outLayerShapes) const; // FIXIT: CV_WRAP
  622. /** @overload */
  623. void getLayerShapes(const std::vector<MatShape>& netInputShapes,
  624. const int layerId,
  625. CV_OUT std::vector<MatShape>& inLayerShapes,
  626. CV_OUT std::vector<MatShape>& outLayerShapes) const; // FIXIT: CV_WRAP
  627. /** @brief Computes FLOP for whole loaded model with specified input shapes.
  628. * @param netInputShapes vector of shapes for all net inputs.
  629. * @returns computed FLOP.
  630. */
  631. CV_WRAP int64 getFLOPS(const std::vector<MatShape>& netInputShapes) const;
  632. /** @overload */
  633. CV_WRAP int64 getFLOPS(const MatShape& netInputShape) const;
  634. /** @overload */
  635. CV_WRAP int64 getFLOPS(const int layerId,
  636. const std::vector<MatShape>& netInputShapes) const;
  637. /** @overload */
  638. CV_WRAP int64 getFLOPS(const int layerId,
  639. const MatShape& netInputShape) const;
  640. /** @brief Returns list of types for layer used in model.
  641. * @param layersTypes output parameter for returning types.
  642. */
  643. CV_WRAP void getLayerTypes(CV_OUT std::vector<String>& layersTypes) const;
  644. /** @brief Returns count of layers of specified type.
  645. * @param layerType type.
  646. * @returns count of layers
  647. */
  648. CV_WRAP int getLayersCount(const String& layerType) const;
  649. /** @brief Computes bytes number which are required to store
  650. * all weights and intermediate blobs for model.
  651. * @param netInputShapes vector of shapes for all net inputs.
  652. * @param weights output parameter to store resulting bytes for weights.
  653. * @param blobs output parameter to store resulting bytes for intermediate blobs.
  654. */
  655. void getMemoryConsumption(const std::vector<MatShape>& netInputShapes,
  656. CV_OUT size_t& weights, CV_OUT size_t& blobs) const; // FIXIT: CV_WRAP
  657. /** @overload */
  658. CV_WRAP void getMemoryConsumption(const MatShape& netInputShape,
  659. CV_OUT size_t& weights, CV_OUT size_t& blobs) const;
  660. /** @overload */
  661. CV_WRAP void getMemoryConsumption(const int layerId,
  662. const std::vector<MatShape>& netInputShapes,
  663. CV_OUT size_t& weights, CV_OUT size_t& blobs) const;
  664. /** @overload */
  665. CV_WRAP void getMemoryConsumption(const int layerId,
  666. const MatShape& netInputShape,
  667. CV_OUT size_t& weights, CV_OUT size_t& blobs) const;
  668. /** @brief Computes bytes number which are required to store
  669. * all weights and intermediate blobs for each layer.
  670. * @param netInputShapes vector of shapes for all net inputs.
  671. * @param layerIds output vector to save layer IDs.
  672. * @param weights output parameter to store resulting bytes for weights.
  673. * @param blobs output parameter to store resulting bytes for intermediate blobs.
  674. */
  675. void getMemoryConsumption(const std::vector<MatShape>& netInputShapes,
  676. CV_OUT std::vector<int>& layerIds,
  677. CV_OUT std::vector<size_t>& weights,
  678. CV_OUT std::vector<size_t>& blobs) const; // FIXIT: CV_WRAP
  679. /** @overload */
  680. void getMemoryConsumption(const MatShape& netInputShape,
  681. CV_OUT std::vector<int>& layerIds,
  682. CV_OUT std::vector<size_t>& weights,
  683. CV_OUT std::vector<size_t>& blobs) const; // FIXIT: CV_WRAP
  684. /** @brief Enables or disables layer fusion in the network.
  685. * @param fusion true to enable the fusion, false to disable. The fusion is enabled by default.
  686. */
  687. CV_WRAP void enableFusion(bool fusion);
  688. /** @brief Returns overall time for inference and timings (in ticks) for layers.
  689. *
  690. * Indexes in returned vector correspond to layers ids. Some layers can be fused with others,
  691. * in this case zero ticks count will be return for that skipped layers. Supported by DNN_BACKEND_OPENCV on DNN_TARGET_CPU only.
  692. *
  693. * @param[out] timings vector for tick timings for all layers.
  694. * @return overall ticks for model inference.
  695. */
  696. CV_WRAP int64 getPerfProfile(CV_OUT std::vector<double>& timings);
  697. private:
  698. struct Impl;
  699. Ptr<Impl> impl;
  700. };
  701. /** @brief Reads a network model stored in <a href="https://pjreddie.com/darknet/">Darknet</a> model files.
  702. * @param cfgFile path to the .cfg file with text description of the network architecture.
  703. * @param darknetModel path to the .weights file with learned network.
  704. * @returns Network object that ready to do forward, throw an exception in failure cases.
  705. * @returns Net object.
  706. */
  707. CV_EXPORTS_W Net readNetFromDarknet(const String &cfgFile, const String &darknetModel = String());
  708. /** @brief Reads a network model stored in <a href="https://pjreddie.com/darknet/">Darknet</a> model files.
  709. * @param bufferCfg A buffer contains a content of .cfg file with text description of the network architecture.
  710. * @param bufferModel A buffer contains a content of .weights file with learned network.
  711. * @returns Net object.
  712. */
  713. CV_EXPORTS_W Net readNetFromDarknet(const std::vector<uchar>& bufferCfg,
  714. const std::vector<uchar>& bufferModel = std::vector<uchar>());
  715. /** @brief Reads a network model stored in <a href="https://pjreddie.com/darknet/">Darknet</a> model files.
  716. * @param bufferCfg A buffer contains a content of .cfg file with text description of the network architecture.
  717. * @param lenCfg Number of bytes to read from bufferCfg
  718. * @param bufferModel A buffer contains a content of .weights file with learned network.
  719. * @param lenModel Number of bytes to read from bufferModel
  720. * @returns Net object.
  721. */
  722. CV_EXPORTS Net readNetFromDarknet(const char *bufferCfg, size_t lenCfg,
  723. const char *bufferModel = NULL, size_t lenModel = 0);
  724. /** @brief Reads a network model stored in <a href="http://caffe.berkeleyvision.org">Caffe</a> framework's format.
  725. * @param prototxt path to the .prototxt file with text description of the network architecture.
  726. * @param caffeModel path to the .caffemodel file with learned network.
  727. * @returns Net object.
  728. */
  729. CV_EXPORTS_W Net readNetFromCaffe(const String &prototxt, const String &caffeModel = String());
  730. /** @brief Reads a network model stored in Caffe model in memory.
  731. * @param bufferProto buffer containing the content of the .prototxt file
  732. * @param bufferModel buffer containing the content of the .caffemodel file
  733. * @returns Net object.
  734. */
  735. CV_EXPORTS_W Net readNetFromCaffe(const std::vector<uchar>& bufferProto,
  736. const std::vector<uchar>& bufferModel = std::vector<uchar>());
  737. /** @brief Reads a network model stored in Caffe model in memory.
  738. * @details This is an overloaded member function, provided for convenience.
  739. * It differs from the above function only in what argument(s) it accepts.
  740. * @param bufferProto buffer containing the content of the .prototxt file
  741. * @param lenProto length of bufferProto
  742. * @param bufferModel buffer containing the content of the .caffemodel file
  743. * @param lenModel length of bufferModel
  744. * @returns Net object.
  745. */
  746. CV_EXPORTS Net readNetFromCaffe(const char *bufferProto, size_t lenProto,
  747. const char *bufferModel = NULL, size_t lenModel = 0);
  748. /** @brief Reads a network model stored in <a href="https://www.tensorflow.org/">TensorFlow</a> framework's format.
  749. * @param model path to the .pb file with binary protobuf description of the network architecture
  750. * @param config path to the .pbtxt file that contains text graph definition in protobuf format.
  751. * Resulting Net object is built by text graph using weights from a binary one that
  752. * let us make it more flexible.
  753. * @returns Net object.
  754. */
  755. CV_EXPORTS_W Net readNetFromTensorflow(const String &model, const String &config = String());
  756. /** @brief Reads a network model stored in <a href="https://www.tensorflow.org/">TensorFlow</a> framework's format.
  757. * @param bufferModel buffer containing the content of the pb file
  758. * @param bufferConfig buffer containing the content of the pbtxt file
  759. * @returns Net object.
  760. */
  761. CV_EXPORTS_W Net readNetFromTensorflow(const std::vector<uchar>& bufferModel,
  762. const std::vector<uchar>& bufferConfig = std::vector<uchar>());
  763. /** @brief Reads a network model stored in <a href="https://www.tensorflow.org/">TensorFlow</a> framework's format.
  764. * @details This is an overloaded member function, provided for convenience.
  765. * It differs from the above function only in what argument(s) it accepts.
  766. * @param bufferModel buffer containing the content of the pb file
  767. * @param lenModel length of bufferModel
  768. * @param bufferConfig buffer containing the content of the pbtxt file
  769. * @param lenConfig length of bufferConfig
  770. */
  771. CV_EXPORTS Net readNetFromTensorflow(const char *bufferModel, size_t lenModel,
  772. const char *bufferConfig = NULL, size_t lenConfig = 0);
  773. /**
  774. * @brief Reads a network model stored in <a href="http://torch.ch">Torch7</a> framework's format.
  775. * @param model path to the file, dumped from Torch by using torch.save() function.
  776. * @param isBinary specifies whether the network was serialized in ascii mode or binary.
  777. * @param evaluate specifies testing phase of network. If true, it's similar to evaluate() method in Torch.
  778. * @returns Net object.
  779. *
  780. * @note Ascii mode of Torch serializer is more preferable, because binary mode extensively use `long` type of C language,
  781. * which has various bit-length on different systems.
  782. *
  783. * The loading file must contain serialized <a href="https://github.com/torch/nn/blob/master/doc/module.md">nn.Module</a> object
  784. * with importing network. Try to eliminate a custom objects from serialazing data to avoid importing errors.
  785. *
  786. * List of supported layers (i.e. object instances derived from Torch nn.Module class):
  787. * - nn.Sequential
  788. * - nn.Parallel
  789. * - nn.Concat
  790. * - nn.Linear
  791. * - nn.SpatialConvolution
  792. * - nn.SpatialMaxPooling, nn.SpatialAveragePooling
  793. * - nn.ReLU, nn.TanH, nn.Sigmoid
  794. * - nn.Reshape
  795. * - nn.SoftMax, nn.LogSoftMax
  796. *
  797. * Also some equivalents of these classes from cunn, cudnn, and fbcunn may be successfully imported.
  798. */
  799. CV_EXPORTS_W Net readNetFromTorch(const String &model, bool isBinary = true, bool evaluate = true);
  800. /**
  801. * @brief Read deep learning network represented in one of the supported formats.
  802. * @param[in] model Binary file contains trained weights. The following file
  803. * extensions are expected for models from different frameworks:
  804. * * `*.caffemodel` (Caffe, http://caffe.berkeleyvision.org/)
  805. * * `*.pb` (TensorFlow, https://www.tensorflow.org/)
  806. * * `*.t7` | `*.net` (Torch, http://torch.ch/)
  807. * * `*.weights` (Darknet, https://pjreddie.com/darknet/)
  808. * * `*.bin` (DLDT, https://software.intel.com/openvino-toolkit)
  809. * * `*.onnx` (ONNX, https://onnx.ai/)
  810. * @param[in] config Text file contains network configuration. It could be a
  811. * file with the following extensions:
  812. * * `*.prototxt` (Caffe, http://caffe.berkeleyvision.org/)
  813. * * `*.pbtxt` (TensorFlow, https://www.tensorflow.org/)
  814. * * `*.cfg` (Darknet, https://pjreddie.com/darknet/)
  815. * * `*.xml` (DLDT, https://software.intel.com/openvino-toolkit)
  816. * @param[in] framework Explicit framework name tag to determine a format.
  817. * @returns Net object.
  818. *
  819. * This function automatically detects an origin framework of trained model
  820. * and calls an appropriate function such @ref readNetFromCaffe, @ref readNetFromTensorflow,
  821. * @ref readNetFromTorch or @ref readNetFromDarknet. An order of @p model and @p config
  822. * arguments does not matter.
  823. */
  824. CV_EXPORTS_W Net readNet(const String& model, const String& config = "", const String& framework = "");
  825. /**
  826. * @brief Read deep learning network represented in one of the supported formats.
  827. * @details This is an overloaded member function, provided for convenience.
  828. * It differs from the above function only in what argument(s) it accepts.
  829. * @param[in] framework Name of origin framework.
  830. * @param[in] bufferModel A buffer with a content of binary file with weights
  831. * @param[in] bufferConfig A buffer with a content of text file contains network configuration.
  832. * @returns Net object.
  833. */
  834. CV_EXPORTS_W Net readNet(const String& framework, const std::vector<uchar>& bufferModel,
  835. const std::vector<uchar>& bufferConfig = std::vector<uchar>());
  836. /** @brief Loads blob which was serialized as torch.Tensor object of Torch7 framework.
  837. * @warning This function has the same limitations as readNetFromTorch().
  838. */
  839. CV_EXPORTS_W Mat readTorchBlob(const String &filename, bool isBinary = true);
  840. /** @brief Load a network from Intel's Model Optimizer intermediate representation.
  841. * @param[in] xml XML configuration file with network's topology.
  842. * @param[in] bin Binary file with trained weights.
  843. * @returns Net object.
  844. * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine
  845. * backend.
  846. */
  847. CV_EXPORTS_W
  848. Net readNetFromModelOptimizer(const String &xml, const String &bin);
  849. /** @brief Load a network from Intel's Model Optimizer intermediate representation.
  850. * @param[in] bufferModelConfig Buffer contains XML configuration with network's topology.
  851. * @param[in] bufferWeights Buffer contains binary data with trained weights.
  852. * @returns Net object.
  853. * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine
  854. * backend.
  855. */
  856. CV_EXPORTS_W
  857. Net readNetFromModelOptimizer(const std::vector<uchar>& bufferModelConfig, const std::vector<uchar>& bufferWeights);
  858. /** @brief Load a network from Intel's Model Optimizer intermediate representation.
  859. * @param[in] bufferModelConfigPtr Pointer to buffer which contains XML configuration with network's topology.
  860. * @param[in] bufferModelConfigSize Binary size of XML configuration data.
  861. * @param[in] bufferWeightsPtr Pointer to buffer which contains binary data with trained weights.
  862. * @param[in] bufferWeightsSize Binary size of trained weights data.
  863. * @returns Net object.
  864. * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine
  865. * backend.
  866. */
  867. CV_EXPORTS
  868. Net readNetFromModelOptimizer(const uchar* bufferModelConfigPtr, size_t bufferModelConfigSize,
  869. const uchar* bufferWeightsPtr, size_t bufferWeightsSize);
  870. /** @brief Reads a network model <a href="https://onnx.ai/">ONNX</a>.
  871. * @param onnxFile path to the .onnx file with text description of the network architecture.
  872. * @returns Network object that ready to do forward, throw an exception in failure cases.
  873. */
  874. CV_EXPORTS_W Net readNetFromONNX(const String &onnxFile);
  875. /** @brief Reads a network model from <a href="https://onnx.ai/">ONNX</a>
  876. * in-memory buffer.
  877. * @param buffer memory address of the first byte of the buffer.
  878. * @param sizeBuffer size of the buffer.
  879. * @returns Network object that ready to do forward, throw an exception
  880. * in failure cases.
  881. */
  882. CV_EXPORTS Net readNetFromONNX(const char* buffer, size_t sizeBuffer);
  883. /** @brief Reads a network model from <a href="https://onnx.ai/">ONNX</a>
  884. * in-memory buffer.
  885. * @param buffer in-memory buffer that stores the ONNX model bytes.
  886. * @returns Network object that ready to do forward, throw an exception
  887. * in failure cases.
  888. */
  889. CV_EXPORTS_W Net readNetFromONNX(const std::vector<uchar>& buffer);
  890. /** @brief Creates blob from .pb file.
  891. * @param path to the .pb file with input tensor.
  892. * @returns Mat.
  893. */
  894. CV_EXPORTS_W Mat readTensorFromONNX(const String& path);
  895. /** @brief Creates 4-dimensional blob from image. Optionally resizes and crops @p image from center,
  896. * subtract @p mean values, scales values by @p scalefactor, swap Blue and Red channels.
  897. * @param image input image (with 1-, 3- or 4-channels).
  898. * @param size spatial size for output image
  899. * @param mean scalar with mean values which are subtracted from channels. Values are intended
  900. * to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true.
  901. * @param scalefactor multiplier for @p image values.
  902. * @param swapRB flag which indicates that swap first and last channels
  903. * in 3-channel image is necessary.
  904. * @param crop flag which indicates whether image will be cropped after resize or not
  905. * @param ddepth Depth of output blob. Choose CV_32F or CV_8U.
  906. * @details if @p crop is true, input image is resized so one side after resize is equal to corresponding
  907. * dimension in @p size and another one is equal or larger. Then, crop from the center is performed.
  908. * If @p crop is false, direct resize without cropping and preserving aspect ratio is performed.
  909. * @returns 4-dimensional Mat with NCHW dimensions order.
  910. */
  911. CV_EXPORTS_W Mat blobFromImage(InputArray image, double scalefactor=1.0, const Size& size = Size(),
  912. const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false,
  913. int ddepth=CV_32F);
  914. /** @brief Creates 4-dimensional blob from image.
  915. * @details This is an overloaded member function, provided for convenience.
  916. * It differs from the above function only in what argument(s) it accepts.
  917. */
  918. CV_EXPORTS void blobFromImage(InputArray image, OutputArray blob, double scalefactor=1.0,
  919. const Size& size = Size(), const Scalar& mean = Scalar(),
  920. bool swapRB=false, bool crop=false, int ddepth=CV_32F);
  921. /** @brief Creates 4-dimensional blob from series of images. Optionally resizes and
  922. * crops @p images from center, subtract @p mean values, scales values by @p scalefactor,
  923. * swap Blue and Red channels.
  924. * @param images input images (all with 1-, 3- or 4-channels).
  925. * @param size spatial size for output image
  926. * @param mean scalar with mean values which are subtracted from channels. Values are intended
  927. * to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true.
  928. * @param scalefactor multiplier for @p images values.
  929. * @param swapRB flag which indicates that swap first and last channels
  930. * in 3-channel image is necessary.
  931. * @param crop flag which indicates whether image will be cropped after resize or not
  932. * @param ddepth Depth of output blob. Choose CV_32F or CV_8U.
  933. * @details if @p crop is true, input image is resized so one side after resize is equal to corresponding
  934. * dimension in @p size and another one is equal or larger. Then, crop from the center is performed.
  935. * If @p crop is false, direct resize without cropping and preserving aspect ratio is performed.
  936. * @returns 4-dimensional Mat with NCHW dimensions order.
  937. */
  938. CV_EXPORTS_W Mat blobFromImages(InputArrayOfArrays images, double scalefactor=1.0,
  939. Size size = Size(), const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false,
  940. int ddepth=CV_32F);
  941. /** @brief Creates 4-dimensional blob from series of images.
  942. * @details This is an overloaded member function, provided for convenience.
  943. * It differs from the above function only in what argument(s) it accepts.
  944. */
  945. CV_EXPORTS void blobFromImages(InputArrayOfArrays images, OutputArray blob,
  946. double scalefactor=1.0, Size size = Size(),
  947. const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false,
  948. int ddepth=CV_32F);
  949. /** @brief Parse a 4D blob and output the images it contains as 2D arrays through a simpler data structure
  950. * (std::vector<cv::Mat>).
  951. * @param[in] blob_ 4 dimensional array (images, channels, height, width) in floating point precision (CV_32F) from
  952. * which you would like to extract the images.
  953. * @param[out] images_ array of 2D Mat containing the images extracted from the blob in floating point precision
  954. * (CV_32F). They are non normalized neither mean added. The number of returned images equals the first dimension
  955. * of the blob (batch size). Every image has a number of channels equals to the second dimension of the blob (depth).
  956. */
  957. CV_EXPORTS_W void imagesFromBlob(const cv::Mat& blob_, OutputArrayOfArrays images_);
  958. /** @brief Convert all weights of Caffe network to half precision floating point.
  959. * @param src Path to origin model from Caffe framework contains single
  960. * precision floating point weights (usually has `.caffemodel` extension).
  961. * @param dst Path to destination model with updated weights.
  962. * @param layersTypes Set of layers types which parameters will be converted.
  963. * By default, converts only Convolutional and Fully-Connected layers'
  964. * weights.
  965. *
  966. * @note Shrinked model has no origin float32 weights so it can't be used
  967. * in origin Caffe framework anymore. However the structure of data
  968. * is taken from NVidia's Caffe fork: https://github.com/NVIDIA/caffe.
  969. * So the resulting model may be used there.
  970. */
  971. CV_EXPORTS_W void shrinkCaffeModel(const String& src, const String& dst,
  972. const std::vector<String>& layersTypes = std::vector<String>());
  973. /** @brief Create a text representation for a binary network stored in protocol buffer format.
  974. * @param[in] model A path to binary network.
  975. * @param[in] output A path to output text file to be created.
  976. *
  977. * @note To reduce output file size, trained weights are not included.
  978. */
  979. CV_EXPORTS_W void writeTextGraph(const String& model, const String& output);
  980. /** @brief Performs non maximum suppression given boxes and corresponding scores.
  981. * @param bboxes a set of bounding boxes to apply NMS.
  982. * @param scores a set of corresponding confidences.
  983. * @param score_threshold a threshold used to filter boxes by score.
  984. * @param nms_threshold a threshold used in non maximum suppression.
  985. * @param indices the kept indices of bboxes after NMS.
  986. * @param eta a coefficient in adaptive threshold formula: \f$nms\_threshold_{i+1}=eta\cdot nms\_threshold_i\f$.
  987. * @param top_k if `>0`, keep at most @p top_k picked indices.
  988. */
  989. CV_EXPORTS void NMSBoxes(const std::vector<Rect>& bboxes, const std::vector<float>& scores,
  990. const float score_threshold, const float nms_threshold,
  991. CV_OUT std::vector<int>& indices,
  992. const float eta = 1.f, const int top_k = 0);
  993. CV_EXPORTS_W void NMSBoxes(const std::vector<Rect2d>& bboxes, const std::vector<float>& scores,
  994. const float score_threshold, const float nms_threshold,
  995. CV_OUT std::vector<int>& indices,
  996. const float eta = 1.f, const int top_k = 0);
  997. CV_EXPORTS_AS(NMSBoxesRotated) void NMSBoxes(const std::vector<RotatedRect>& bboxes, const std::vector<float>& scores,
  998. const float score_threshold, const float nms_threshold,
  999. CV_OUT std::vector<int>& indices,
  1000. const float eta = 1.f, const int top_k = 0);
  1001. /**
  1002. * @brief Enum of Soft NMS methods.
  1003. * @see softNMSBoxes
  1004. */
  1005. enum class SoftNMSMethod
  1006. {
  1007. SOFTNMS_LINEAR = 1,
  1008. SOFTNMS_GAUSSIAN = 2
  1009. };
  1010. /** @brief Performs soft non maximum suppression given boxes and corresponding scores.
  1011. * Reference: https://arxiv.org/abs/1704.04503
  1012. * @param bboxes a set of bounding boxes to apply Soft NMS.
  1013. * @param scores a set of corresponding confidences.
  1014. * @param updated_scores a set of corresponding updated confidences.
  1015. * @param score_threshold a threshold used to filter boxes by score.
  1016. * @param nms_threshold a threshold used in non maximum suppression.
  1017. * @param indices the kept indices of bboxes after NMS.
  1018. * @param top_k keep at most @p top_k picked indices.
  1019. * @param sigma parameter of Gaussian weighting.
  1020. * @param method Gaussian or linear.
  1021. * @see SoftNMSMethod
  1022. */
  1023. CV_EXPORTS_W void softNMSBoxes(const std::vector<Rect>& bboxes,
  1024. const std::vector<float>& scores,
  1025. CV_OUT std::vector<float>& updated_scores,
  1026. const float score_threshold,
  1027. const float nms_threshold,
  1028. CV_OUT std::vector<int>& indices,
  1029. size_t top_k = 0,
  1030. const float sigma = 0.5,
  1031. SoftNMSMethod method = SoftNMSMethod::SOFTNMS_GAUSSIAN);
  1032. /** @brief This class is presented high-level API for neural networks.
  1033. *
  1034. * Model allows to set params for preprocessing input image.
  1035. * Model creates net from file with trained weights and config,
  1036. * sets preprocessing input and runs forward pass.
  1037. */
  1038. class CV_EXPORTS_W_SIMPLE Model
  1039. {
  1040. public:
  1041. CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first)
  1042. Model();
  1043. Model(const Model&) = default;
  1044. Model(Model&&) = default;
  1045. Model& operator=(const Model&) = default;
  1046. Model& operator=(Model&&) = default;
  1047. /**
  1048. * @brief Create model from deep learning network represented in one of the supported formats.
  1049. * An order of @p model and @p config arguments does not matter.
  1050. * @param[in] model Binary file contains trained weights.
  1051. * @param[in] config Text file contains network configuration.
  1052. */
  1053. CV_WRAP Model(const String& model, const String& config = "");
  1054. /**
  1055. * @brief Create model from deep learning network.
  1056. * @param[in] network Net object.
  1057. */
  1058. CV_WRAP Model(const Net& network);
  1059. /** @brief Set input size for frame.
  1060. * @param[in] size New input size.
  1061. * @note If shape of the new blob less than 0, then frame size not change.
  1062. */
  1063. CV_WRAP Model& setInputSize(const Size& size);
  1064. /** @overload
  1065. * @param[in] width New input width.
  1066. * @param[in] height New input height.
  1067. */
  1068. CV_WRAP inline
  1069. Model& setInputSize(int width, int height) { return setInputSize(Size(width, height)); }
  1070. /** @brief Set mean value for frame.
  1071. * @param[in] mean Scalar with mean values which are subtracted from channels.
  1072. */
  1073. CV_WRAP Model& setInputMean(const Scalar& mean);
  1074. /** @brief Set scalefactor value for frame.
  1075. * @param[in] scale Multiplier for frame values.
  1076. */
  1077. CV_WRAP Model& setInputScale(double scale);
  1078. /** @brief Set flag crop for frame.
  1079. * @param[in] crop Flag which indicates whether image will be cropped after resize or not.
  1080. */
  1081. CV_WRAP Model& setInputCrop(bool crop);
  1082. /** @brief Set flag swapRB for frame.
  1083. * @param[in] swapRB Flag which indicates that swap first and last channels.
  1084. */
  1085. CV_WRAP Model& setInputSwapRB(bool swapRB);
  1086. /** @brief Set preprocessing parameters for frame.
  1087. * @param[in] size New input size.
  1088. * @param[in] mean Scalar with mean values which are subtracted from channels.
  1089. * @param[in] scale Multiplier for frame values.
  1090. * @param[in] swapRB Flag which indicates that swap first and last channels.
  1091. * @param[in] crop Flag which indicates whether image will be cropped after resize or not.
  1092. * blob(n, c, y, x) = scale * resize( frame(y, x, c) ) - mean(c) )
  1093. */
  1094. CV_WRAP void setInputParams(double scale = 1.0, const Size& size = Size(),
  1095. const Scalar& mean = Scalar(), bool swapRB = false, bool crop = false);
  1096. /** @brief Given the @p input frame, create input blob, run net and return the output @p blobs.
  1097. * @param[in] frame The input image.
  1098. * @param[out] outs Allocated output blobs, which will store results of the computation.
  1099. */
  1100. CV_WRAP void predict(InputArray frame, OutputArrayOfArrays outs) const;
  1101. // ============================== Net proxy methods ==============================
  1102. // Never expose methods with network implementation details, like:
  1103. // - addLayer, addLayerToPrev, connect, setInputsNames, setInputShape, setParam, getParam
  1104. // - getLayer*, getUnconnectedOutLayers, getUnconnectedOutLayersNames, getLayersShapes
  1105. // - forward* methods, setInput
  1106. /// @sa Net::setPreferableBackend
  1107. CV_WRAP Model& setPreferableBackend(dnn::Backend backendId);
  1108. /// @sa Net::setPreferableTarget
  1109. CV_WRAP Model& setPreferableTarget(dnn::Target targetId);
  1110. CV_DEPRECATED_EXTERNAL
  1111. operator Net&() const { return getNetwork_(); }
  1112. //protected: - internal/tests usage only
  1113. Net& getNetwork_() const;
  1114. inline Net& getNetwork_() { return const_cast<const Model*>(this)->getNetwork_(); }
  1115. struct Impl;
  1116. inline Impl* getImpl() const { return impl.get(); }
  1117. inline Impl& getImplRef() const { CV_DbgAssert(impl); return *impl.get(); }
  1118. protected:
  1119. Ptr<Impl> impl;
  1120. };
  1121. /** @brief This class represents high-level API for classification models.
  1122. *
  1123. * ClassificationModel allows to set params for preprocessing input image.
  1124. * ClassificationModel creates net from file with trained weights and config,
  1125. * sets preprocessing input, runs forward pass and return top-1 prediction.
  1126. */
  1127. class CV_EXPORTS_W_SIMPLE ClassificationModel : public Model
  1128. {
  1129. public:
  1130. /**
  1131. * @brief Create classification model from network represented in one of the supported formats.
  1132. * An order of @p model and @p config arguments does not matter.
  1133. * @param[in] model Binary file contains trained weights.
  1134. * @param[in] config Text file contains network configuration.
  1135. */
  1136. CV_WRAP ClassificationModel(const String& model, const String& config = "");
  1137. /**
  1138. * @brief Create model from deep learning network.
  1139. * @param[in] network Net object.
  1140. */
  1141. CV_WRAP ClassificationModel(const Net& network);
  1142. /** @brief Given the @p input frame, create input blob, run net and return top-1 prediction.
  1143. * @param[in] frame The input image.
  1144. */
  1145. std::pair<int, float> classify(InputArray frame);
  1146. /** @overload */
  1147. CV_WRAP void classify(InputArray frame, CV_OUT int& classId, CV_OUT float& conf);
  1148. };
  1149. /** @brief This class represents high-level API for keypoints models
  1150. *
  1151. * KeypointsModel allows to set params for preprocessing input image.
  1152. * KeypointsModel creates net from file with trained weights and config,
  1153. * sets preprocessing input, runs forward pass and returns the x and y coordinates of each detected keypoint
  1154. */
  1155. class CV_EXPORTS_W_SIMPLE KeypointsModel: public Model
  1156. {
  1157. public:
  1158. /**
  1159. * @brief Create keypoints model from network represented in one of the supported formats.
  1160. * An order of @p model and @p config arguments does not matter.
  1161. * @param[in] model Binary file contains trained weights.
  1162. * @param[in] config Text file contains network configuration.
  1163. */
  1164. CV_WRAP KeypointsModel(const String& model, const String& config = "");
  1165. /**
  1166. * @brief Create model from deep learning network.
  1167. * @param[in] network Net object.
  1168. */
  1169. CV_WRAP KeypointsModel(const Net& network);
  1170. /** @brief Given the @p input frame, create input blob, run net
  1171. * @param[in] frame The input image.
  1172. * @param thresh minimum confidence threshold to select a keypoint
  1173. * @returns a vector holding the x and y coordinates of each detected keypoint
  1174. *
  1175. */
  1176. CV_WRAP std::vector<Point2f> estimate(InputArray frame, float thresh=0.5);
  1177. };
  1178. /** @brief This class represents high-level API for segmentation models
  1179. *
  1180. * SegmentationModel allows to set params for preprocessing input image.
  1181. * SegmentationModel creates net from file with trained weights and config,
  1182. * sets preprocessing input, runs forward pass and returns the class prediction for each pixel.
  1183. */
  1184. class CV_EXPORTS_W_SIMPLE SegmentationModel: public Model
  1185. {
  1186. public:
  1187. /**
  1188. * @brief Create segmentation model from network represented in one of the supported formats.
  1189. * An order of @p model and @p config arguments does not matter.
  1190. * @param[in] model Binary file contains trained weights.
  1191. * @param[in] config Text file contains network configuration.
  1192. */
  1193. CV_WRAP SegmentationModel(const String& model, const String& config = "");
  1194. /**
  1195. * @brief Create model from deep learning network.
  1196. * @param[in] network Net object.
  1197. */
  1198. CV_WRAP SegmentationModel(const Net& network);
  1199. /** @brief Given the @p input frame, create input blob, run net
  1200. * @param[in] frame The input image.
  1201. * @param[out] mask Allocated class prediction for each pixel
  1202. */
  1203. CV_WRAP void segment(InputArray frame, OutputArray mask);
  1204. };
  1205. /** @brief This class represents high-level API for object detection networks.
  1206. *
  1207. * DetectionModel allows to set params for preprocessing input image.
  1208. * DetectionModel creates net from file with trained weights and config,
  1209. * sets preprocessing input, runs forward pass and return result detections.
  1210. * For DetectionModel SSD, Faster R-CNN, YOLO topologies are supported.
  1211. */
  1212. class CV_EXPORTS_W_SIMPLE DetectionModel : public Model
  1213. {
  1214. public:
  1215. /**
  1216. * @brief Create detection model from network represented in one of the supported formats.
  1217. * An order of @p model and @p config arguments does not matter.
  1218. * @param[in] model Binary file contains trained weights.
  1219. * @param[in] config Text file contains network configuration.
  1220. */
  1221. CV_WRAP DetectionModel(const String& model, const String& config = "");
  1222. /**
  1223. * @brief Create model from deep learning network.
  1224. * @param[in] network Net object.
  1225. */
  1226. CV_WRAP DetectionModel(const Net& network);
  1227. CV_DEPRECATED_EXTERNAL // avoid using in C++ code (need to fix bindings first)
  1228. DetectionModel();
  1229. /**
  1230. * @brief nmsAcrossClasses defaults to false,
  1231. * such that when non max suppression is used during the detect() function, it will do so per-class.
  1232. * This function allows you to toggle this behaviour.
  1233. * @param[in] value The new value for nmsAcrossClasses
  1234. */
  1235. CV_WRAP DetectionModel& setNmsAcrossClasses(bool value);
  1236. /**
  1237. * @brief Getter for nmsAcrossClasses. This variable defaults to false,
  1238. * such that when non max suppression is used during the detect() function, it will do so only per-class
  1239. */
  1240. CV_WRAP bool getNmsAcrossClasses();
  1241. /** @brief Given the @p input frame, create input blob, run net and return result detections.
  1242. * @param[in] frame The input image.
  1243. * @param[out] classIds Class indexes in result detection.
  1244. * @param[out] confidences A set of corresponding confidences.
  1245. * @param[out] boxes A set of bounding boxes.
  1246. * @param[in] confThreshold A threshold used to filter boxes by confidences.
  1247. * @param[in] nmsThreshold A threshold used in non maximum suppression.
  1248. */
  1249. CV_WRAP void detect(InputArray frame, CV_OUT std::vector<int>& classIds,
  1250. CV_OUT std::vector<float>& confidences, CV_OUT std::vector<Rect>& boxes,
  1251. float confThreshold = 0.5f, float nmsThreshold = 0.0f);
  1252. };
  1253. /** @brief This class represents high-level API for text recognition networks.
  1254. *
  1255. * TextRecognitionModel allows to set params for preprocessing input image.
  1256. * TextRecognitionModel creates net from file with trained weights and config,
  1257. * sets preprocessing input, runs forward pass and return recognition result.
  1258. * For TextRecognitionModel, CRNN-CTC is supported.
  1259. */
  1260. class CV_EXPORTS_W_SIMPLE TextRecognitionModel : public Model
  1261. {
  1262. public:
  1263. CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first)
  1264. TextRecognitionModel();
  1265. /**
  1266. * @brief Create Text Recognition model from deep learning network
  1267. * Call setDecodeType() and setVocabulary() after constructor to initialize the decoding method
  1268. * @param[in] network Net object
  1269. */
  1270. CV_WRAP TextRecognitionModel(const Net& network);
  1271. /**
  1272. * @brief Create text recognition model from network represented in one of the supported formats
  1273. * Call setDecodeType() and setVocabulary() after constructor to initialize the decoding method
  1274. * @param[in] model Binary file contains trained weights
  1275. * @param[in] config Text file contains network configuration
  1276. */
  1277. CV_WRAP inline
  1278. TextRecognitionModel(const std::string& model, const std::string& config = "")
  1279. : TextRecognitionModel(readNet(model, config)) { /* nothing */ }
  1280. /**
  1281. * @brief Set the decoding method of translating the network output into string
  1282. * @param[in] decodeType The decoding method of translating the network output into string, currently supported type:
  1283. * - `"CTC-greedy"` greedy decoding for the output of CTC-based methods
  1284. * - `"CTC-prefix-beam-search"` Prefix beam search decoding for the output of CTC-based methods
  1285. */
  1286. CV_WRAP
  1287. TextRecognitionModel& setDecodeType(const std::string& decodeType);
  1288. /**
  1289. * @brief Get the decoding method
  1290. * @return the decoding method
  1291. */
  1292. CV_WRAP
  1293. const std::string& getDecodeType() const;
  1294. /**
  1295. * @brief Set the decoding method options for `"CTC-prefix-beam-search"` decode usage
  1296. * @param[in] beamSize Beam size for search
  1297. * @param[in] vocPruneSize Parameter to optimize big vocabulary search,
  1298. * only take top @p vocPruneSize tokens in each search step, @p vocPruneSize <= 0 stands for disable this prune.
  1299. */
  1300. CV_WRAP
  1301. TextRecognitionModel& setDecodeOptsCTCPrefixBeamSearch(int beamSize, int vocPruneSize = 0);
  1302. /**
  1303. * @brief Set the vocabulary for recognition.
  1304. * @param[in] vocabulary the associated vocabulary of the network.
  1305. */
  1306. CV_WRAP
  1307. TextRecognitionModel& setVocabulary(const std::vector<std::string>& vocabulary);
  1308. /**
  1309. * @brief Get the vocabulary for recognition.
  1310. * @return vocabulary the associated vocabulary
  1311. */
  1312. CV_WRAP
  1313. const std::vector<std::string>& getVocabulary() const;
  1314. /**
  1315. * @brief Given the @p input frame, create input blob, run net and return recognition result
  1316. * @param[in] frame The input image
  1317. * @return The text recognition result
  1318. */
  1319. CV_WRAP
  1320. std::string recognize(InputArray frame) const;
  1321. /**
  1322. * @brief Given the @p input frame, create input blob, run net and return recognition result
  1323. * @param[in] frame The input image
  1324. * @param[in] roiRects List of text detection regions of interest (cv::Rect, CV_32SC4). ROIs is be cropped as the network inputs
  1325. * @param[out] results A set of text recognition results.
  1326. */
  1327. CV_WRAP
  1328. void recognize(InputArray frame, InputArrayOfArrays roiRects, CV_OUT std::vector<std::string>& results) const;
  1329. };
  1330. /** @brief Base class for text detection networks
  1331. */
  1332. class CV_EXPORTS_W_SIMPLE TextDetectionModel : public Model
  1333. {
  1334. protected:
  1335. CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first)
  1336. TextDetectionModel();
  1337. public:
  1338. /** @brief Performs detection
  1339. *
  1340. * Given the input @p frame, prepare network input, run network inference, post-process network output and return result detections.
  1341. *
  1342. * Each result is quadrangle's 4 points in this order:
  1343. * - bottom-left
  1344. * - top-left
  1345. * - top-right
  1346. * - bottom-right
  1347. *
  1348. * Use cv::getPerspectiveTransform function to retrive image region without perspective transformations.
  1349. *
  1350. * @note If DL model doesn't support that kind of output then result may be derived from detectTextRectangles() output.
  1351. *
  1352. * @param[in] frame The input image
  1353. * @param[out] detections array with detections' quadrangles (4 points per result)
  1354. * @param[out] confidences array with detection confidences
  1355. */
  1356. CV_WRAP
  1357. void detect(
  1358. InputArray frame,
  1359. CV_OUT std::vector< std::vector<Point> >& detections,
  1360. CV_OUT std::vector<float>& confidences
  1361. ) const;
  1362. /** @overload */
  1363. CV_WRAP
  1364. void detect(
  1365. InputArray frame,
  1366. CV_OUT std::vector< std::vector<Point> >& detections
  1367. ) const;
  1368. /** @brief Performs detection
  1369. *
  1370. * Given the input @p frame, prepare network input, run network inference, post-process network output and return result detections.
  1371. *
  1372. * Each result is rotated rectangle.
  1373. *
  1374. * @note Result may be inaccurate in case of strong perspective transformations.
  1375. *
  1376. * @param[in] frame the input image
  1377. * @param[out] detections array with detections' RotationRect results
  1378. * @param[out] confidences array with detection confidences
  1379. */
  1380. CV_WRAP
  1381. void detectTextRectangles(
  1382. InputArray frame,
  1383. CV_OUT std::vector<cv::RotatedRect>& detections,
  1384. CV_OUT std::vector<float>& confidences
  1385. ) const;
  1386. /** @overload */
  1387. CV_WRAP
  1388. void detectTextRectangles(
  1389. InputArray frame,
  1390. CV_OUT std::vector<cv::RotatedRect>& detections
  1391. ) const;
  1392. };
  1393. /** @brief This class represents high-level API for text detection DL networks compatible with EAST model.
  1394. *
  1395. * Configurable parameters:
  1396. * - (float) confThreshold - used to filter boxes by confidences, default: 0.5f
  1397. * - (float) nmsThreshold - used in non maximum suppression, default: 0.0f
  1398. */
  1399. class CV_EXPORTS_W_SIMPLE TextDetectionModel_EAST : public TextDetectionModel
  1400. {
  1401. public:
  1402. CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first)
  1403. TextDetectionModel_EAST();
  1404. /**
  1405. * @brief Create text detection algorithm from deep learning network
  1406. * @param[in] network Net object
  1407. */
  1408. CV_WRAP TextDetectionModel_EAST(const Net& network);
  1409. /**
  1410. * @brief Create text detection model from network represented in one of the supported formats.
  1411. * An order of @p model and @p config arguments does not matter.
  1412. * @param[in] model Binary file contains trained weights.
  1413. * @param[in] config Text file contains network configuration.
  1414. */
  1415. CV_WRAP inline
  1416. TextDetectionModel_EAST(const std::string& model, const std::string& config = "")
  1417. : TextDetectionModel_EAST(readNet(model, config)) { /* nothing */ }
  1418. /**
  1419. * @brief Set the detection confidence threshold
  1420. * @param[in] confThreshold A threshold used to filter boxes by confidences
  1421. */
  1422. CV_WRAP
  1423. TextDetectionModel_EAST& setConfidenceThreshold(float confThreshold);
  1424. /**
  1425. * @brief Get the detection confidence threshold
  1426. */
  1427. CV_WRAP
  1428. float getConfidenceThreshold() const;
  1429. /**
  1430. * @brief Set the detection NMS filter threshold
  1431. * @param[in] nmsThreshold A threshold used in non maximum suppression
  1432. */
  1433. CV_WRAP
  1434. TextDetectionModel_EAST& setNMSThreshold(float nmsThreshold);
  1435. /**
  1436. * @brief Get the detection confidence threshold
  1437. */
  1438. CV_WRAP
  1439. float getNMSThreshold() const;
  1440. };
  1441. /** @brief This class represents high-level API for text detection DL networks compatible with DB model.
  1442. *
  1443. * Related publications: @cite liao2020real
  1444. * Paper: https://arxiv.org/abs/1911.08947
  1445. * For more information about the hyper-parameters setting, please refer to https://github.com/MhLiao/DB
  1446. *
  1447. * Configurable parameters:
  1448. * - (float) binaryThreshold - The threshold of the binary map. It is usually set to 0.3.
  1449. * - (float) polygonThreshold - The threshold of text polygons. It is usually set to 0.5, 0.6, and 0.7. Default is 0.5f
  1450. * - (double) unclipRatio - The unclip ratio of the detected text region, which determines the output size. It is usually set to 2.0.
  1451. * - (int) maxCandidates - The max number of the output results.
  1452. */
  1453. class CV_EXPORTS_W_SIMPLE TextDetectionModel_DB : public TextDetectionModel
  1454. {
  1455. public:
  1456. CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first)
  1457. TextDetectionModel_DB();
  1458. /**
  1459. * @brief Create text detection algorithm from deep learning network.
  1460. * @param[in] network Net object.
  1461. */
  1462. CV_WRAP TextDetectionModel_DB(const Net& network);
  1463. /**
  1464. * @brief Create text detection model from network represented in one of the supported formats.
  1465. * An order of @p model and @p config arguments does not matter.
  1466. * @param[in] model Binary file contains trained weights.
  1467. * @param[in] config Text file contains network configuration.
  1468. */
  1469. CV_WRAP inline
  1470. TextDetectionModel_DB(const std::string& model, const std::string& config = "")
  1471. : TextDetectionModel_DB(readNet(model, config)) { /* nothing */ }
  1472. CV_WRAP TextDetectionModel_DB& setBinaryThreshold(float binaryThreshold);
  1473. CV_WRAP float getBinaryThreshold() const;
  1474. CV_WRAP TextDetectionModel_DB& setPolygonThreshold(float polygonThreshold);
  1475. CV_WRAP float getPolygonThreshold() const;
  1476. CV_WRAP TextDetectionModel_DB& setUnclipRatio(double unclipRatio);
  1477. CV_WRAP double getUnclipRatio() const;
  1478. CV_WRAP TextDetectionModel_DB& setMaxCandidates(int maxCandidates);
  1479. CV_WRAP int getMaxCandidates() const;
  1480. };
  1481. //! @}
  1482. CV__DNN_INLINE_NS_END
  1483. }
  1484. }
  1485. #include <opencv2/dnn/layer.hpp>
  1486. #include <opencv2/dnn/dnn.inl.hpp>
  1487. /// @deprecated Include this header directly from application. Automatic inclusion will be removed
  1488. #include <opencv2/dnn/utils/inference_engine.hpp>
  1489. #endif /* OPENCV_DNN_DNN_HPP */