dnn.hpp 93 KB

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