dnn.hpp 95 KB

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