all_layers.hpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  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_ALL_LAYERS_HPP
  42. #define OPENCV_DNN_DNN_ALL_LAYERS_HPP
  43. #include <opencv2/dnn.hpp>
  44. namespace cv {
  45. namespace dnn {
  46. CV__DNN_INLINE_NS_BEGIN
  47. //! @addtogroup dnn
  48. //! @{
  49. /** @defgroup dnnLayerList Partial List of Implemented Layers
  50. @{
  51. This subsection of dnn module contains information about built-in layers and their descriptions.
  52. Classes listed here, in fact, provides C++ API for creating instances of built-in layers.
  53. In addition to this way of layers instantiation, there is a more common factory API (see @ref dnnLayerFactory), it allows to create layers dynamically (by name) and register new ones.
  54. You can use both API, but factory API is less convenient for native C++ programming and basically designed for use inside importers (see @ref readNetFromCaffe(), @ref readNetFromTorch(), @ref readNetFromTensorflow()).
  55. Built-in layers partially reproduce functionality of corresponding Caffe and Torch7 layers.
  56. In particular, the following layers and Caffe importer were tested to reproduce <a href="http://caffe.berkeleyvision.org/tutorial/layers.html">Caffe</a> functionality:
  57. - Convolution
  58. - Deconvolution
  59. - Pooling
  60. - InnerProduct
  61. - TanH, ReLU, Sigmoid, BNLL, Power, AbsVal
  62. - Softmax
  63. - Reshape, Flatten, Slice, Split
  64. - LRN
  65. - MVN
  66. - Dropout (since it does nothing on forward pass -))
  67. */
  68. class CV_EXPORTS BlankLayer : public Layer
  69. {
  70. public:
  71. static Ptr<Layer> create(const LayerParams &params);
  72. };
  73. /**
  74. * Constant layer produces the same data blob at an every forward pass.
  75. */
  76. class CV_EXPORTS ConstLayer : public Layer
  77. {
  78. public:
  79. static Ptr<Layer> create(const LayerParams &params);
  80. };
  81. //! LSTM recurrent layer
  82. class CV_EXPORTS LSTMLayer : public Layer
  83. {
  84. public:
  85. /** Creates instance of LSTM layer */
  86. static Ptr<LSTMLayer> create(const LayerParams& params);
  87. /** @deprecated Use LayerParams::blobs instead.
  88. @brief Set trained weights for LSTM layer.
  89. LSTM behavior on each step is defined by current input, previous output, previous cell state and learned weights.
  90. Let @f$x_t@f$ be current input, @f$h_t@f$ be current output, @f$c_t@f$ be current state.
  91. Than current output and current cell state is computed as follows:
  92. @f{eqnarray*}{
  93. h_t &= o_t \odot tanh(c_t), \\
  94. c_t &= f_t \odot c_{t-1} + i_t \odot g_t, \\
  95. @f}
  96. where @f$\odot@f$ is per-element multiply operation and @f$i_t, f_t, o_t, g_t@f$ is internal gates that are computed using learned weights.
  97. Gates are computed as follows:
  98. @f{eqnarray*}{
  99. i_t &= sigmoid&(W_{xi} x_t + W_{hi} h_{t-1} + b_i), \\
  100. f_t &= sigmoid&(W_{xf} x_t + W_{hf} h_{t-1} + b_f), \\
  101. o_t &= sigmoid&(W_{xo} x_t + W_{ho} h_{t-1} + b_o), \\
  102. g_t &= tanh &(W_{xg} x_t + W_{hg} h_{t-1} + b_g), \\
  103. @f}
  104. where @f$W_{x?}@f$, @f$W_{h?}@f$ and @f$b_{?}@f$ are learned weights represented as matrices:
  105. @f$W_{x?} \in R^{N_h \times N_x}@f$, @f$W_{h?} \in R^{N_h \times N_h}@f$, @f$b_? \in R^{N_h}@f$.
  106. For simplicity and performance purposes we use @f$ W_x = [W_{xi}; W_{xf}; W_{xo}, W_{xg}] @f$
  107. (i.e. @f$W_x@f$ is vertical concatenation of @f$ W_{x?} @f$), @f$ W_x \in R^{4N_h \times N_x} @f$.
  108. The same for @f$ W_h = [W_{hi}; W_{hf}; W_{ho}, W_{hg}], W_h \in R^{4N_h \times N_h} @f$
  109. and for @f$ b = [b_i; b_f, b_o, b_g]@f$, @f$b \in R^{4N_h} @f$.
  110. @param Wh is matrix defining how previous output is transformed to internal gates (i.e. according to above mentioned notation is @f$ W_h @f$)
  111. @param Wx is matrix defining how current input is transformed to internal gates (i.e. according to above mentioned notation is @f$ W_x @f$)
  112. @param b is bias vector (i.e. according to above mentioned notation is @f$ b @f$)
  113. */
  114. CV_DEPRECATED virtual void setWeights(const Mat &Wh, const Mat &Wx, const Mat &b) = 0;
  115. /** @brief Specifies shape of output blob which will be [[`T`], `N`] + @p outTailShape.
  116. * @details If this parameter is empty or unset then @p outTailShape = [`Wh`.size(0)] will be used,
  117. * where `Wh` is parameter from setWeights().
  118. */
  119. virtual void setOutShape(const MatShape &outTailShape = MatShape()) = 0;
  120. /** @deprecated Use flag `produce_cell_output` in LayerParams.
  121. * @brief Specifies either interpret first dimension of input blob as timestamp dimension either as sample.
  122. *
  123. * If flag is set to true then shape of input blob will be interpreted as [`T`, `N`, `[data dims]`] where `T` specifies number of timestamps, `N` is number of independent streams.
  124. * In this case each forward() call will iterate through `T` timestamps and update layer's state `T` times.
  125. *
  126. * If flag is set to false then shape of input blob will be interpreted as [`N`, `[data dims]`].
  127. * In this case each forward() call will make one iteration and produce one timestamp with shape [`N`, `[out dims]`].
  128. */
  129. CV_DEPRECATED virtual void setUseTimstampsDim(bool use = true) = 0;
  130. /** @deprecated Use flag `use_timestamp_dim` in LayerParams.
  131. * @brief If this flag is set to true then layer will produce @f$ c_t @f$ as second output.
  132. * @details Shape of the second output is the same as first output.
  133. */
  134. CV_DEPRECATED virtual void setProduceCellOutput(bool produce = false) = 0;
  135. /* In common case it use single input with @f$x_t@f$ values to compute output(s) @f$h_t@f$ (and @f$c_t@f$).
  136. * @param input should contain packed values @f$x_t@f$
  137. * @param output contains computed outputs: @f$h_t@f$ (and @f$c_t@f$ if setProduceCellOutput() flag was set to true).
  138. *
  139. * If setUseTimstampsDim() is set to true then @p input[0] should has at least two dimensions with the following shape: [`T`, `N`, `[data dims]`],
  140. * where `T` specifies number of timestamps, `N` is number of independent streams (i.e. @f$ x_{t_0 + t}^{stream} @f$ is stored inside @p input[0][t, stream, ...]).
  141. *
  142. * If setUseTimstampsDim() is set to false then @p input[0] should contain single timestamp, its shape should has form [`N`, `[data dims]`] with at least one dimension.
  143. * (i.e. @f$ x_{t}^{stream} @f$ is stored inside @p input[0][stream, ...]).
  144. */
  145. int inputNameToIndex(String inputName) CV_OVERRIDE;
  146. int outputNameToIndex(const String& outputName) CV_OVERRIDE;
  147. };
  148. /** @brief GRU recurrent one-layer
  149. *
  150. * Accepts input sequence and computes the final hidden state for each element in the batch.
  151. *
  152. * - input[0] containing the features of the input sequence.
  153. * input[0] should have shape [`T`, `N`, `data_dims`] where `T` is sequence length, `N` is batch size, `data_dims` is input size
  154. * - output would have shape [`T`, `N`, `D` * `hidden_size`] where `D = 2` if layer is bidirectional otherwise `D = 1`
  155. *
  156. * Depends on the following attributes:
  157. * - hidden_size - Number of neurons in the hidden layer
  158. * - direction - RNN could be bidirectional or forward
  159. *
  160. * The final hidden state @f$ h_t @f$ computes by the following formulas:
  161. *
  162. @f{eqnarray*}{
  163. r_t = \sigma(W_{ir} x_t + b_{ir} + W_{hr} h_{(t-1)} + b_{hr}) \\
  164. z_t = \sigma(W_{iz} x_t + b_{iz} + W_{hz} h_{(t-1)} + b_{hz}) \\
  165. n_t = \tanh(W_{in} x_t + b_{in} + r_t \odot (W_{hn} h_{(t-1)}+ b_{hn})) \\
  166. h_t = (1 - z_t) \odot n_t + z_t \odot h_{(t-1)} \\
  167. @f}
  168. * Where @f$x_t@f$ is current input, @f$h_{(t-1)}@f$ is previous or initial hidden state.
  169. *
  170. * @f$W_{x?}@f$, @f$W_{h?}@f$ and @f$b_{?}@f$ are learned weights represented as matrices:
  171. * @f$W_{x?} \in R^{N_h \times N_x}@f$, @f$W_{h?} \in R^{N_h \times N_h}@f$, @f$b_? \in R^{N_h}@f$.
  172. *
  173. * @f$\odot@f$ is per-element multiply operation.
  174. */
  175. class CV_EXPORTS GRULayer : public Layer
  176. {
  177. public:
  178. /** Creates instance of GRU layer */
  179. static Ptr<GRULayer> create(const LayerParams& params);
  180. };
  181. /** @brief Classical recurrent layer
  182. Accepts two inputs @f$x_t@f$ and @f$h_{t-1}@f$ and compute two outputs @f$o_t@f$ and @f$h_t@f$.
  183. - input: should contain packed input @f$x_t@f$.
  184. - output: should contain output @f$o_t@f$ (and @f$h_t@f$ if setProduceHiddenOutput() is set to true).
  185. input[0] should have shape [`T`, `N`, `data_dims`] where `T` and `N` is number of timestamps and number of independent samples of @f$x_t@f$ respectively.
  186. output[0] will have shape [`T`, `N`, @f$N_o@f$], where @f$N_o@f$ is number of rows in @f$ W_{xo} @f$ matrix.
  187. If setProduceHiddenOutput() is set to true then @p output[1] will contain a Mat with shape [`T`, `N`, @f$N_h@f$], where @f$N_h@f$ is number of rows in @f$ W_{hh} @f$ matrix.
  188. */
  189. class CV_EXPORTS RNNLayer : public Layer
  190. {
  191. public:
  192. /** Creates instance of RNNLayer */
  193. static Ptr<RNNLayer> create(const LayerParams& params);
  194. /** Setups learned weights.
  195. Recurrent-layer behavior on each step is defined by current input @f$ x_t @f$, previous state @f$ h_t @f$ and learned weights as follows:
  196. @f{eqnarray*}{
  197. h_t &= tanh&(W_{hh} h_{t-1} + W_{xh} x_t + b_h), \\
  198. o_t &= tanh&(W_{ho} h_t + b_o),
  199. @f}
  200. @param Wxh is @f$ W_{xh} @f$ matrix
  201. @param bh is @f$ b_{h} @f$ vector
  202. @param Whh is @f$ W_{hh} @f$ matrix
  203. @param Who is @f$ W_{xo} @f$ matrix
  204. @param bo is @f$ b_{o} @f$ vector
  205. */
  206. virtual void setWeights(const Mat &Wxh, const Mat &bh, const Mat &Whh, const Mat &Who, const Mat &bo) = 0;
  207. /** @brief If this flag is set to true then layer will produce @f$ h_t @f$ as second output.
  208. * @details Shape of the second output is the same as first output.
  209. */
  210. virtual void setProduceHiddenOutput(bool produce = false) = 0;
  211. };
  212. /** @brief This function performs array summation based
  213. * on the Einstein summation convention. The function
  214. * allows for concise expressions of various mathematical
  215. * operations using subscripts.
  216. *
  217. * By default, the labels are placed in alphabetical
  218. * order at the end of the output.
  219. * For example:
  220. * if `c = einsum("i,j", a, b)`, then `c[i,j] == a[i]*b[j]`.
  221. * However, if `c = einsum("j,i", a, b)`, then `c[i,j] = a[j]*b[i]`.
  222. * Alternatively, you can control the output order or prevent
  223. * an axis from being summed/force an axis to be summed
  224. * by providing indices for the output.
  225. * For example:
  226. * `diag(a)` -> `einsum("ii->i", a)`
  227. * `sum(a, axis=0)` -> `einsum("i...->", a)`
  228. * Subscripts at the beginning and end may be specified
  229. * by putting an ellipsis "..." in the middle.
  230. * For instance, the function `einsum("i...i", a)` takes
  231. * the diagonal of the first and last dimensions of
  232. * the operand, and `einsum("ij...,jk...->ik...")` performs
  233. * the matrix product using the first two indices
  234. * of each operand instead of the last two.
  235. * When there is only one operand, no axes being summed,
  236. * and no output parameter, this function returns
  237. * a view into the operand instead of creating a copy.
  238. */
  239. class CV_EXPORTS EinsumLayer : public Layer
  240. {
  241. public:
  242. static Ptr<EinsumLayer> create(const LayerParams& params);
  243. };
  244. class CV_EXPORTS BaseConvolutionLayer : public Layer
  245. {
  246. public:
  247. CV_DEPRECATED_EXTERNAL Size kernel, stride, pad, dilation, adjustPad;
  248. std::vector<size_t> adjust_pads;
  249. std::vector<size_t> kernel_size, strides, dilations;
  250. std::vector<size_t> pads_begin, pads_end;
  251. String padMode;
  252. int numOutput;
  253. };
  254. class CV_EXPORTS ConvolutionLayer : public BaseConvolutionLayer
  255. {
  256. public:
  257. static Ptr<BaseConvolutionLayer> create(const LayerParams& params);
  258. bool fusedActivation = false;
  259. bool fusedAdd = false;
  260. bool useWinograd = true; // Flag whether to use Winograd to speed up 3x3 convolution.
  261. };
  262. class CV_EXPORTS ConvolutionLayerInt8 : public BaseConvolutionLayer
  263. {
  264. public:
  265. int input_zp, output_zp;
  266. float input_sc, output_sc;
  267. // quantization type flag. The perChannel default is true, that means it contains the parameters
  268. // of per-Channel quantization. Otherwise, that means this layer contains per-Tensor quantized parameters.
  269. bool per_channel;
  270. bool useWinograd = false; // Flag whether to use Winograd to speed up 3x3 convolution.
  271. static Ptr<BaseConvolutionLayer> create(const LayerParams& params);
  272. };
  273. class CV_EXPORTS DeconvolutionLayer : public BaseConvolutionLayer
  274. {
  275. public:
  276. static Ptr<BaseConvolutionLayer> create(const LayerParams& params);
  277. };
  278. class CV_EXPORTS LRNLayer : public Layer
  279. {
  280. public:
  281. int type;
  282. int size;
  283. float alpha, beta, bias;
  284. bool normBySize;
  285. static Ptr<LRNLayer> create(const LayerParams& params);
  286. };
  287. /** @brief ArgMax/ArgMin layer
  288. * @note returns indices as floats, which means the supported range is [-2^24; 2^24]
  289. */
  290. class CV_EXPORTS ArgLayer : public Layer
  291. {
  292. public:
  293. static Ptr<ArgLayer> create(const LayerParams& params);
  294. };
  295. /** @brief Gather layer
  296. */
  297. class CV_EXPORTS GatherLayer : public Layer
  298. {
  299. public:
  300. static Ptr<GatherLayer> create(const LayerParams& params);
  301. };
  302. /** @brief GatherElements layer
  303. * GatherElements takes two inputs data and indices of the same rank r >= 1 and an optional attribute axis and works such that:
  304. * output[i][j][k] = data[index[i][j][k]][j][k] if axis = 0 and r = 3
  305. * output[i][j][k] = data[i][index[i][j][k]][k] if axis = 1 and r = 3
  306. * output[i][j][k] = data[i][j][index[i][j][k]] if axis = 2 and r = 3
  307. *
  308. * Gather, on the other hand, takes a data tensor of rank r >= 1, and indices tensor of rank q, and works such that:
  309. * it gathers the enteries along axis dimension of the input data indexed by indices and concatenates them in an output tensor of rank q + (r - 1)
  310. * e.g. If axis = 0, let k = indices[i_{0}, ..., i_{q-1}] then output[i_{0}, ..., i_{q-1}, j_{0}, ..., j_{r-2}] = input[k , j_{0}, ..., j_{r-2}]:
  311. **/
  312. class CV_EXPORTS GatherElementsLayer : public Layer
  313. {
  314. public:
  315. static Ptr<GatherElementsLayer> create(const LayerParams& params);
  316. };
  317. class CV_EXPORTS PoolingLayer : public Layer
  318. {
  319. public:
  320. int type;
  321. std::vector<size_t> kernel_size, strides;
  322. std::vector<size_t> pads_begin, pads_end;
  323. bool globalPooling; //!< Flag is true if at least one of the axes is global pooled.
  324. std::vector<bool> isGlobalPooling;
  325. bool computeMaxIdx;
  326. String padMode;
  327. bool ceilMode;
  328. // If true for average pooling with padding, divide an every output region
  329. // by a whole kernel area. Otherwise exclude zero padded values and divide
  330. // by number of real values.
  331. bool avePoolPaddedArea;
  332. // ROIPooling parameters.
  333. Size pooledSize;
  334. float spatialScale;
  335. // PSROIPooling parameters.
  336. int psRoiOutChannels;
  337. static Ptr<PoolingLayer> create(const LayerParams& params);
  338. };
  339. class CV_EXPORTS PoolingLayerInt8 : public PoolingLayer
  340. {
  341. public:
  342. int input_zp, output_zp;
  343. float input_sc, output_sc;
  344. static Ptr<PoolingLayerInt8> create(const LayerParams& params);
  345. };
  346. class CV_EXPORTS ReduceLayer : public Layer
  347. {
  348. public:
  349. static Ptr<ReduceLayer> create(const LayerParams& params);
  350. };
  351. class CV_EXPORTS SoftmaxLayer : public Layer
  352. {
  353. public:
  354. bool logSoftMax;
  355. static Ptr<SoftmaxLayer> create(const LayerParams& params);
  356. };
  357. class CV_EXPORTS SoftmaxLayerInt8 : public SoftmaxLayer
  358. {
  359. public:
  360. float output_sc;
  361. int output_zp;
  362. static Ptr<SoftmaxLayerInt8> create(const LayerParams& params);
  363. };
  364. /**
  365. * `InnerProduct`, `MatMul` and `Gemm` operations are all implemented by Fully Connected Layer.
  366. * Parameter `is_matmul` is used to distinguish `MatMul` and `Gemm` from `InnerProduct`.
  367. */
  368. class CV_EXPORTS InnerProductLayer : public Layer
  369. {
  370. public:
  371. int axis;
  372. static Ptr<InnerProductLayer> create(const LayerParams& params);
  373. };
  374. class CV_EXPORTS InnerProductLayerInt8 : public InnerProductLayer
  375. {
  376. public:
  377. int input_zp, output_zp;
  378. float input_sc, output_sc;
  379. // quantization type flag. The perChannel default is true, that means it contains the parameters
  380. // of per-Channel quantization. Otherwise, that means this layer contains per-Tensor quantized parameters.
  381. bool per_channel;
  382. static Ptr<InnerProductLayerInt8> create(const LayerParams& params);
  383. };
  384. class CV_EXPORTS MVNLayer : public Layer
  385. {
  386. public:
  387. float eps;
  388. bool normVariance, acrossChannels;
  389. static Ptr<MVNLayer> create(const LayerParams& params);
  390. };
  391. /* Reshaping */
  392. class CV_EXPORTS ReshapeLayer : public Layer
  393. {
  394. public:
  395. MatShape newShapeDesc;
  396. Range newShapeRange;
  397. static Ptr<ReshapeLayer> create(const LayerParams& params);
  398. };
  399. class CV_EXPORTS FlattenLayer : public Layer
  400. {
  401. public:
  402. static Ptr<FlattenLayer> create(const LayerParams &params);
  403. };
  404. class CV_EXPORTS QuantizeLayer : public Layer
  405. {
  406. public:
  407. std::vector<float> scales;
  408. std::vector<int> zeropoints;
  409. static Ptr<QuantizeLayer> create(const LayerParams &params);
  410. };
  411. class CV_EXPORTS DequantizeLayer : public Layer
  412. {
  413. public:
  414. std::vector<float> scales;
  415. std::vector<int> zeropoints;
  416. static Ptr<DequantizeLayer> create(const LayerParams &params);
  417. };
  418. class CV_EXPORTS RequantizeLayer : public Layer
  419. {
  420. public:
  421. float scale, shift;
  422. static Ptr<RequantizeLayer> create(const LayerParams &params);
  423. };
  424. class CV_EXPORTS ConcatLayer : public Layer
  425. {
  426. public:
  427. int axis;
  428. /**
  429. * @brief Add zero padding in case of concatenation of blobs with different
  430. * spatial sizes.
  431. *
  432. * Details: https://github.com/torch/nn/blob/master/doc/containers.md#depthconcat
  433. */
  434. bool padding;
  435. int paddingValue;
  436. static Ptr<ConcatLayer> create(const LayerParams &params);
  437. };
  438. class CV_EXPORTS SplitLayer : public Layer
  439. {
  440. public:
  441. int outputsCount; //!< Number of copies that will be produced (is ignored when negative).
  442. static Ptr<SplitLayer> create(const LayerParams &params);
  443. };
  444. /**
  445. * Slice layer has several modes:
  446. * 1. Caffe mode
  447. * @param[in] axis Axis of split operation
  448. * @param[in] slice_point Array of split points
  449. *
  450. * Number of output blobs equals to number of split points plus one. The
  451. * first blob is a slice on input from 0 to @p slice_point[0] - 1 by @p axis,
  452. * the second output blob is a slice of input from @p slice_point[0] to
  453. * @p slice_point[1] - 1 by @p axis and the last output blob is a slice of
  454. * input from @p slice_point[-1] up to the end of @p axis size.
  455. *
  456. * 2. TensorFlow mode
  457. * @param begin Vector of start indices
  458. * @param size Vector of sizes
  459. *
  460. * More convenient numpy-like slice. One and only output blob
  461. * is a slice `input[begin[0]:begin[0]+size[0], begin[1]:begin[1]+size[1], ...]`
  462. *
  463. * 3. Torch mode
  464. * @param axis Axis of split operation
  465. *
  466. * Split input blob on the equal parts by @p axis.
  467. */
  468. class CV_EXPORTS SliceLayer : public Layer
  469. {
  470. public:
  471. /**
  472. * @brief Vector of slice ranges.
  473. *
  474. * The first dimension equals number of output blobs.
  475. * Inner vector has slice ranges for the first number of input dimensions.
  476. */
  477. std::vector<std::vector<Range> > sliceRanges;
  478. std::vector<std::vector<int> > sliceSteps;
  479. int axis;
  480. int num_split;
  481. static Ptr<SliceLayer> create(const LayerParams &params);
  482. };
  483. class CV_EXPORTS PermuteLayer : public Layer
  484. {
  485. public:
  486. static Ptr<PermuteLayer> create(const LayerParams& params);
  487. };
  488. /**
  489. * Permute channels of 4-dimensional input blob.
  490. * @param group Number of groups to split input channels and pick in turns
  491. * into output blob.
  492. *
  493. * \f[ groupSize = \frac{number\ of\ channels}{group} \f]
  494. * \f[ output(n, c, h, w) = input(n, groupSize \times (c \% group) + \lfloor \frac{c}{group} \rfloor, h, w) \f]
  495. * Read more at https://arxiv.org/pdf/1707.01083.pdf
  496. */
  497. class CV_EXPORTS ShuffleChannelLayer : public Layer
  498. {
  499. public:
  500. static Ptr<Layer> create(const LayerParams& params);
  501. int group;
  502. };
  503. /**
  504. * @brief Adds extra values for specific axes.
  505. * @param paddings Vector of paddings in format
  506. * @code
  507. * [ pad_before, pad_after, // [0]th dimension
  508. * pad_before, pad_after, // [1]st dimension
  509. * ...
  510. * pad_before, pad_after ] // [n]th dimension
  511. * @endcode
  512. * that represents number of padded values at every dimension
  513. * starting from the first one. The rest of dimensions won't
  514. * be padded.
  515. * @param value Value to be padded. Defaults to zero.
  516. * @param type Padding type: 'constant', 'reflect'
  517. * @param input_dims Torch's parameter. If @p input_dims is not equal to the
  518. * actual input dimensionality then the `[0]th` dimension
  519. * is considered as a batch dimension and @p paddings are shifted
  520. * to a one dimension. Defaults to `-1` that means padding
  521. * corresponding to @p paddings.
  522. */
  523. class CV_EXPORTS PaddingLayer : public Layer
  524. {
  525. public:
  526. static Ptr<PaddingLayer> create(const LayerParams& params);
  527. };
  528. /* Activations */
  529. class CV_EXPORTS ActivationLayer : public Layer
  530. {
  531. public:
  532. virtual void forwardSlice(const float* src, float* dst, int len,
  533. size_t outPlaneSize, int cn0, int cn1) const {}
  534. virtual void forwardSlice(const int* src, const int* lut, int* dst, int len,
  535. size_t outPlaneSize, int cn0, int cn1) const {}
  536. virtual void forwardSlice(const int8_t* src, const int8_t* lut, int8_t* dst, int len,
  537. size_t outPlaneSize, int cn0, int cn1) const {}
  538. };
  539. class CV_EXPORTS ReLULayer : public ActivationLayer
  540. {
  541. public:
  542. float negativeSlope;
  543. static Ptr<ReLULayer> create(const LayerParams &params);
  544. };
  545. class CV_EXPORTS ReLU6Layer : public ActivationLayer
  546. {
  547. public:
  548. float minValue, maxValue;
  549. static Ptr<ReLU6Layer> create(const LayerParams &params);
  550. };
  551. class CV_EXPORTS ChannelsPReLULayer : public ActivationLayer
  552. {
  553. public:
  554. static Ptr<Layer> create(const LayerParams& params);
  555. };
  556. class CV_EXPORTS ELULayer : public ActivationLayer
  557. {
  558. public:
  559. float alpha;
  560. static Ptr<ELULayer> create(const LayerParams &params);
  561. };
  562. class CV_EXPORTS TanHLayer : public ActivationLayer
  563. {
  564. public:
  565. static Ptr<TanHLayer> create(const LayerParams &params);
  566. };
  567. class CV_EXPORTS SwishLayer : public ActivationLayer
  568. {
  569. public:
  570. static Ptr<SwishLayer> create(const LayerParams &params);
  571. };
  572. class CV_EXPORTS MishLayer : public ActivationLayer
  573. {
  574. public:
  575. static Ptr<MishLayer> create(const LayerParams &params);
  576. };
  577. class CV_EXPORTS SigmoidLayer : public ActivationLayer
  578. {
  579. public:
  580. static Ptr<SigmoidLayer> create(const LayerParams &params);
  581. };
  582. class CV_EXPORTS BNLLLayer : public ActivationLayer
  583. {
  584. public:
  585. static Ptr<BNLLLayer> create(const LayerParams &params);
  586. };
  587. class CV_EXPORTS AbsLayer : public ActivationLayer
  588. {
  589. public:
  590. static Ptr<AbsLayer> create(const LayerParams &params);
  591. };
  592. class CV_EXPORTS PowerLayer : public ActivationLayer
  593. {
  594. public:
  595. float power, scale, shift;
  596. static Ptr<PowerLayer> create(const LayerParams &params);
  597. };
  598. class CV_EXPORTS ExpLayer : public ActivationLayer
  599. {
  600. public:
  601. float base, scale, shift;
  602. static Ptr<ExpLayer> create(const LayerParams &params);
  603. };
  604. class CV_EXPORTS CeilLayer : public ActivationLayer
  605. {
  606. public:
  607. static Ptr<CeilLayer> create(const LayerParams &params);
  608. };
  609. class CV_EXPORTS FloorLayer : public ActivationLayer
  610. {
  611. public:
  612. static Ptr<FloorLayer> create(const LayerParams &params);
  613. };
  614. class CV_EXPORTS LogLayer : public ActivationLayer
  615. {
  616. public:
  617. static Ptr<LogLayer> create(const LayerParams &params);
  618. };
  619. class CV_EXPORTS RoundLayer : public ActivationLayer
  620. {
  621. public:
  622. static Ptr<RoundLayer> create(const LayerParams &params);
  623. };
  624. class CV_EXPORTS SqrtLayer : public ActivationLayer
  625. {
  626. public:
  627. static Ptr<SqrtLayer> create(const LayerParams &params);
  628. };
  629. class CV_EXPORTS NotLayer : public ActivationLayer
  630. {
  631. public:
  632. static Ptr<NotLayer> create(const LayerParams &params);
  633. };
  634. class CV_EXPORTS AcosLayer : public ActivationLayer
  635. {
  636. public:
  637. static Ptr<AcosLayer> create(const LayerParams &params);
  638. };
  639. class CV_EXPORTS AcoshLayer : public ActivationLayer
  640. {
  641. public:
  642. static Ptr<AcoshLayer> create(const LayerParams &params);
  643. };
  644. class CV_EXPORTS AsinLayer : public ActivationLayer
  645. {
  646. public:
  647. static Ptr<AsinLayer> create(const LayerParams &params);
  648. };
  649. class CV_EXPORTS AsinhLayer : public ActivationLayer
  650. {
  651. public:
  652. static Ptr<AsinhLayer> create(const LayerParams &params);
  653. };
  654. class CV_EXPORTS AtanLayer : public ActivationLayer
  655. {
  656. public:
  657. static Ptr<AtanLayer> create(const LayerParams &params);
  658. };
  659. class CV_EXPORTS AtanhLayer : public ActivationLayer
  660. {
  661. public:
  662. static Ptr<AtanhLayer> create(const LayerParams &params);
  663. };
  664. class CV_EXPORTS CosLayer : public ActivationLayer
  665. {
  666. public:
  667. static Ptr<CosLayer> create(const LayerParams &params);
  668. };
  669. class CV_EXPORTS CoshLayer : public ActivationLayer
  670. {
  671. public:
  672. static Ptr<CoshLayer> create(const LayerParams &params);
  673. };
  674. class CV_EXPORTS ErfLayer : public ActivationLayer
  675. {
  676. public:
  677. static Ptr<ErfLayer> create(const LayerParams &params);
  678. };
  679. class CV_EXPORTS HardSwishLayer : public ActivationLayer
  680. {
  681. public:
  682. static Ptr<HardSwishLayer> create(const LayerParams &params);
  683. };
  684. class CV_EXPORTS SinLayer : public ActivationLayer
  685. {
  686. public:
  687. static Ptr<SinLayer> create(const LayerParams &params);
  688. };
  689. class CV_EXPORTS SinhLayer : public ActivationLayer
  690. {
  691. public:
  692. static Ptr<SinhLayer> create(const LayerParams &params);
  693. };
  694. class CV_EXPORTS SoftplusLayer : public ActivationLayer
  695. {
  696. public:
  697. static Ptr<SoftplusLayer> create(const LayerParams &params);
  698. };
  699. class CV_EXPORTS SoftsignLayer : public ActivationLayer
  700. {
  701. public:
  702. static Ptr<SoftsignLayer> create(const LayerParams &params);
  703. };
  704. class CV_EXPORTS TanLayer : public ActivationLayer
  705. {
  706. public:
  707. static Ptr<TanLayer> create(const LayerParams &params);
  708. };
  709. class CV_EXPORTS CeluLayer : public ActivationLayer
  710. {
  711. public:
  712. float alpha;
  713. static Ptr<CeluLayer> create(const LayerParams &params);
  714. };
  715. class CV_EXPORTS HardSigmoidLayer : public ActivationLayer
  716. {
  717. public:
  718. float alpha;
  719. float beta;
  720. static Ptr<HardSigmoidLayer> create(const LayerParams &params);
  721. };
  722. class CV_EXPORTS SeluLayer : public ActivationLayer
  723. {
  724. public:
  725. float alpha;
  726. float gamma;
  727. static Ptr<SeluLayer> create(const LayerParams &params);
  728. };
  729. class CV_EXPORTS GeluLayer : public ActivationLayer
  730. {
  731. public:
  732. static Ptr<GeluLayer> create(const LayerParams &params);
  733. };
  734. class CV_EXPORTS GeluApproximationLayer : public ActivationLayer
  735. {
  736. public:
  737. static Ptr<GeluApproximationLayer> create(const LayerParams &params);
  738. };
  739. class CV_EXPORTS ThresholdedReluLayer : public ActivationLayer
  740. {
  741. public:
  742. float alpha;
  743. static Ptr<ThresholdedReluLayer> create(const LayerParams &params);
  744. };
  745. class CV_EXPORTS ActivationLayerInt8 : public ActivationLayer
  746. {
  747. public:
  748. static Ptr<ActivationLayerInt8> create(const LayerParams &params);
  749. };
  750. class CV_EXPORTS SignLayer : public ActivationLayer
  751. {
  752. public:
  753. static Ptr<SignLayer> create(const LayerParams &params);
  754. };
  755. class CV_EXPORTS ShrinkLayer : public ActivationLayer
  756. {
  757. public:
  758. float bias;
  759. float lambd;
  760. static Ptr<ShrinkLayer> create(const LayerParams &params);
  761. };
  762. class CV_EXPORTS ReciprocalLayer : public ActivationLayer
  763. {
  764. public:
  765. static Ptr<ReciprocalLayer> create(const LayerParams &params);
  766. };
  767. /* Layers used in semantic segmentation */
  768. class CV_EXPORTS CropLayer : public Layer
  769. {
  770. public:
  771. static Ptr<Layer> create(const LayerParams &params);
  772. };
  773. /** @brief Element wise operation on inputs
  774. Extra optional parameters:
  775. - "operation" as string. Values are "sum" (default), "prod", "max", "div", "min"
  776. - "coeff" as float array. Specify weights of inputs for SUM operation
  777. - "output_channels_mode" as string. Values are "same" (default, all input must have the same layout), "input_0", "input_0_truncate", "max_input_channels"
  778. */
  779. class CV_EXPORTS EltwiseLayer : public Layer
  780. {
  781. public:
  782. static Ptr<EltwiseLayer> create(const LayerParams &params);
  783. };
  784. class CV_EXPORTS EltwiseLayerInt8 : public Layer
  785. {
  786. public:
  787. static Ptr<EltwiseLayerInt8> create(const LayerParams &params);
  788. };
  789. class CV_EXPORTS NaryEltwiseLayer : public Layer
  790. {
  791. public:
  792. static Ptr<NaryEltwiseLayer> create(const LayerParams &params);
  793. };
  794. class CV_EXPORTS BatchNormLayer : public ActivationLayer
  795. {
  796. public:
  797. bool hasWeights, hasBias;
  798. float epsilon;
  799. static Ptr<BatchNormLayer> create(const LayerParams &params);
  800. };
  801. class CV_EXPORTS BatchNormLayerInt8 : public BatchNormLayer
  802. {
  803. public:
  804. float input_sc, output_sc;
  805. int input_zp, output_zp;
  806. static Ptr<BatchNormLayerInt8> create(const LayerParams &params);
  807. };
  808. class CV_EXPORTS MaxUnpoolLayer : public Layer
  809. {
  810. public:
  811. Size poolKernel;
  812. Size poolPad;
  813. Size poolStride;
  814. static Ptr<MaxUnpoolLayer> create(const LayerParams &params);
  815. };
  816. class CV_EXPORTS ScaleLayer : public Layer
  817. {
  818. public:
  819. bool hasBias;
  820. int axis;
  821. String mode;
  822. static Ptr<ScaleLayer> create(const LayerParams& params);
  823. };
  824. class CV_EXPORTS ScaleLayerInt8 : public ScaleLayer
  825. {
  826. public:
  827. float output_sc;
  828. int output_zp;
  829. static Ptr<ScaleLayerInt8> create(const LayerParams &params);
  830. };
  831. class CV_EXPORTS ShiftLayer : public Layer
  832. {
  833. public:
  834. static Ptr<Layer> create(const LayerParams& params);
  835. };
  836. class CV_EXPORTS ShiftLayerInt8 : public Layer
  837. {
  838. public:
  839. static Ptr<Layer> create(const LayerParams& params);
  840. };
  841. class CV_EXPORTS CompareLayer : public Layer
  842. {
  843. public:
  844. static Ptr<Layer> create(const LayerParams& params);
  845. };
  846. class CV_EXPORTS DataAugmentationLayer : public Layer
  847. {
  848. public:
  849. static Ptr<DataAugmentationLayer> create(const LayerParams& params);
  850. };
  851. class CV_EXPORTS CorrelationLayer : public Layer
  852. {
  853. public:
  854. static Ptr<CorrelationLayer> create(const LayerParams& params);
  855. };
  856. class CV_EXPORTS AccumLayer : public Layer
  857. {
  858. public:
  859. static Ptr<AccumLayer> create(const LayerParams& params);
  860. };
  861. class CV_EXPORTS FlowWarpLayer : public Layer
  862. {
  863. public:
  864. static Ptr<FlowWarpLayer> create(const LayerParams& params);
  865. };
  866. class CV_EXPORTS PriorBoxLayer : public Layer
  867. {
  868. public:
  869. static Ptr<PriorBoxLayer> create(const LayerParams& params);
  870. };
  871. class CV_EXPORTS ReorgLayer : public Layer
  872. {
  873. public:
  874. static Ptr<ReorgLayer> create(const LayerParams& params);
  875. };
  876. class CV_EXPORTS RegionLayer : public Layer
  877. {
  878. public:
  879. float nmsThreshold;
  880. static Ptr<RegionLayer> create(const LayerParams& params);
  881. };
  882. /**
  883. * @brief Detection output layer.
  884. *
  885. * The layer size is: @f$ (1 \times 1 \times N \times 7) @f$
  886. * where N is [keep_top_k] parameter multiplied by batch size. Each row is:
  887. * [image_id, label, confidence, xmin, ymin, xmax, ymax]
  888. * where image_id is the index of image input in the batch.
  889. */
  890. class CV_EXPORTS DetectionOutputLayer : public Layer
  891. {
  892. public:
  893. static Ptr<DetectionOutputLayer> create(const LayerParams& params);
  894. };
  895. /**
  896. * @brief \f$ L_p \f$ - normalization layer.
  897. * @param p Normalization factor. The most common `p = 1` for \f$ L_1 \f$ -
  898. * normalization or `p = 2` for \f$ L_2 \f$ - normalization or a custom one.
  899. * @param eps Parameter \f$ \epsilon \f$ to prevent a division by zero.
  900. * @param across_spatial If true, normalize an input across all non-batch dimensions.
  901. * Otherwise normalize an every channel separately.
  902. *
  903. * Across spatial:
  904. * @f[
  905. * norm = \sqrt[p]{\epsilon + \sum_{x, y, c} |src(x, y, c)|^p } \\
  906. * dst(x, y, c) = \frac{ src(x, y, c) }{norm}
  907. * @f]
  908. *
  909. * Channel wise normalization:
  910. * @f[
  911. * norm(c) = \sqrt[p]{\epsilon + \sum_{x, y} |src(x, y, c)|^p } \\
  912. * dst(x, y, c) = \frac{ src(x, y, c) }{norm(c)}
  913. * @f]
  914. *
  915. * Where `x, y` - spatial coordinates, `c` - channel.
  916. *
  917. * An every sample in the batch is normalized separately. Optionally,
  918. * output is scaled by the trained parameters.
  919. */
  920. class CV_EXPORTS NormalizeBBoxLayer : public Layer
  921. {
  922. public:
  923. float pnorm, epsilon;
  924. CV_DEPRECATED_EXTERNAL bool acrossSpatial;
  925. static Ptr<NormalizeBBoxLayer> create(const LayerParams& params);
  926. };
  927. /**
  928. * @brief Resize input 4-dimensional blob by nearest neighbor or bilinear strategy.
  929. *
  930. * Layer is used to support TensorFlow's resize_nearest_neighbor and resize_bilinear ops.
  931. */
  932. class CV_EXPORTS ResizeLayer : public Layer
  933. {
  934. public:
  935. static Ptr<ResizeLayer> create(const LayerParams& params);
  936. };
  937. /**
  938. * @brief Bilinear resize layer from https://github.com/cdmh/deeplab-public-ver2
  939. *
  940. * It differs from @ref ResizeLayer in output shape and resize scales computations.
  941. */
  942. class CV_EXPORTS InterpLayer : public Layer
  943. {
  944. public:
  945. static Ptr<Layer> create(const LayerParams& params);
  946. };
  947. class CV_EXPORTS ProposalLayer : public Layer
  948. {
  949. public:
  950. static Ptr<ProposalLayer> create(const LayerParams& params);
  951. };
  952. class CV_EXPORTS CropAndResizeLayer : public Layer
  953. {
  954. public:
  955. static Ptr<Layer> create(const LayerParams& params);
  956. };
  957. class CV_EXPORTS CumSumLayer : public Layer
  958. {
  959. public:
  960. int exclusive;
  961. int reverse;
  962. static Ptr<CumSumLayer> create(const LayerParams& params);
  963. };
  964. class CV_EXPORTS ScatterLayer : public Layer
  965. {
  966. public:
  967. static Ptr<ScatterLayer> create(const LayerParams& params);
  968. };
  969. class CV_EXPORTS ScatterNDLayer : public Layer
  970. {
  971. public:
  972. static Ptr<ScatterNDLayer> create(const LayerParams& params);
  973. };
  974. class CV_EXPORTS TileLayer : public Layer
  975. {
  976. public:
  977. static Ptr<TileLayer> create(const LayerParams& params);
  978. };
  979. class CV_EXPORTS LayerNormLayer : public Layer
  980. {
  981. public:
  982. CV_DEPRECATED_EXTERNAL bool hasBias; // Deprecated, preserve for compatibility
  983. int axis;
  984. float epsilon;
  985. static Ptr<LayerNormLayer> create(const LayerParams& params);
  986. };
  987. class CV_EXPORTS GemmLayer : public Layer {
  988. public:
  989. bool trans_a;
  990. bool trans_b;
  991. float alpha;
  992. float beta;
  993. static Ptr<GemmLayer> create(const LayerParams& params);
  994. };
  995. class CV_EXPORTS MatMulLayer : public Layer {
  996. public:
  997. static Ptr<MatMulLayer> create(const LayerParams &params);
  998. };
  999. class CV_EXPORTS ExpandLayer : public Layer
  1000. {
  1001. public:
  1002. static Ptr<ExpandLayer> create(const LayerParams &params);
  1003. };
  1004. class CV_EXPORTS InstanceNormLayer : public Layer {
  1005. public:
  1006. float epsilon;
  1007. static Ptr<InstanceNormLayer> create(const LayerParams &params);
  1008. };
  1009. class CV_EXPORTS AttentionLayer : public Layer {
  1010. public:
  1011. static Ptr<AttentionLayer> create(const LayerParams &params);
  1012. };
  1013. class CV_EXPORTS GroupNormLayer : public Layer {
  1014. public:
  1015. static Ptr<GroupNormLayer> create(const LayerParams &params);
  1016. };
  1017. //! @}
  1018. //! @}
  1019. CV__DNN_INLINE_NS_END
  1020. }
  1021. }
  1022. #endif