core.hpp 150 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344
  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) 2000-2015, Intel Corporation, all rights reserved.
  14. // Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved.
  15. // Copyright (C) 2015, OpenCV Foundation, all rights reserved.
  16. // Copyright (C) 2015, Itseez Inc., all rights reserved.
  17. // Third party copyrights are property of their respective owners.
  18. //
  19. // Redistribution and use in source and binary forms, with or without modification,
  20. // are permitted provided that the following conditions are met:
  21. //
  22. // * Redistribution's of source code must retain the above copyright notice,
  23. // this list of conditions and the following disclaimer.
  24. //
  25. // * Redistribution's in binary form must reproduce the above copyright notice,
  26. // this list of conditions and the following disclaimer in the documentation
  27. // and/or other materials provided with the distribution.
  28. //
  29. // * The name of the copyright holders may not be used to endorse or promote products
  30. // derived from this software without specific prior written permission.
  31. //
  32. // This software is provided by the copyright holders and contributors "as is" and
  33. // any express or implied warranties, including, but not limited to, the implied
  34. // warranties of merchantability and fitness for a particular purpose are disclaimed.
  35. // In no event shall the Intel Corporation or contributors be liable for any direct,
  36. // indirect, incidental, special, exemplary, or consequential damages
  37. // (including, but not limited to, procurement of substitute goods or services;
  38. // loss of use, data, or profits; or business interruption) however caused
  39. // and on any theory of liability, whether in contract, strict liability,
  40. // or tort (including negligence or otherwise) arising in any way out of
  41. // the use of this software, even if advised of the possibility of such damage.
  42. //
  43. //M*/
  44. #ifndef OPENCV_CORE_HPP
  45. #define OPENCV_CORE_HPP
  46. #ifndef __cplusplus
  47. # error core.hpp header must be compiled as C++
  48. #endif
  49. #include "opencv2/core/cvdef.h"
  50. #include "opencv2/core/base.hpp"
  51. #include "opencv2/core/cvstd.hpp"
  52. #include "opencv2/core/traits.hpp"
  53. #include "opencv2/core/matx.hpp"
  54. #include "opencv2/core/types.hpp"
  55. #include "opencv2/core/mat.hpp"
  56. #include "opencv2/core/persistence.hpp"
  57. /**
  58. @defgroup core Core functionality
  59. @{
  60. @defgroup core_basic Basic structures
  61. @defgroup core_c C structures and operations
  62. @{
  63. @defgroup core_c_glue Connections with C++
  64. @}
  65. @defgroup core_array Operations on arrays
  66. @defgroup core_async Asynchronous API
  67. @defgroup core_xml XML/YAML Persistence
  68. @defgroup core_cluster Clustering
  69. @defgroup core_utils Utility and system functions and macros
  70. @{
  71. @defgroup core_logging Logging facilities
  72. @defgroup core_utils_sse SSE utilities
  73. @defgroup core_utils_neon NEON utilities
  74. @defgroup core_utils_vsx VSX utilities
  75. @defgroup core_utils_softfloat Softfloat support
  76. @defgroup core_utils_samples Utility functions for OpenCV samples
  77. @}
  78. @defgroup core_opengl OpenGL interoperability
  79. @defgroup core_ipp Intel IPP Asynchronous C/C++ Converters
  80. @defgroup core_optim Optimization Algorithms
  81. @defgroup core_directx DirectX interoperability
  82. @defgroup core_eigen Eigen support
  83. @defgroup core_opencl OpenCL support
  84. @defgroup core_va_intel Intel VA-API/OpenCL (CL-VA) interoperability
  85. @defgroup core_hal Hardware Acceleration Layer
  86. @{
  87. @defgroup core_hal_functions Functions
  88. @defgroup core_hal_interface Interface
  89. @defgroup core_hal_intrin Universal intrinsics
  90. @{
  91. @defgroup core_hal_intrin_impl Private implementation helpers
  92. @}
  93. @defgroup core_lowlevel_api Low-level API for external libraries / plugins
  94. @}
  95. @defgroup core_parallel Parallel Processing
  96. @{
  97. @defgroup core_parallel_backend Parallel backends API
  98. @}
  99. @}
  100. */
  101. namespace cv {
  102. //! @addtogroup core_utils
  103. //! @{
  104. /*! @brief Class passed to an error.
  105. This class encapsulates all or almost all necessary
  106. information about the error happened in the program. The exception is
  107. usually constructed and thrown implicitly via CV_Error and CV_Error_ macros.
  108. @see error
  109. */
  110. class CV_EXPORTS Exception : public std::exception
  111. {
  112. public:
  113. /*!
  114. Default constructor
  115. */
  116. Exception();
  117. /*!
  118. Full constructor. Normally the constructor is not called explicitly.
  119. Instead, the macros CV_Error(), CV_Error_() and CV_Assert() are used.
  120. */
  121. Exception(int _code, const String& _err, const String& _func, const String& _file, int _line);
  122. virtual ~Exception() throw();
  123. /*!
  124. \return the error description and the context as a text string.
  125. */
  126. virtual const char *what() const throw() CV_OVERRIDE;
  127. void formatMessage();
  128. String msg; ///< the formatted error message
  129. int code; ///< error code @see CVStatus
  130. String err; ///< error description
  131. String func; ///< function name. Available only when the compiler supports getting it
  132. String file; ///< source file name where the error has occurred
  133. int line; ///< line number in the source file where the error has occurred
  134. };
  135. /*! @brief Signals an error and raises the exception.
  136. By default the function prints information about the error to stderr,
  137. then it either stops if cv::setBreakOnError() had been called before or raises the exception.
  138. It is possible to alternate error processing by using #redirectError().
  139. @param exc the exception raisen.
  140. @deprecated drop this version
  141. */
  142. CV_EXPORTS CV_NORETURN void error(const Exception& exc);
  143. enum SortFlags { SORT_EVERY_ROW = 0, //!< each matrix row is sorted independently
  144. SORT_EVERY_COLUMN = 1, //!< each matrix column is sorted
  145. //!< independently; this flag and the previous one are
  146. //!< mutually exclusive.
  147. SORT_ASCENDING = 0, //!< each matrix row is sorted in the ascending
  148. //!< order.
  149. SORT_DESCENDING = 16 //!< each matrix row is sorted in the
  150. //!< descending order; this flag and the previous one are also
  151. //!< mutually exclusive.
  152. };
  153. //! @} core_utils
  154. //! @addtogroup core
  155. //! @{
  156. //! Covariation flags
  157. enum CovarFlags {
  158. /** The output covariance matrix is calculated as:
  159. \f[\texttt{scale} \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...]^T \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...],\f]
  160. The covariance matrix will be nsamples x nsamples. Such an unusual covariance matrix is used
  161. for fast PCA of a set of very large vectors (see, for example, the EigenFaces technique for
  162. face recognition). Eigenvalues of this "scrambled" matrix match the eigenvalues of the true
  163. covariance matrix. The "true" eigenvectors can be easily calculated from the eigenvectors of
  164. the "scrambled" covariance matrix. */
  165. COVAR_SCRAMBLED = 0,
  166. /**The output covariance matrix is calculated as:
  167. \f[\texttt{scale} \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...] \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...]^T,\f]
  168. covar will be a square matrix of the same size as the total number of elements in each input
  169. vector. One and only one of #COVAR_SCRAMBLED and #COVAR_NORMAL must be specified.*/
  170. COVAR_NORMAL = 1,
  171. /** If the flag is specified, the function does not calculate mean from
  172. the input vectors but, instead, uses the passed mean vector. This is useful if mean has been
  173. pre-calculated or known in advance, or if the covariance matrix is calculated by parts. In
  174. this case, mean is not a mean vector of the input sub-set of vectors but rather the mean
  175. vector of the whole set.*/
  176. COVAR_USE_AVG = 2,
  177. /** If the flag is specified, the covariance matrix is scaled. In the
  178. "normal" mode, scale is 1./nsamples . In the "scrambled" mode, scale is the reciprocal of the
  179. total number of elements in each input vector. By default (if the flag is not specified), the
  180. covariance matrix is not scaled ( scale=1 ).*/
  181. COVAR_SCALE = 4,
  182. /** If the flag is
  183. specified, all the input vectors are stored as rows of the samples matrix. mean should be a
  184. single-row vector in this case.*/
  185. COVAR_ROWS = 8,
  186. /** If the flag is
  187. specified, all the input vectors are stored as columns of the samples matrix. mean should be a
  188. single-column vector in this case.*/
  189. COVAR_COLS = 16
  190. };
  191. //! @addtogroup core_cluster
  192. //! @{
  193. //! k-Means flags
  194. enum KmeansFlags {
  195. /** Select random initial centers in each attempt.*/
  196. KMEANS_RANDOM_CENTERS = 0,
  197. /** Use kmeans++ center initialization by Arthur and Vassilvitskii [Arthur2007].*/
  198. KMEANS_PP_CENTERS = 2,
  199. /** During the first (and possibly the only) attempt, use the
  200. user-supplied labels instead of computing them from the initial centers. For the second and
  201. further attempts, use the random or semi-random centers. Use one of KMEANS_\*_CENTERS flag
  202. to specify the exact method.*/
  203. KMEANS_USE_INITIAL_LABELS = 1
  204. };
  205. //! @} core_cluster
  206. //! @addtogroup core_array
  207. //! @{
  208. enum ReduceTypes { REDUCE_SUM = 0, //!< the output is the sum of all rows/columns of the matrix.
  209. REDUCE_AVG = 1, //!< the output is the mean vector of all rows/columns of the matrix.
  210. REDUCE_MAX = 2, //!< the output is the maximum (column/row-wise) of all rows/columns of the matrix.
  211. REDUCE_MIN = 3 //!< the output is the minimum (column/row-wise) of all rows/columns of the matrix.
  212. };
  213. //! @} core_array
  214. /** @brief Swaps two matrices
  215. */
  216. CV_EXPORTS void swap(Mat& a, Mat& b);
  217. /** @overload */
  218. CV_EXPORTS void swap( UMat& a, UMat& b );
  219. //! @} core
  220. //! @addtogroup core_array
  221. //! @{
  222. /** @brief Computes the source location of an extrapolated pixel.
  223. The function computes and returns the coordinate of a donor pixel corresponding to the specified
  224. extrapolated pixel when using the specified extrapolation border mode. For example, if you use
  225. cv::BORDER_WRAP mode in the horizontal direction, cv::BORDER_REFLECT_101 in the vertical direction and
  226. want to compute value of the "virtual" pixel Point(-5, 100) in a floating-point image img , it
  227. looks like:
  228. @code{.cpp}
  229. float val = img.at<float>(borderInterpolate(100, img.rows, cv::BORDER_REFLECT_101),
  230. borderInterpolate(-5, img.cols, cv::BORDER_WRAP));
  231. @endcode
  232. Normally, the function is not called directly. It is used inside filtering functions and also in
  233. copyMakeBorder.
  234. @param p 0-based coordinate of the extrapolated pixel along one of the axes, likely \<0 or \>= len
  235. @param len Length of the array along the corresponding axis.
  236. @param borderType Border type, one of the #BorderTypes, except for #BORDER_TRANSPARENT and
  237. #BORDER_ISOLATED . When borderType==#BORDER_CONSTANT , the function always returns -1, regardless
  238. of p and len.
  239. @sa copyMakeBorder
  240. */
  241. CV_EXPORTS_W int borderInterpolate(int p, int len, int borderType);
  242. /** @example samples/cpp/tutorial_code/ImgTrans/copyMakeBorder_demo.cpp
  243. An example using copyMakeBorder function.
  244. Check @ref tutorial_copyMakeBorder "the corresponding tutorial" for more details
  245. */
  246. /** @brief Forms a border around an image.
  247. The function copies the source image into the middle of the destination image. The areas to the
  248. left, to the right, above and below the copied source image will be filled with extrapolated
  249. pixels. This is not what filtering functions based on it do (they extrapolate pixels on-fly), but
  250. what other more complex functions, including your own, may do to simplify image boundary handling.
  251. The function supports the mode when src is already in the middle of dst . In this case, the
  252. function does not copy src itself but simply constructs the border, for example:
  253. @code{.cpp}
  254. // let border be the same in all directions
  255. int border=2;
  256. // constructs a larger image to fit both the image and the border
  257. Mat gray_buf(rgb.rows + border*2, rgb.cols + border*2, rgb.depth());
  258. // select the middle part of it w/o copying data
  259. Mat gray(gray_canvas, Rect(border, border, rgb.cols, rgb.rows));
  260. // convert image from RGB to grayscale
  261. cvtColor(rgb, gray, COLOR_RGB2GRAY);
  262. // form a border in-place
  263. copyMakeBorder(gray, gray_buf, border, border,
  264. border, border, BORDER_REPLICATE);
  265. // now do some custom filtering ...
  266. ...
  267. @endcode
  268. @note When the source image is a part (ROI) of a bigger image, the function will try to use the
  269. pixels outside of the ROI to form a border. To disable this feature and always do extrapolation, as
  270. if src was not a ROI, use borderType | #BORDER_ISOLATED.
  271. @param src Source image.
  272. @param dst Destination image of the same type as src and the size Size(src.cols+left+right,
  273. src.rows+top+bottom) .
  274. @param top the top pixels
  275. @param bottom the bottom pixels
  276. @param left the left pixels
  277. @param right Parameter specifying how many pixels in each direction from the source image rectangle
  278. to extrapolate. For example, top=1, bottom=1, left=1, right=1 mean that 1 pixel-wide border needs
  279. to be built.
  280. @param borderType Border type. See borderInterpolate for details.
  281. @param value Border value if borderType==BORDER_CONSTANT .
  282. @sa borderInterpolate
  283. */
  284. CV_EXPORTS_W void copyMakeBorder(InputArray src, OutputArray dst,
  285. int top, int bottom, int left, int right,
  286. int borderType, const Scalar& value = Scalar() );
  287. /** @brief Calculates the per-element sum of two arrays or an array and a scalar.
  288. The function add calculates:
  289. - Sum of two arrays when both input arrays have the same size and the same number of channels:
  290. \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f]
  291. - Sum of an array and a scalar when src2 is constructed from Scalar or has the same number of
  292. elements as `src1.channels()`:
  293. \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2} ) \quad \texttt{if mask}(I) \ne0\f]
  294. - Sum of a scalar and an array when src1 is constructed from Scalar or has the same number of
  295. elements as `src2.channels()`:
  296. \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1} + \texttt{src2}(I) ) \quad \texttt{if mask}(I) \ne0\f]
  297. where `I` is a multi-dimensional index of array elements. In case of multi-channel arrays, each
  298. channel is processed independently.
  299. The first function in the list above can be replaced with matrix expressions:
  300. @code{.cpp}
  301. dst = src1 + src2;
  302. dst += src1; // equivalent to add(dst, src1, dst);
  303. @endcode
  304. The input arrays and the output array can all have the same or different depths. For example, you
  305. can add a 16-bit unsigned array to a 8-bit signed array and store the sum as a 32-bit
  306. floating-point array. Depth of the output array is determined by the dtype parameter. In the second
  307. and third cases above, as well as in the first case, when src1.depth() == src2.depth(), dtype can
  308. be set to the default -1. In this case, the output array will have the same depth as the input
  309. array, be it src1, src2 or both.
  310. @note Saturation is not applied when the output array has the depth CV_32S. You may even get
  311. result of an incorrect sign in the case of overflow.
  312. @param src1 first input array or a scalar.
  313. @param src2 second input array or a scalar.
  314. @param dst output array that has the same size and number of channels as the input array(s); the
  315. depth is defined by dtype or src1/src2.
  316. @param mask optional operation mask - 8-bit single channel array, that specifies elements of the
  317. output array to be changed.
  318. @param dtype optional depth of the output array (see the discussion below).
  319. @sa subtract, addWeighted, scaleAdd, Mat::convertTo
  320. */
  321. CV_EXPORTS_W void add(InputArray src1, InputArray src2, OutputArray dst,
  322. InputArray mask = noArray(), int dtype = -1);
  323. /** @brief Calculates the per-element difference between two arrays or array and a scalar.
  324. The function subtract calculates:
  325. - Difference between two arrays, when both input arrays have the same size and the same number of
  326. channels:
  327. \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) - \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f]
  328. - Difference between an array and a scalar, when src2 is constructed from Scalar or has the same
  329. number of elements as `src1.channels()`:
  330. \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) - \texttt{src2} ) \quad \texttt{if mask}(I) \ne0\f]
  331. - Difference between a scalar and an array, when src1 is constructed from Scalar or has the same
  332. number of elements as `src2.channels()`:
  333. \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1} - \texttt{src2}(I) ) \quad \texttt{if mask}(I) \ne0\f]
  334. - The reverse difference between a scalar and an array in the case of `SubRS`:
  335. \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src2} - \texttt{src1}(I) ) \quad \texttt{if mask}(I) \ne0\f]
  336. where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each
  337. channel is processed independently.
  338. The first function in the list above can be replaced with matrix expressions:
  339. @code{.cpp}
  340. dst = src1 - src2;
  341. dst -= src1; // equivalent to subtract(dst, src1, dst);
  342. @endcode
  343. The input arrays and the output array can all have the same or different depths. For example, you
  344. can subtract to 8-bit unsigned arrays and store the difference in a 16-bit signed array. Depth of
  345. the output array is determined by dtype parameter. In the second and third cases above, as well as
  346. in the first case, when src1.depth() == src2.depth(), dtype can be set to the default -1. In this
  347. case the output array will have the same depth as the input array, be it src1, src2 or both.
  348. @note Saturation is not applied when the output array has the depth CV_32S. You may even get
  349. result of an incorrect sign in the case of overflow.
  350. @param src1 first input array or a scalar.
  351. @param src2 second input array or a scalar.
  352. @param dst output array of the same size and the same number of channels as the input array.
  353. @param mask optional operation mask; this is an 8-bit single channel array that specifies elements
  354. of the output array to be changed.
  355. @param dtype optional depth of the output array
  356. @sa add, addWeighted, scaleAdd, Mat::convertTo
  357. */
  358. CV_EXPORTS_W void subtract(InputArray src1, InputArray src2, OutputArray dst,
  359. InputArray mask = noArray(), int dtype = -1);
  360. /** @brief Calculates the per-element scaled product of two arrays.
  361. The function multiply calculates the per-element product of two arrays:
  362. \f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{scale} \cdot \texttt{src1} (I) \cdot \texttt{src2} (I))\f]
  363. There is also a @ref MatrixExpressions -friendly variant of the first function. See Mat::mul .
  364. For a not-per-element matrix product, see gemm .
  365. @note Saturation is not applied when the output array has the depth
  366. CV_32S. You may even get result of an incorrect sign in the case of
  367. overflow.
  368. @param src1 first input array.
  369. @param src2 second input array of the same size and the same type as src1.
  370. @param dst output array of the same size and type as src1.
  371. @param scale optional scale factor.
  372. @param dtype optional depth of the output array
  373. @sa add, subtract, divide, scaleAdd, addWeighted, accumulate, accumulateProduct, accumulateSquare,
  374. Mat::convertTo
  375. */
  376. CV_EXPORTS_W void multiply(InputArray src1, InputArray src2,
  377. OutputArray dst, double scale = 1, int dtype = -1);
  378. /** @brief Performs per-element division of two arrays or a scalar by an array.
  379. The function cv::divide divides one array by another:
  380. \f[\texttt{dst(I) = saturate(src1(I)*scale/src2(I))}\f]
  381. or a scalar by an array when there is no src1 :
  382. \f[\texttt{dst(I) = saturate(scale/src2(I))}\f]
  383. Different channels of multi-channel arrays are processed independently.
  384. For integer types when src2(I) is zero, dst(I) will also be zero.
  385. @note In case of floating point data there is no special defined behavior for zero src2(I) values.
  386. Regular floating-point division is used.
  387. Expect correct IEEE-754 behaviour for floating-point data (with NaN, Inf result values).
  388. @note Saturation is not applied when the output array has the depth CV_32S. You may even get
  389. result of an incorrect sign in the case of overflow.
  390. @param src1 first input array.
  391. @param src2 second input array of the same size and type as src1.
  392. @param scale scalar factor.
  393. @param dst output array of the same size and type as src2.
  394. @param dtype optional depth of the output array; if -1, dst will have depth src2.depth(), but in
  395. case of an array-by-array division, you can only pass -1 when src1.depth()==src2.depth().
  396. @sa multiply, add, subtract
  397. */
  398. CV_EXPORTS_W void divide(InputArray src1, InputArray src2, OutputArray dst,
  399. double scale = 1, int dtype = -1);
  400. /** @overload */
  401. CV_EXPORTS_W void divide(double scale, InputArray src2,
  402. OutputArray dst, int dtype = -1);
  403. /** @brief Calculates the sum of a scaled array and another array.
  404. The function scaleAdd is one of the classical primitive linear algebra operations, known as DAXPY
  405. or SAXPY in [BLAS](http://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms). It calculates
  406. the sum of a scaled array and another array:
  407. \f[\texttt{dst} (I)= \texttt{scale} \cdot \texttt{src1} (I) + \texttt{src2} (I)\f]
  408. The function can also be emulated with a matrix expression, for example:
  409. @code{.cpp}
  410. Mat A(3, 3, CV_64F);
  411. ...
  412. A.row(0) = A.row(1)*2 + A.row(2);
  413. @endcode
  414. @param src1 first input array.
  415. @param alpha scale factor for the first array.
  416. @param src2 second input array of the same size and type as src1.
  417. @param dst output array of the same size and type as src1.
  418. @sa add, addWeighted, subtract, Mat::dot, Mat::convertTo
  419. */
  420. CV_EXPORTS_W void scaleAdd(InputArray src1, double alpha, InputArray src2, OutputArray dst);
  421. /** @example samples/cpp/tutorial_code/HighGUI/AddingImagesTrackbar.cpp
  422. Check @ref tutorial_trackbar "the corresponding tutorial" for more details
  423. */
  424. /** @brief Calculates the weighted sum of two arrays.
  425. The function addWeighted calculates the weighted sum of two arrays as follows:
  426. \f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{src1} (I)* \texttt{alpha} + \texttt{src2} (I)* \texttt{beta} + \texttt{gamma} )\f]
  427. where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each
  428. channel is processed independently.
  429. The function can be replaced with a matrix expression:
  430. @code{.cpp}
  431. dst = src1*alpha + src2*beta + gamma;
  432. @endcode
  433. @note Saturation is not applied when the output array has the depth CV_32S. You may even get
  434. result of an incorrect sign in the case of overflow.
  435. @param src1 first input array.
  436. @param alpha weight of the first array elements.
  437. @param src2 second input array of the same size and channel number as src1.
  438. @param beta weight of the second array elements.
  439. @param gamma scalar added to each sum.
  440. @param dst output array that has the same size and number of channels as the input arrays.
  441. @param dtype optional depth of the output array; when both input arrays have the same depth, dtype
  442. can be set to -1, which will be equivalent to src1.depth().
  443. @sa add, subtract, scaleAdd, Mat::convertTo
  444. */
  445. CV_EXPORTS_W void addWeighted(InputArray src1, double alpha, InputArray src2,
  446. double beta, double gamma, OutputArray dst, int dtype = -1);
  447. /** @brief Scales, calculates absolute values, and converts the result to 8-bit.
  448. On each element of the input array, the function convertScaleAbs
  449. performs three operations sequentially: scaling, taking an absolute
  450. value, conversion to an unsigned 8-bit type:
  451. \f[\texttt{dst} (I)= \texttt{saturate\_cast<uchar>} (| \texttt{src} (I)* \texttt{alpha} + \texttt{beta} |)\f]
  452. In case of multi-channel arrays, the function processes each channel
  453. independently. When the output is not 8-bit, the operation can be
  454. emulated by calling the Mat::convertTo method (or by using matrix
  455. expressions) and then by calculating an absolute value of the result.
  456. For example:
  457. @code{.cpp}
  458. Mat_<float> A(30,30);
  459. randu(A, Scalar(-100), Scalar(100));
  460. Mat_<float> B = A*5 + 3;
  461. B = abs(B);
  462. // Mat_<float> B = abs(A*5+3) will also do the job,
  463. // but it will allocate a temporary matrix
  464. @endcode
  465. @param src input array.
  466. @param dst output array.
  467. @param alpha optional scale factor.
  468. @param beta optional delta added to the scaled values.
  469. @sa Mat::convertTo, cv::abs(const Mat&)
  470. */
  471. CV_EXPORTS_W void convertScaleAbs(InputArray src, OutputArray dst,
  472. double alpha = 1, double beta = 0);
  473. /** @brief Converts an array to half precision floating number.
  474. This function converts FP32 (single precision floating point) from/to FP16 (half precision floating point). CV_16S format is used to represent FP16 data.
  475. There are two use modes (src -> dst): CV_32F -> CV_16S and CV_16S -> CV_32F. The input array has to have type of CV_32F or
  476. CV_16S to represent the bit depth. If the input array is neither of them, the function will raise an error.
  477. The format of half precision floating point is defined in IEEE 754-2008.
  478. @param src input array.
  479. @param dst output array.
  480. */
  481. CV_EXPORTS_W void convertFp16(InputArray src, OutputArray dst);
  482. /** @brief Performs a look-up table transform of an array.
  483. The function LUT fills the output array with values from the look-up table. Indices of the entries
  484. are taken from the input array. That is, the function processes each element of src as follows:
  485. \f[\texttt{dst} (I) \leftarrow \texttt{lut(src(I) + d)}\f]
  486. where
  487. \f[d = \fork{0}{if \(\texttt{src}\) has depth \(\texttt{CV_8U}\)}{128}{if \(\texttt{src}\) has depth \(\texttt{CV_8S}\)}\f]
  488. @param src input array of 8-bit elements.
  489. @param lut look-up table of 256 elements; in case of multi-channel input array, the table should
  490. either have a single channel (in this case the same table is used for all channels) or the same
  491. number of channels as in the input array.
  492. @param dst output array of the same size and number of channels as src, and the same depth as lut.
  493. @sa convertScaleAbs, Mat::convertTo
  494. */
  495. CV_EXPORTS_W void LUT(InputArray src, InputArray lut, OutputArray dst);
  496. /** @brief Calculates the sum of array elements.
  497. The function cv::sum calculates and returns the sum of array elements,
  498. independently for each channel.
  499. @param src input array that must have from 1 to 4 channels.
  500. @sa countNonZero, mean, meanStdDev, norm, minMaxLoc, reduce
  501. */
  502. CV_EXPORTS_AS(sumElems) Scalar sum(InputArray src);
  503. /** @brief Counts non-zero array elements.
  504. The function returns the number of non-zero elements in src :
  505. \f[\sum _{I: \; \texttt{src} (I) \ne0 } 1\f]
  506. @param src single-channel array.
  507. @sa mean, meanStdDev, norm, minMaxLoc, calcCovarMatrix
  508. */
  509. CV_EXPORTS_W int countNonZero( InputArray src );
  510. /** @brief Returns the list of locations of non-zero pixels
  511. Given a binary matrix (likely returned from an operation such
  512. as threshold(), compare(), >, ==, etc, return all of
  513. the non-zero indices as a cv::Mat or std::vector<cv::Point> (x,y)
  514. For example:
  515. @code{.cpp}
  516. cv::Mat binaryImage; // input, binary image
  517. cv::Mat locations; // output, locations of non-zero pixels
  518. cv::findNonZero(binaryImage, locations);
  519. // access pixel coordinates
  520. Point pnt = locations.at<Point>(i);
  521. @endcode
  522. or
  523. @code{.cpp}
  524. cv::Mat binaryImage; // input, binary image
  525. vector<Point> locations; // output, locations of non-zero pixels
  526. cv::findNonZero(binaryImage, locations);
  527. // access pixel coordinates
  528. Point pnt = locations[i];
  529. @endcode
  530. @param src single-channel array
  531. @param idx the output array, type of cv::Mat or std::vector<Point>, corresponding to non-zero indices in the input
  532. */
  533. CV_EXPORTS_W void findNonZero( InputArray src, OutputArray idx );
  534. /** @brief Calculates an average (mean) of array elements.
  535. The function cv::mean calculates the mean value M of array elements,
  536. independently for each channel, and return it:
  537. \f[\begin{array}{l} N = \sum _{I: \; \texttt{mask} (I) \ne 0} 1 \\ M_c = \left ( \sum _{I: \; \texttt{mask} (I) \ne 0}{ \texttt{mtx} (I)_c} \right )/N \end{array}\f]
  538. When all the mask elements are 0's, the function returns Scalar::all(0)
  539. @param src input array that should have from 1 to 4 channels so that the result can be stored in
  540. Scalar_ .
  541. @param mask optional operation mask.
  542. @sa countNonZero, meanStdDev, norm, minMaxLoc
  543. */
  544. CV_EXPORTS_W Scalar mean(InputArray src, InputArray mask = noArray());
  545. /** Calculates a mean and standard deviation of array elements.
  546. The function cv::meanStdDev calculates the mean and the standard deviation M
  547. of array elements independently for each channel and returns it via the
  548. output parameters:
  549. \f[\begin{array}{l} N = \sum _{I, \texttt{mask} (I) \ne 0} 1 \\ \texttt{mean} _c = \frac{\sum_{ I: \; \texttt{mask}(I) \ne 0} \texttt{src} (I)_c}{N} \\ \texttt{stddev} _c = \sqrt{\frac{\sum_{ I: \; \texttt{mask}(I) \ne 0} \left ( \texttt{src} (I)_c - \texttt{mean} _c \right )^2}{N}} \end{array}\f]
  550. When all the mask elements are 0's, the function returns
  551. mean=stddev=Scalar::all(0).
  552. @note The calculated standard deviation is only the diagonal of the
  553. complete normalized covariance matrix. If the full matrix is needed, you
  554. can reshape the multi-channel array M x N to the single-channel array
  555. M\*N x mtx.channels() (only possible when the matrix is continuous) and
  556. then pass the matrix to calcCovarMatrix .
  557. @param src input array that should have from 1 to 4 channels so that the results can be stored in
  558. Scalar_ 's.
  559. @param mean output parameter: calculated mean value.
  560. @param stddev output parameter: calculated standard deviation.
  561. @param mask optional operation mask.
  562. @sa countNonZero, mean, norm, minMaxLoc, calcCovarMatrix
  563. */
  564. CV_EXPORTS_W void meanStdDev(InputArray src, OutputArray mean, OutputArray stddev,
  565. InputArray mask=noArray());
  566. /** @brief Calculates the absolute norm of an array.
  567. This version of #norm calculates the absolute norm of src1. The type of norm to calculate is specified using #NormTypes.
  568. As example for one array consider the function \f$r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\f$.
  569. The \f$ L_{1}, L_{2} \f$ and \f$ L_{\infty} \f$ norm for the sample value \f$r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\f$
  570. is calculated as follows
  571. \f{align*}
  572. \| r(-1) \|_{L_1} &= |-1| + |2| = 3 \\
  573. \| r(-1) \|_{L_2} &= \sqrt{(-1)^{2} + (2)^{2}} = \sqrt{5} \\
  574. \| r(-1) \|_{L_\infty} &= \max(|-1|,|2|) = 2
  575. \f}
  576. and for \f$r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\f$ the calculation is
  577. \f{align*}
  578. \| r(0.5) \|_{L_1} &= |0.5| + |0.5| = 1 \\
  579. \| r(0.5) \|_{L_2} &= \sqrt{(0.5)^{2} + (0.5)^{2}} = \sqrt{0.5} \\
  580. \| r(0.5) \|_{L_\infty} &= \max(|0.5|,|0.5|) = 0.5.
  581. \f}
  582. The following graphic shows all values for the three norm functions \f$\| r(x) \|_{L_1}, \| r(x) \|_{L_2}\f$ and \f$\| r(x) \|_{L_\infty}\f$.
  583. It is notable that the \f$ L_{1} \f$ norm forms the upper and the \f$ L_{\infty} \f$ norm forms the lower border for the example function \f$ r(x) \f$.
  584. ![Graphs for the different norm functions from the above example](pics/NormTypes_OneArray_1-2-INF.png)
  585. When the mask parameter is specified and it is not empty, the norm is
  586. If normType is not specified, #NORM_L2 is used.
  587. calculated only over the region specified by the mask.
  588. Multi-channel input arrays are treated as single-channel arrays, that is,
  589. the results for all channels are combined.
  590. Hamming norms can only be calculated with CV_8U depth arrays.
  591. @param src1 first input array.
  592. @param normType type of the norm (see #NormTypes).
  593. @param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type.
  594. */
  595. CV_EXPORTS_W double norm(InputArray src1, int normType = NORM_L2, InputArray mask = noArray());
  596. /** @brief Calculates an absolute difference norm or a relative difference norm.
  597. This version of cv::norm calculates the absolute difference norm
  598. or the relative difference norm of arrays src1 and src2.
  599. The type of norm to calculate is specified using #NormTypes.
  600. @param src1 first input array.
  601. @param src2 second input array of the same size and the same type as src1.
  602. @param normType type of the norm (see #NormTypes).
  603. @param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type.
  604. */
  605. CV_EXPORTS_W double norm(InputArray src1, InputArray src2,
  606. int normType = NORM_L2, InputArray mask = noArray());
  607. /** @overload
  608. @param src first input array.
  609. @param normType type of the norm (see #NormTypes).
  610. */
  611. CV_EXPORTS double norm( const SparseMat& src, int normType );
  612. /** @brief Computes the Peak Signal-to-Noise Ratio (PSNR) image quality metric.
  613. This function calculates the Peak Signal-to-Noise Ratio (PSNR) image quality metric in decibels (dB),
  614. between two input arrays src1 and src2. The arrays must have the same type.
  615. The PSNR is calculated as follows:
  616. \f[
  617. \texttt{PSNR} = 10 \cdot \log_{10}{\left( \frac{R^2}{MSE} \right) }
  618. \f]
  619. where R is the maximum integer value of depth (e.g. 255 in the case of CV_8U data)
  620. and MSE is the mean squared error between the two arrays.
  621. @param src1 first input array.
  622. @param src2 second input array of the same size as src1.
  623. @param R the maximum pixel value (255 by default)
  624. */
  625. CV_EXPORTS_W double PSNR(InputArray src1, InputArray src2, double R=255.);
  626. /** @brief naive nearest neighbor finder
  627. see http://en.wikipedia.org/wiki/Nearest_neighbor_search
  628. @todo document
  629. */
  630. CV_EXPORTS_W void batchDistance(InputArray src1, InputArray src2,
  631. OutputArray dist, int dtype, OutputArray nidx,
  632. int normType = NORM_L2, int K = 0,
  633. InputArray mask = noArray(), int update = 0,
  634. bool crosscheck = false);
  635. /** @brief Normalizes the norm or value range of an array.
  636. The function cv::normalize normalizes scale and shift the input array elements so that
  637. \f[\| \texttt{dst} \| _{L_p}= \texttt{alpha}\f]
  638. (where p=Inf, 1 or 2) when normType=NORM_INF, NORM_L1, or NORM_L2, respectively; or so that
  639. \f[\min _I \texttt{dst} (I)= \texttt{alpha} , \, \, \max _I \texttt{dst} (I)= \texttt{beta}\f]
  640. when normType=NORM_MINMAX (for dense arrays only). The optional mask specifies a sub-array to be
  641. normalized. This means that the norm or min-n-max are calculated over the sub-array, and then this
  642. sub-array is modified to be normalized. If you want to only use the mask to calculate the norm or
  643. min-max but modify the whole array, you can use norm and Mat::convertTo.
  644. In case of sparse matrices, only the non-zero values are analyzed and transformed. Because of this,
  645. the range transformation for sparse matrices is not allowed since it can shift the zero level.
  646. Possible usage with some positive example data:
  647. @code{.cpp}
  648. vector<double> positiveData = { 2.0, 8.0, 10.0 };
  649. vector<double> normalizedData_l1, normalizedData_l2, normalizedData_inf, normalizedData_minmax;
  650. // Norm to probability (total count)
  651. // sum(numbers) = 20.0
  652. // 2.0 0.1 (2.0/20.0)
  653. // 8.0 0.4 (8.0/20.0)
  654. // 10.0 0.5 (10.0/20.0)
  655. normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1);
  656. // Norm to unit vector: ||positiveData|| = 1.0
  657. // 2.0 0.15
  658. // 8.0 0.62
  659. // 10.0 0.77
  660. normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2);
  661. // Norm to max element
  662. // 2.0 0.2 (2.0/10.0)
  663. // 8.0 0.8 (8.0/10.0)
  664. // 10.0 1.0 (10.0/10.0)
  665. normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF);
  666. // Norm to range [0.0;1.0]
  667. // 2.0 0.0 (shift to left border)
  668. // 8.0 0.75 (6.0/8.0)
  669. // 10.0 1.0 (shift to right border)
  670. normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX);
  671. @endcode
  672. @param src input array.
  673. @param dst output array of the same size as src .
  674. @param alpha norm value to normalize to or the lower range boundary in case of the range
  675. normalization.
  676. @param beta upper range boundary in case of the range normalization; it is not used for the norm
  677. normalization.
  678. @param norm_type normalization type (see cv::NormTypes).
  679. @param dtype when negative, the output array has the same type as src; otherwise, it has the same
  680. number of channels as src and the depth =CV_MAT_DEPTH(dtype).
  681. @param mask optional operation mask.
  682. @sa norm, Mat::convertTo, SparseMat::convertTo
  683. */
  684. CV_EXPORTS_W void normalize( InputArray src, InputOutputArray dst, double alpha = 1, double beta = 0,
  685. int norm_type = NORM_L2, int dtype = -1, InputArray mask = noArray());
  686. /** @overload
  687. @param src input array.
  688. @param dst output array of the same size as src .
  689. @param alpha norm value to normalize to or the lower range boundary in case of the range
  690. normalization.
  691. @param normType normalization type (see cv::NormTypes).
  692. */
  693. CV_EXPORTS void normalize( const SparseMat& src, SparseMat& dst, double alpha, int normType );
  694. /** @brief Finds the global minimum and maximum in an array.
  695. The function cv::minMaxLoc finds the minimum and maximum element values and their positions. The
  696. extremums are searched across the whole array or, if mask is not an empty array, in the specified
  697. array region.
  698. The function do not work with multi-channel arrays. If you need to find minimum or maximum
  699. elements across all the channels, use Mat::reshape first to reinterpret the array as
  700. single-channel. Or you may extract the particular channel using either extractImageCOI , or
  701. mixChannels , or split .
  702. @param src input single-channel array.
  703. @param minVal pointer to the returned minimum value; NULL is used if not required.
  704. @param maxVal pointer to the returned maximum value; NULL is used if not required.
  705. @param minLoc pointer to the returned minimum location (in 2D case); NULL is used if not required.
  706. @param maxLoc pointer to the returned maximum location (in 2D case); NULL is used if not required.
  707. @param mask optional mask used to select a sub-array.
  708. @sa max, min, reduceArgMin, reduceArgMax, compare, inRange, extractImageCOI, mixChannels, split, Mat::reshape
  709. */
  710. CV_EXPORTS_W void minMaxLoc(InputArray src, CV_OUT double* minVal,
  711. CV_OUT double* maxVal = 0, CV_OUT Point* minLoc = 0,
  712. CV_OUT Point* maxLoc = 0, InputArray mask = noArray());
  713. /**
  714. * @brief Finds indices of min elements along provided axis
  715. *
  716. * @note
  717. * - If input or output array is not continuous, this function will create an internal copy.
  718. * - NaN handling is left unspecified, see patchNaNs().
  719. * - The returned index is always in bounds of input matrix.
  720. *
  721. * @param src input single-channel array.
  722. * @param dst output array of type CV_32SC1 with the same dimensionality as src,
  723. * except for axis being reduced - it should be set to 1.
  724. * @param lastIndex whether to get the index of first or last occurrence of min.
  725. * @param axis axis to reduce along.
  726. * @sa reduceArgMax, minMaxLoc, min, max, compare, reduce
  727. */
  728. CV_EXPORTS_W void reduceArgMin(InputArray src, OutputArray dst, int axis, bool lastIndex = false);
  729. /**
  730. * @brief Finds indices of max elements along provided axis
  731. *
  732. * @note
  733. * - If input or output array is not continuous, this function will create an internal copy.
  734. * - NaN handling is left unspecified, see patchNaNs().
  735. * - The returned index is always in bounds of input matrix.
  736. *
  737. * @param src input single-channel array.
  738. * @param dst output array of type CV_32SC1 with the same dimensionality as src,
  739. * except for axis being reduced - it should be set to 1.
  740. * @param lastIndex whether to get the index of first or last occurrence of max.
  741. * @param axis axis to reduce along.
  742. * @sa reduceArgMin, minMaxLoc, min, max, compare, reduce
  743. */
  744. CV_EXPORTS_W void reduceArgMax(InputArray src, OutputArray dst, int axis, bool lastIndex = false);
  745. /** @brief Finds the global minimum and maximum in an array
  746. The function cv::minMaxIdx finds the minimum and maximum element values and their positions. The
  747. extremums are searched across the whole array or, if mask is not an empty array, in the specified
  748. array region. The function does not work with multi-channel arrays. If you need to find minimum or
  749. maximum elements across all the channels, use Mat::reshape first to reinterpret the array as
  750. single-channel. Or you may extract the particular channel using either extractImageCOI , or
  751. mixChannels , or split . In case of a sparse matrix, the minimum is found among non-zero elements
  752. only.
  753. @note When minIdx is not NULL, it must have at least 2 elements (as well as maxIdx), even if src is
  754. a single-row or single-column matrix. In OpenCV (following MATLAB) each array has at least 2
  755. dimensions, i.e. single-column matrix is Mx1 matrix (and therefore minIdx/maxIdx will be
  756. (i1,0)/(i2,0)) and single-row matrix is 1xN matrix (and therefore minIdx/maxIdx will be
  757. (0,j1)/(0,j2)).
  758. @param src input single-channel array.
  759. @param minVal pointer to the returned minimum value; NULL is used if not required.
  760. @param maxVal pointer to the returned maximum value; NULL is used if not required.
  761. @param minIdx pointer to the returned minimum location (in nD case); NULL is used if not required;
  762. Otherwise, it must point to an array of src.dims elements, the coordinates of the minimum element
  763. in each dimension are stored there sequentially.
  764. @param maxIdx pointer to the returned maximum location (in nD case). NULL is used if not required.
  765. @param mask specified array region
  766. */
  767. CV_EXPORTS void minMaxIdx(InputArray src, double* minVal, double* maxVal = 0,
  768. int* minIdx = 0, int* maxIdx = 0, InputArray mask = noArray());
  769. /** @overload
  770. @param a input single-channel array.
  771. @param minVal pointer to the returned minimum value; NULL is used if not required.
  772. @param maxVal pointer to the returned maximum value; NULL is used if not required.
  773. @param minIdx pointer to the returned minimum location (in nD case); NULL is used if not required;
  774. Otherwise, it must point to an array of src.dims elements, the coordinates of the minimum element
  775. in each dimension are stored there sequentially.
  776. @param maxIdx pointer to the returned maximum location (in nD case). NULL is used if not required.
  777. */
  778. CV_EXPORTS void minMaxLoc(const SparseMat& a, double* minVal,
  779. double* maxVal, int* minIdx = 0, int* maxIdx = 0);
  780. /** @brief Reduces a matrix to a vector.
  781. The function #reduce reduces the matrix to a vector by treating the matrix rows/columns as a set of
  782. 1D vectors and performing the specified operation on the vectors until a single row/column is
  783. obtained. For example, the function can be used to compute horizontal and vertical projections of a
  784. raster image. In case of #REDUCE_MAX and #REDUCE_MIN , the output image should have the same type as the source one.
  785. In case of #REDUCE_SUM and #REDUCE_AVG , the output may have a larger element bit-depth to preserve accuracy.
  786. And multi-channel arrays are also supported in these two reduction modes.
  787. The following code demonstrates its usage for a single channel matrix.
  788. @snippet snippets/core_reduce.cpp example
  789. And the following code demonstrates its usage for a two-channel matrix.
  790. @snippet snippets/core_reduce.cpp example2
  791. @param src input 2D matrix.
  792. @param dst output vector. Its size and type is defined by dim and dtype parameters.
  793. @param dim dimension index along which the matrix is reduced. 0 means that the matrix is reduced to
  794. a single row. 1 means that the matrix is reduced to a single column.
  795. @param rtype reduction operation that could be one of #ReduceTypes
  796. @param dtype when negative, the output vector will have the same type as the input matrix,
  797. otherwise, its type will be CV_MAKE_TYPE(CV_MAT_DEPTH(dtype), src.channels()).
  798. @sa repeat, reduceArgMin, reduceArgMax
  799. */
  800. CV_EXPORTS_W void reduce(InputArray src, OutputArray dst, int dim, int rtype, int dtype = -1);
  801. /** @brief Creates one multi-channel array out of several single-channel ones.
  802. The function cv::merge merges several arrays to make a single multi-channel array. That is, each
  803. element of the output array will be a concatenation of the elements of the input arrays, where
  804. elements of i-th input array are treated as mv[i].channels()-element vectors.
  805. The function cv::split does the reverse operation. If you need to shuffle channels in some other
  806. advanced way, use cv::mixChannels.
  807. The following example shows how to merge 3 single channel matrices into a single 3-channel matrix.
  808. @snippet snippets/core_merge.cpp example
  809. @param mv input array of matrices to be merged; all the matrices in mv must have the same
  810. size and the same depth.
  811. @param count number of input matrices when mv is a plain C array; it must be greater than zero.
  812. @param dst output array of the same size and the same depth as mv[0]; The number of channels will
  813. be equal to the parameter count.
  814. @sa mixChannels, split, Mat::reshape
  815. */
  816. CV_EXPORTS void merge(const Mat* mv, size_t count, OutputArray dst);
  817. /** @overload
  818. @param mv input vector of matrices to be merged; all the matrices in mv must have the same
  819. size and the same depth.
  820. @param dst output array of the same size and the same depth as mv[0]; The number of channels will
  821. be the total number of channels in the matrix array.
  822. */
  823. CV_EXPORTS_W void merge(InputArrayOfArrays mv, OutputArray dst);
  824. /** @brief Divides a multi-channel array into several single-channel arrays.
  825. The function cv::split splits a multi-channel array into separate single-channel arrays:
  826. \f[\texttt{mv} [c](I) = \texttt{src} (I)_c\f]
  827. If you need to extract a single channel or do some other sophisticated channel permutation, use
  828. mixChannels .
  829. The following example demonstrates how to split a 3-channel matrix into 3 single channel matrices.
  830. @snippet snippets/core_split.cpp example
  831. @param src input multi-channel array.
  832. @param mvbegin output array; the number of arrays must match src.channels(); the arrays themselves are
  833. reallocated, if needed.
  834. @sa merge, mixChannels, cvtColor
  835. */
  836. CV_EXPORTS void split(const Mat& src, Mat* mvbegin);
  837. /** @overload
  838. @param m input multi-channel array.
  839. @param mv output vector of arrays; the arrays themselves are reallocated, if needed.
  840. */
  841. CV_EXPORTS_W void split(InputArray m, OutputArrayOfArrays mv);
  842. /** @brief Copies specified channels from input arrays to the specified channels of
  843. output arrays.
  844. The function cv::mixChannels provides an advanced mechanism for shuffling image channels.
  845. cv::split,cv::merge,cv::extractChannel,cv::insertChannel and some forms of cv::cvtColor are partial cases of cv::mixChannels.
  846. In the example below, the code splits a 4-channel BGRA image into a 3-channel BGR (with B and R
  847. channels swapped) and a separate alpha-channel image:
  848. @code{.cpp}
  849. Mat bgra( 100, 100, CV_8UC4, Scalar(255,0,0,255) );
  850. Mat bgr( bgra.rows, bgra.cols, CV_8UC3 );
  851. Mat alpha( bgra.rows, bgra.cols, CV_8UC1 );
  852. // forming an array of matrices is a quite efficient operation,
  853. // because the matrix data is not copied, only the headers
  854. Mat out[] = { bgr, alpha };
  855. // bgra[0] -> bgr[2], bgra[1] -> bgr[1],
  856. // bgra[2] -> bgr[0], bgra[3] -> alpha[0]
  857. int from_to[] = { 0,2, 1,1, 2,0, 3,3 };
  858. mixChannels( &bgra, 1, out, 2, from_to, 4 );
  859. @endcode
  860. @note Unlike many other new-style C++ functions in OpenCV (see the introduction section and
  861. Mat::create ), cv::mixChannels requires the output arrays to be pre-allocated before calling the
  862. function.
  863. @param src input array or vector of matrices; all of the matrices must have the same size and the
  864. same depth.
  865. @param nsrcs number of matrices in `src`.
  866. @param dst output array or vector of matrices; all the matrices **must be allocated**; their size and
  867. depth must be the same as in `src[0]`.
  868. @param ndsts number of matrices in `dst`.
  869. @param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is
  870. a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in
  871. dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to
  872. src[0].channels()-1, the second input image channels are indexed from src[0].channels() to
  873. src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image
  874. channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is
  875. filled with zero .
  876. @param npairs number of index pairs in `fromTo`.
  877. @sa split, merge, extractChannel, insertChannel, cvtColor
  878. */
  879. CV_EXPORTS void mixChannels(const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts,
  880. const int* fromTo, size_t npairs);
  881. /** @overload
  882. @param src input array or vector of matrices; all of the matrices must have the same size and the
  883. same depth.
  884. @param dst output array or vector of matrices; all the matrices **must be allocated**; their size and
  885. depth must be the same as in src[0].
  886. @param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is
  887. a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in
  888. dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to
  889. src[0].channels()-1, the second input image channels are indexed from src[0].channels() to
  890. src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image
  891. channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is
  892. filled with zero .
  893. @param npairs number of index pairs in fromTo.
  894. */
  895. CV_EXPORTS void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst,
  896. const int* fromTo, size_t npairs);
  897. /** @overload
  898. @param src input array or vector of matrices; all of the matrices must have the same size and the
  899. same depth.
  900. @param dst output array or vector of matrices; all the matrices **must be allocated**; their size and
  901. depth must be the same as in src[0].
  902. @param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is
  903. a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in
  904. dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to
  905. src[0].channels()-1, the second input image channels are indexed from src[0].channels() to
  906. src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image
  907. channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is
  908. filled with zero .
  909. */
  910. CV_EXPORTS_W void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst,
  911. const std::vector<int>& fromTo);
  912. /** @brief Extracts a single channel from src (coi is 0-based index)
  913. @param src input array
  914. @param dst output array
  915. @param coi index of channel to extract
  916. @sa mixChannels, split
  917. */
  918. CV_EXPORTS_W void extractChannel(InputArray src, OutputArray dst, int coi);
  919. /** @brief Inserts a single channel to dst (coi is 0-based index)
  920. @param src input array
  921. @param dst output array
  922. @param coi index of channel for insertion
  923. @sa mixChannels, merge
  924. */
  925. CV_EXPORTS_W void insertChannel(InputArray src, InputOutputArray dst, int coi);
  926. /** @brief Flips a 2D array around vertical, horizontal, or both axes.
  927. The function cv::flip flips the array in one of three different ways (row
  928. and column indices are 0-based):
  929. \f[\texttt{dst} _{ij} =
  930. \left\{
  931. \begin{array}{l l}
  932. \texttt{src} _{\texttt{src.rows}-i-1,j} & if\; \texttt{flipCode} = 0 \\
  933. \texttt{src} _{i, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} > 0 \\
  934. \texttt{src} _{ \texttt{src.rows} -i-1, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} < 0 \\
  935. \end{array}
  936. \right.\f]
  937. The example scenarios of using the function are the following:
  938. * Vertical flipping of the image (flipCode == 0) to switch between
  939. top-left and bottom-left image origin. This is a typical operation
  940. in video processing on Microsoft Windows\* OS.
  941. * Horizontal flipping of the image with the subsequent horizontal
  942. shift and absolute difference calculation to check for a
  943. vertical-axis symmetry (flipCode \> 0).
  944. * Simultaneous horizontal and vertical flipping of the image with
  945. the subsequent shift and absolute difference calculation to check
  946. for a central symmetry (flipCode \< 0).
  947. * Reversing the order of point arrays (flipCode \> 0 or
  948. flipCode == 0).
  949. @param src input array.
  950. @param dst output array of the same size and type as src.
  951. @param flipCode a flag to specify how to flip the array; 0 means
  952. flipping around the x-axis and positive value (for example, 1) means
  953. flipping around y-axis. Negative value (for example, -1) means flipping
  954. around both axes.
  955. @sa transpose , repeat , completeSymm
  956. */
  957. CV_EXPORTS_W void flip(InputArray src, OutputArray dst, int flipCode);
  958. enum RotateFlags {
  959. ROTATE_90_CLOCKWISE = 0, //!<Rotate 90 degrees clockwise
  960. ROTATE_180 = 1, //!<Rotate 180 degrees clockwise
  961. ROTATE_90_COUNTERCLOCKWISE = 2, //!<Rotate 270 degrees clockwise
  962. };
  963. /** @brief Rotates a 2D array in multiples of 90 degrees.
  964. The function cv::rotate rotates the array in one of three different ways:
  965. * Rotate by 90 degrees clockwise (rotateCode = ROTATE_90_CLOCKWISE).
  966. * Rotate by 180 degrees clockwise (rotateCode = ROTATE_180).
  967. * Rotate by 270 degrees clockwise (rotateCode = ROTATE_90_COUNTERCLOCKWISE).
  968. @param src input array.
  969. @param dst output array of the same type as src. The size is the same with ROTATE_180,
  970. and the rows and cols are switched for ROTATE_90_CLOCKWISE and ROTATE_90_COUNTERCLOCKWISE.
  971. @param rotateCode an enum to specify how to rotate the array; see the enum #RotateFlags
  972. @sa transpose , repeat , completeSymm, flip, RotateFlags
  973. */
  974. CV_EXPORTS_W void rotate(InputArray src, OutputArray dst, int rotateCode);
  975. /** @brief Fills the output array with repeated copies of the input array.
  976. The function cv::repeat duplicates the input array one or more times along each of the two axes:
  977. \f[\texttt{dst} _{ij}= \texttt{src} _{i\mod src.rows, \; j\mod src.cols }\f]
  978. The second variant of the function is more convenient to use with @ref MatrixExpressions.
  979. @param src input array to replicate.
  980. @param ny Flag to specify how many times the `src` is repeated along the
  981. vertical axis.
  982. @param nx Flag to specify how many times the `src` is repeated along the
  983. horizontal axis.
  984. @param dst output array of the same type as `src`.
  985. @sa cv::reduce
  986. */
  987. CV_EXPORTS_W void repeat(InputArray src, int ny, int nx, OutputArray dst);
  988. /** @overload
  989. @param src input array to replicate.
  990. @param ny Flag to specify how many times the `src` is repeated along the
  991. vertical axis.
  992. @param nx Flag to specify how many times the `src` is repeated along the
  993. horizontal axis.
  994. */
  995. CV_EXPORTS Mat repeat(const Mat& src, int ny, int nx);
  996. /** @brief Applies horizontal concatenation to given matrices.
  997. The function horizontally concatenates two or more cv::Mat matrices (with the same number of rows).
  998. @code{.cpp}
  999. cv::Mat matArray[] = { cv::Mat(4, 1, CV_8UC1, cv::Scalar(1)),
  1000. cv::Mat(4, 1, CV_8UC1, cv::Scalar(2)),
  1001. cv::Mat(4, 1, CV_8UC1, cv::Scalar(3)),};
  1002. cv::Mat out;
  1003. cv::hconcat( matArray, 3, out );
  1004. //out:
  1005. //[1, 2, 3;
  1006. // 1, 2, 3;
  1007. // 1, 2, 3;
  1008. // 1, 2, 3]
  1009. @endcode
  1010. @param src input array or vector of matrices. all of the matrices must have the same number of rows and the same depth.
  1011. @param nsrc number of matrices in src.
  1012. @param dst output array. It has the same number of rows and depth as the src, and the sum of cols of the src.
  1013. @sa cv::vconcat(const Mat*, size_t, OutputArray), @sa cv::vconcat(InputArrayOfArrays, OutputArray) and @sa cv::vconcat(InputArray, InputArray, OutputArray)
  1014. */
  1015. CV_EXPORTS void hconcat(const Mat* src, size_t nsrc, OutputArray dst);
  1016. /** @overload
  1017. @code{.cpp}
  1018. cv::Mat_<float> A = (cv::Mat_<float>(3, 2) << 1, 4,
  1019. 2, 5,
  1020. 3, 6);
  1021. cv::Mat_<float> B = (cv::Mat_<float>(3, 2) << 7, 10,
  1022. 8, 11,
  1023. 9, 12);
  1024. cv::Mat C;
  1025. cv::hconcat(A, B, C);
  1026. //C:
  1027. //[1, 4, 7, 10;
  1028. // 2, 5, 8, 11;
  1029. // 3, 6, 9, 12]
  1030. @endcode
  1031. @param src1 first input array to be considered for horizontal concatenation.
  1032. @param src2 second input array to be considered for horizontal concatenation.
  1033. @param dst output array. It has the same number of rows and depth as the src1 and src2, and the sum of cols of the src1 and src2.
  1034. */
  1035. CV_EXPORTS void hconcat(InputArray src1, InputArray src2, OutputArray dst);
  1036. /** @overload
  1037. @code{.cpp}
  1038. std::vector<cv::Mat> matrices = { cv::Mat(4, 1, CV_8UC1, cv::Scalar(1)),
  1039. cv::Mat(4, 1, CV_8UC1, cv::Scalar(2)),
  1040. cv::Mat(4, 1, CV_8UC1, cv::Scalar(3)),};
  1041. cv::Mat out;
  1042. cv::hconcat( matrices, out );
  1043. //out:
  1044. //[1, 2, 3;
  1045. // 1, 2, 3;
  1046. // 1, 2, 3;
  1047. // 1, 2, 3]
  1048. @endcode
  1049. @param src input array or vector of matrices. all of the matrices must have the same number of rows and the same depth.
  1050. @param dst output array. It has the same number of rows and depth as the src, and the sum of cols of the src.
  1051. same depth.
  1052. */
  1053. CV_EXPORTS_W void hconcat(InputArrayOfArrays src, OutputArray dst);
  1054. /** @brief Applies vertical concatenation to given matrices.
  1055. The function vertically concatenates two or more cv::Mat matrices (with the same number of cols).
  1056. @code{.cpp}
  1057. cv::Mat matArray[] = { cv::Mat(1, 4, CV_8UC1, cv::Scalar(1)),
  1058. cv::Mat(1, 4, CV_8UC1, cv::Scalar(2)),
  1059. cv::Mat(1, 4, CV_8UC1, cv::Scalar(3)),};
  1060. cv::Mat out;
  1061. cv::vconcat( matArray, 3, out );
  1062. //out:
  1063. //[1, 1, 1, 1;
  1064. // 2, 2, 2, 2;
  1065. // 3, 3, 3, 3]
  1066. @endcode
  1067. @param src input array or vector of matrices. all of the matrices must have the same number of cols and the same depth.
  1068. @param nsrc number of matrices in src.
  1069. @param dst output array. It has the same number of cols and depth as the src, and the sum of rows of the src.
  1070. @sa cv::hconcat(const Mat*, size_t, OutputArray), @sa cv::hconcat(InputArrayOfArrays, OutputArray) and @sa cv::hconcat(InputArray, InputArray, OutputArray)
  1071. */
  1072. CV_EXPORTS void vconcat(const Mat* src, size_t nsrc, OutputArray dst);
  1073. /** @overload
  1074. @code{.cpp}
  1075. cv::Mat_<float> A = (cv::Mat_<float>(3, 2) << 1, 7,
  1076. 2, 8,
  1077. 3, 9);
  1078. cv::Mat_<float> B = (cv::Mat_<float>(3, 2) << 4, 10,
  1079. 5, 11,
  1080. 6, 12);
  1081. cv::Mat C;
  1082. cv::vconcat(A, B, C);
  1083. //C:
  1084. //[1, 7;
  1085. // 2, 8;
  1086. // 3, 9;
  1087. // 4, 10;
  1088. // 5, 11;
  1089. // 6, 12]
  1090. @endcode
  1091. @param src1 first input array to be considered for vertical concatenation.
  1092. @param src2 second input array to be considered for vertical concatenation.
  1093. @param dst output array. It has the same number of cols and depth as the src1 and src2, and the sum of rows of the src1 and src2.
  1094. */
  1095. CV_EXPORTS void vconcat(InputArray src1, InputArray src2, OutputArray dst);
  1096. /** @overload
  1097. @code{.cpp}
  1098. std::vector<cv::Mat> matrices = { cv::Mat(1, 4, CV_8UC1, cv::Scalar(1)),
  1099. cv::Mat(1, 4, CV_8UC1, cv::Scalar(2)),
  1100. cv::Mat(1, 4, CV_8UC1, cv::Scalar(3)),};
  1101. cv::Mat out;
  1102. cv::vconcat( matrices, out );
  1103. //out:
  1104. //[1, 1, 1, 1;
  1105. // 2, 2, 2, 2;
  1106. // 3, 3, 3, 3]
  1107. @endcode
  1108. @param src input array or vector of matrices. all of the matrices must have the same number of cols and the same depth
  1109. @param dst output array. It has the same number of cols and depth as the src, and the sum of rows of the src.
  1110. same depth.
  1111. */
  1112. CV_EXPORTS_W void vconcat(InputArrayOfArrays src, OutputArray dst);
  1113. /** @brief computes bitwise conjunction of the two arrays (dst = src1 & src2)
  1114. Calculates the per-element bit-wise conjunction of two arrays or an
  1115. array and a scalar.
  1116. The function cv::bitwise_and calculates the per-element bit-wise logical conjunction for:
  1117. * Two arrays when src1 and src2 have the same size:
  1118. \f[\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
  1119. * An array and a scalar when src2 is constructed from Scalar or has
  1120. the same number of elements as `src1.channels()`:
  1121. \f[\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} \quad \texttt{if mask} (I) \ne0\f]
  1122. * A scalar and an array when src1 is constructed from Scalar or has
  1123. the same number of elements as `src2.channels()`:
  1124. \f[\texttt{dst} (I) = \texttt{src1} \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
  1125. In case of floating-point arrays, their machine-specific bit
  1126. representations (usually IEEE754-compliant) are used for the operation.
  1127. In case of multi-channel arrays, each channel is processed
  1128. independently. In the second and third cases above, the scalar is first
  1129. converted to the array type.
  1130. @param src1 first input array or a scalar.
  1131. @param src2 second input array or a scalar.
  1132. @param dst output array that has the same size and type as the input
  1133. arrays.
  1134. @param mask optional operation mask, 8-bit single channel array, that
  1135. specifies elements of the output array to be changed.
  1136. */
  1137. CV_EXPORTS_W void bitwise_and(InputArray src1, InputArray src2,
  1138. OutputArray dst, InputArray mask = noArray());
  1139. /** @brief Calculates the per-element bit-wise disjunction of two arrays or an
  1140. array and a scalar.
  1141. The function cv::bitwise_or calculates the per-element bit-wise logical disjunction for:
  1142. * Two arrays when src1 and src2 have the same size:
  1143. \f[\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
  1144. * An array and a scalar when src2 is constructed from Scalar or has
  1145. the same number of elements as `src1.channels()`:
  1146. \f[\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} \quad \texttt{if mask} (I) \ne0\f]
  1147. * A scalar and an array when src1 is constructed from Scalar or has
  1148. the same number of elements as `src2.channels()`:
  1149. \f[\texttt{dst} (I) = \texttt{src1} \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
  1150. In case of floating-point arrays, their machine-specific bit
  1151. representations (usually IEEE754-compliant) are used for the operation.
  1152. In case of multi-channel arrays, each channel is processed
  1153. independently. In the second and third cases above, the scalar is first
  1154. converted to the array type.
  1155. @param src1 first input array or a scalar.
  1156. @param src2 second input array or a scalar.
  1157. @param dst output array that has the same size and type as the input
  1158. arrays.
  1159. @param mask optional operation mask, 8-bit single channel array, that
  1160. specifies elements of the output array to be changed.
  1161. */
  1162. CV_EXPORTS_W void bitwise_or(InputArray src1, InputArray src2,
  1163. OutputArray dst, InputArray mask = noArray());
  1164. /** @brief Calculates the per-element bit-wise "exclusive or" operation on two
  1165. arrays or an array and a scalar.
  1166. The function cv::bitwise_xor calculates the per-element bit-wise logical "exclusive-or"
  1167. operation for:
  1168. * Two arrays when src1 and src2 have the same size:
  1169. \f[\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
  1170. * An array and a scalar when src2 is constructed from Scalar or has
  1171. the same number of elements as `src1.channels()`:
  1172. \f[\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} \quad \texttt{if mask} (I) \ne0\f]
  1173. * A scalar and an array when src1 is constructed from Scalar or has
  1174. the same number of elements as `src2.channels()`:
  1175. \f[\texttt{dst} (I) = \texttt{src1} \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f]
  1176. In case of floating-point arrays, their machine-specific bit
  1177. representations (usually IEEE754-compliant) are used for the operation.
  1178. In case of multi-channel arrays, each channel is processed
  1179. independently. In the 2nd and 3rd cases above, the scalar is first
  1180. converted to the array type.
  1181. @param src1 first input array or a scalar.
  1182. @param src2 second input array or a scalar.
  1183. @param dst output array that has the same size and type as the input
  1184. arrays.
  1185. @param mask optional operation mask, 8-bit single channel array, that
  1186. specifies elements of the output array to be changed.
  1187. */
  1188. CV_EXPORTS_W void bitwise_xor(InputArray src1, InputArray src2,
  1189. OutputArray dst, InputArray mask = noArray());
  1190. /** @brief Inverts every bit of an array.
  1191. The function cv::bitwise_not calculates per-element bit-wise inversion of the input
  1192. array:
  1193. \f[\texttt{dst} (I) = \neg \texttt{src} (I)\f]
  1194. In case of a floating-point input array, its machine-specific bit
  1195. representation (usually IEEE754-compliant) is used for the operation. In
  1196. case of multi-channel arrays, each channel is processed independently.
  1197. @param src input array.
  1198. @param dst output array that has the same size and type as the input
  1199. array.
  1200. @param mask optional operation mask, 8-bit single channel array, that
  1201. specifies elements of the output array to be changed.
  1202. */
  1203. CV_EXPORTS_W void bitwise_not(InputArray src, OutputArray dst,
  1204. InputArray mask = noArray());
  1205. /** @brief Calculates the per-element absolute difference between two arrays or between an array and a scalar.
  1206. The function cv::absdiff calculates:
  1207. * Absolute difference between two arrays when they have the same
  1208. size and type:
  1209. \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2}(I)|)\f]
  1210. * Absolute difference between an array and a scalar when the second
  1211. array is constructed from Scalar or has as many elements as the
  1212. number of channels in `src1`:
  1213. \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2} |)\f]
  1214. * Absolute difference between a scalar and an array when the first
  1215. array is constructed from Scalar or has as many elements as the
  1216. number of channels in `src2`:
  1217. \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1} - \texttt{src2}(I) |)\f]
  1218. where I is a multi-dimensional index of array elements. In case of
  1219. multi-channel arrays, each channel is processed independently.
  1220. @note Saturation is not applied when the arrays have the depth CV_32S.
  1221. You may even get a negative value in the case of overflow.
  1222. @param src1 first input array or a scalar.
  1223. @param src2 second input array or a scalar.
  1224. @param dst output array that has the same size and type as input arrays.
  1225. @sa cv::abs(const Mat&)
  1226. */
  1227. CV_EXPORTS_W void absdiff(InputArray src1, InputArray src2, OutputArray dst);
  1228. /** @brief This is an overloaded member function, provided for convenience (python)
  1229. Copies the matrix to another one.
  1230. When the operation mask is specified, if the Mat::create call shown above reallocates the matrix, the newly allocated matrix is initialized with all zeros before copying the data.
  1231. @param src source matrix.
  1232. @param dst Destination matrix. If it does not have a proper size or type before the operation, it is
  1233. reallocated.
  1234. @param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix
  1235. elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels.
  1236. */
  1237. void CV_EXPORTS_W copyTo(InputArray src, OutputArray dst, InputArray mask);
  1238. /** @brief Checks if array elements lie between the elements of two other arrays.
  1239. The function checks the range as follows:
  1240. - For every element of a single-channel input array:
  1241. \f[\texttt{dst} (I)= \texttt{lowerb} (I)_0 \leq \texttt{src} (I)_0 \leq \texttt{upperb} (I)_0\f]
  1242. - For two-channel arrays:
  1243. \f[\texttt{dst} (I)= \texttt{lowerb} (I)_0 \leq \texttt{src} (I)_0 \leq \texttt{upperb} (I)_0 \land \texttt{lowerb} (I)_1 \leq \texttt{src} (I)_1 \leq \texttt{upperb} (I)_1\f]
  1244. - and so forth.
  1245. That is, dst (I) is set to 255 (all 1 -bits) if src (I) is within the
  1246. specified 1D, 2D, 3D, ... box and 0 otherwise.
  1247. When the lower and/or upper boundary parameters are scalars, the indexes
  1248. (I) at lowerb and upperb in the above formulas should be omitted.
  1249. @param src first input array.
  1250. @param lowerb inclusive lower boundary array or a scalar.
  1251. @param upperb inclusive upper boundary array or a scalar.
  1252. @param dst output array of the same size as src and CV_8U type.
  1253. */
  1254. CV_EXPORTS_W void inRange(InputArray src, InputArray lowerb,
  1255. InputArray upperb, OutputArray dst);
  1256. /** @brief Performs the per-element comparison of two arrays or an array and scalar value.
  1257. The function compares:
  1258. * Elements of two arrays when src1 and src2 have the same size:
  1259. \f[\texttt{dst} (I) = \texttt{src1} (I) \,\texttt{cmpop}\, \texttt{src2} (I)\f]
  1260. * Elements of src1 with a scalar src2 when src2 is constructed from
  1261. Scalar or has a single element:
  1262. \f[\texttt{dst} (I) = \texttt{src1}(I) \,\texttt{cmpop}\, \texttt{src2}\f]
  1263. * src1 with elements of src2 when src1 is constructed from Scalar or
  1264. has a single element:
  1265. \f[\texttt{dst} (I) = \texttt{src1} \,\texttt{cmpop}\, \texttt{src2} (I)\f]
  1266. When the comparison result is true, the corresponding element of output
  1267. array is set to 255. The comparison operations can be replaced with the
  1268. equivalent matrix expressions:
  1269. @code{.cpp}
  1270. Mat dst1 = src1 >= src2;
  1271. Mat dst2 = src1 < 8;
  1272. ...
  1273. @endcode
  1274. @param src1 first input array or a scalar; when it is an array, it must have a single channel.
  1275. @param src2 second input array or a scalar; when it is an array, it must have a single channel.
  1276. @param dst output array of type ref CV_8U that has the same size and the same number of channels as
  1277. the input arrays.
  1278. @param cmpop a flag, that specifies correspondence between the arrays (cv::CmpTypes)
  1279. @sa checkRange, min, max, threshold
  1280. */
  1281. CV_EXPORTS_W void compare(InputArray src1, InputArray src2, OutputArray dst, int cmpop);
  1282. /** @brief Calculates per-element minimum of two arrays or an array and a scalar.
  1283. The function cv::min calculates the per-element minimum of two arrays:
  1284. \f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{src2} (I))\f]
  1285. or array and a scalar:
  1286. \f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{value} )\f]
  1287. @param src1 first input array.
  1288. @param src2 second input array of the same size and type as src1.
  1289. @param dst output array of the same size and type as src1.
  1290. @sa max, compare, inRange, minMaxLoc
  1291. */
  1292. CV_EXPORTS_W void min(InputArray src1, InputArray src2, OutputArray dst);
  1293. /** @overload
  1294. needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare)
  1295. */
  1296. CV_EXPORTS void min(const Mat& src1, const Mat& src2, Mat& dst);
  1297. /** @overload
  1298. needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare)
  1299. */
  1300. CV_EXPORTS void min(const UMat& src1, const UMat& src2, UMat& dst);
  1301. /** @brief Calculates per-element maximum of two arrays or an array and a scalar.
  1302. The function cv::max calculates the per-element maximum of two arrays:
  1303. \f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{src2} (I))\f]
  1304. or array and a scalar:
  1305. \f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{value} )\f]
  1306. @param src1 first input array.
  1307. @param src2 second input array of the same size and type as src1 .
  1308. @param dst output array of the same size and type as src1.
  1309. @sa min, compare, inRange, minMaxLoc, @ref MatrixExpressions
  1310. */
  1311. CV_EXPORTS_W void max(InputArray src1, InputArray src2, OutputArray dst);
  1312. /** @overload
  1313. needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare)
  1314. */
  1315. CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst);
  1316. /** @overload
  1317. needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare)
  1318. */
  1319. CV_EXPORTS void max(const UMat& src1, const UMat& src2, UMat& dst);
  1320. /** @brief Calculates a square root of array elements.
  1321. The function cv::sqrt calculates a square root of each input array element.
  1322. In case of multi-channel arrays, each channel is processed
  1323. independently. The accuracy is approximately the same as of the built-in
  1324. std::sqrt .
  1325. @param src input floating-point array.
  1326. @param dst output array of the same size and type as src.
  1327. */
  1328. CV_EXPORTS_W void sqrt(InputArray src, OutputArray dst);
  1329. /** @brief Raises every array element to a power.
  1330. The function cv::pow raises every element of the input array to power :
  1331. \f[\texttt{dst} (I) = \fork{\texttt{src}(I)^{power}}{if \(\texttt{power}\) is integer}{|\texttt{src}(I)|^{power}}{otherwise}\f]
  1332. So, for a non-integer power exponent, the absolute values of input array
  1333. elements are used. However, it is possible to get true values for
  1334. negative values using some extra operations. In the example below,
  1335. computing the 5th root of array src shows:
  1336. @code{.cpp}
  1337. Mat mask = src < 0;
  1338. pow(src, 1./5, dst);
  1339. subtract(Scalar::all(0), dst, dst, mask);
  1340. @endcode
  1341. For some values of power, such as integer values, 0.5 and -0.5,
  1342. specialized faster algorithms are used.
  1343. Special values (NaN, Inf) are not handled.
  1344. @param src input array.
  1345. @param power exponent of power.
  1346. @param dst output array of the same size and type as src.
  1347. @sa sqrt, exp, log, cartToPolar, polarToCart
  1348. */
  1349. CV_EXPORTS_W void pow(InputArray src, double power, OutputArray dst);
  1350. /** @brief Calculates the exponent of every array element.
  1351. The function cv::exp calculates the exponent of every element of the input
  1352. array:
  1353. \f[\texttt{dst} [I] = e^{ src(I) }\f]
  1354. The maximum relative error is about 7e-6 for single-precision input and
  1355. less than 1e-10 for double-precision input. Currently, the function
  1356. converts denormalized values to zeros on output. Special values (NaN,
  1357. Inf) are not handled.
  1358. @param src input array.
  1359. @param dst output array of the same size and type as src.
  1360. @sa log , cartToPolar , polarToCart , phase , pow , sqrt , magnitude
  1361. */
  1362. CV_EXPORTS_W void exp(InputArray src, OutputArray dst);
  1363. /** @brief Calculates the natural logarithm of every array element.
  1364. The function cv::log calculates the natural logarithm of every element of the input array:
  1365. \f[\texttt{dst} (I) = \log (\texttt{src}(I)) \f]
  1366. Output on zero, negative and special (NaN, Inf) values is undefined.
  1367. @param src input array.
  1368. @param dst output array of the same size and type as src .
  1369. @sa exp, cartToPolar, polarToCart, phase, pow, sqrt, magnitude
  1370. */
  1371. CV_EXPORTS_W void log(InputArray src, OutputArray dst);
  1372. /** @brief Calculates x and y coordinates of 2D vectors from their magnitude and angle.
  1373. The function cv::polarToCart calculates the Cartesian coordinates of each 2D
  1374. vector represented by the corresponding elements of magnitude and angle:
  1375. \f[\begin{array}{l} \texttt{x} (I) = \texttt{magnitude} (I) \cos ( \texttt{angle} (I)) \\ \texttt{y} (I) = \texttt{magnitude} (I) \sin ( \texttt{angle} (I)) \\ \end{array}\f]
  1376. The relative accuracy of the estimated coordinates is about 1e-6.
  1377. @param magnitude input floating-point array of magnitudes of 2D vectors;
  1378. it can be an empty matrix (=Mat()), in this case, the function assumes
  1379. that all the magnitudes are =1; if it is not empty, it must have the
  1380. same size and type as angle.
  1381. @param angle input floating-point array of angles of 2D vectors.
  1382. @param x output array of x-coordinates of 2D vectors; it has the same
  1383. size and type as angle.
  1384. @param y output array of y-coordinates of 2D vectors; it has the same
  1385. size and type as angle.
  1386. @param angleInDegrees when true, the input angles are measured in
  1387. degrees, otherwise, they are measured in radians.
  1388. @sa cartToPolar, magnitude, phase, exp, log, pow, sqrt
  1389. */
  1390. CV_EXPORTS_W void polarToCart(InputArray magnitude, InputArray angle,
  1391. OutputArray x, OutputArray y, bool angleInDegrees = false);
  1392. /** @brief Calculates the magnitude and angle of 2D vectors.
  1393. The function cv::cartToPolar calculates either the magnitude, angle, or both
  1394. for every 2D vector (x(I),y(I)):
  1395. \f[\begin{array}{l} \texttt{magnitude} (I)= \sqrt{\texttt{x}(I)^2+\texttt{y}(I)^2} , \\ \texttt{angle} (I)= \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))[ \cdot180 / \pi ] \end{array}\f]
  1396. The angles are calculated with accuracy about 0.3 degrees. For the point
  1397. (0,0), the angle is set to 0.
  1398. @param x array of x-coordinates; this must be a single-precision or
  1399. double-precision floating-point array.
  1400. @param y array of y-coordinates, that must have the same size and same type as x.
  1401. @param magnitude output array of magnitudes of the same size and type as x.
  1402. @param angle output array of angles that has the same size and type as
  1403. x; the angles are measured in radians (from 0 to 2\*Pi) or in degrees (0 to 360 degrees).
  1404. @param angleInDegrees a flag, indicating whether the angles are measured
  1405. in radians (which is by default), or in degrees.
  1406. @sa Sobel, Scharr
  1407. */
  1408. CV_EXPORTS_W void cartToPolar(InputArray x, InputArray y,
  1409. OutputArray magnitude, OutputArray angle,
  1410. bool angleInDegrees = false);
  1411. /** @brief Calculates the rotation angle of 2D vectors.
  1412. The function cv::phase calculates the rotation angle of each 2D vector that
  1413. is formed from the corresponding elements of x and y :
  1414. \f[\texttt{angle} (I) = \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))\f]
  1415. The angle estimation accuracy is about 0.3 degrees. When x(I)=y(I)=0 ,
  1416. the corresponding angle(I) is set to 0.
  1417. @param x input floating-point array of x-coordinates of 2D vectors.
  1418. @param y input array of y-coordinates of 2D vectors; it must have the
  1419. same size and the same type as x.
  1420. @param angle output array of vector angles; it has the same size and
  1421. same type as x .
  1422. @param angleInDegrees when true, the function calculates the angle in
  1423. degrees, otherwise, they are measured in radians.
  1424. */
  1425. CV_EXPORTS_W void phase(InputArray x, InputArray y, OutputArray angle,
  1426. bool angleInDegrees = false);
  1427. /** @brief Calculates the magnitude of 2D vectors.
  1428. The function cv::magnitude calculates the magnitude of 2D vectors formed
  1429. from the corresponding elements of x and y arrays:
  1430. \f[\texttt{dst} (I) = \sqrt{\texttt{x}(I)^2 + \texttt{y}(I)^2}\f]
  1431. @param x floating-point array of x-coordinates of the vectors.
  1432. @param y floating-point array of y-coordinates of the vectors; it must
  1433. have the same size as x.
  1434. @param magnitude output array of the same size and type as x.
  1435. @sa cartToPolar, polarToCart, phase, sqrt
  1436. */
  1437. CV_EXPORTS_W void magnitude(InputArray x, InputArray y, OutputArray magnitude);
  1438. /** @brief Checks every element of an input array for invalid values.
  1439. The function cv::checkRange checks that every array element is neither NaN nor infinite. When minVal \>
  1440. -DBL_MAX and maxVal \< DBL_MAX, the function also checks that each value is between minVal and
  1441. maxVal. In case of multi-channel arrays, each channel is processed independently. If some values
  1442. are out of range, position of the first outlier is stored in pos (when pos != NULL). Then, the
  1443. function either returns false (when quiet=true) or throws an exception.
  1444. @param a input array.
  1445. @param quiet a flag, indicating whether the functions quietly return false when the array elements
  1446. are out of range or they throw an exception.
  1447. @param pos optional output parameter, when not NULL, must be a pointer to array of src.dims
  1448. elements.
  1449. @param minVal inclusive lower boundary of valid values range.
  1450. @param maxVal exclusive upper boundary of valid values range.
  1451. */
  1452. CV_EXPORTS_W bool checkRange(InputArray a, bool quiet = true, CV_OUT Point* pos = 0,
  1453. double minVal = -DBL_MAX, double maxVal = DBL_MAX);
  1454. /** @brief converts NaNs to the given number
  1455. @param a input/output matrix (CV_32F type).
  1456. @param val value to convert the NaNs
  1457. */
  1458. CV_EXPORTS_W void patchNaNs(InputOutputArray a, double val = 0);
  1459. /** @brief Performs generalized matrix multiplication.
  1460. The function cv::gemm performs generalized matrix multiplication similar to the
  1461. gemm functions in BLAS level 3. For example,
  1462. `gemm(src1, src2, alpha, src3, beta, dst, GEMM_1_T + GEMM_3_T)`
  1463. corresponds to
  1464. \f[\texttt{dst} = \texttt{alpha} \cdot \texttt{src1} ^T \cdot \texttt{src2} + \texttt{beta} \cdot \texttt{src3} ^T\f]
  1465. In case of complex (two-channel) data, performed a complex matrix
  1466. multiplication.
  1467. The function can be replaced with a matrix expression. For example, the
  1468. above call can be replaced with:
  1469. @code{.cpp}
  1470. dst = alpha*src1.t()*src2 + beta*src3.t();
  1471. @endcode
  1472. @param src1 first multiplied input matrix that could be real(CV_32FC1,
  1473. CV_64FC1) or complex(CV_32FC2, CV_64FC2).
  1474. @param src2 second multiplied input matrix of the same type as src1.
  1475. @param alpha weight of the matrix product.
  1476. @param src3 third optional delta matrix added to the matrix product; it
  1477. should have the same type as src1 and src2.
  1478. @param beta weight of src3.
  1479. @param dst output matrix; it has the proper size and the same type as
  1480. input matrices.
  1481. @param flags operation flags (cv::GemmFlags)
  1482. @sa mulTransposed , transform
  1483. */
  1484. CV_EXPORTS_W void gemm(InputArray src1, InputArray src2, double alpha,
  1485. InputArray src3, double beta, OutputArray dst, int flags = 0);
  1486. /** @brief Calculates the product of a matrix and its transposition.
  1487. The function cv::mulTransposed calculates the product of src and its
  1488. transposition:
  1489. \f[\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} )^T ( \texttt{src} - \texttt{delta} )\f]
  1490. if aTa=true , and
  1491. \f[\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} ) ( \texttt{src} - \texttt{delta} )^T\f]
  1492. otherwise. The function is used to calculate the covariance matrix. With
  1493. zero delta, it can be used as a faster substitute for general matrix
  1494. product A\*B when B=A'
  1495. @param src input single-channel matrix. Note that unlike gemm, the
  1496. function can multiply not only floating-point matrices.
  1497. @param dst output square matrix.
  1498. @param aTa Flag specifying the multiplication ordering. See the
  1499. description below.
  1500. @param delta Optional delta matrix subtracted from src before the
  1501. multiplication. When the matrix is empty ( delta=noArray() ), it is
  1502. assumed to be zero, that is, nothing is subtracted. If it has the same
  1503. size as src , it is simply subtracted. Otherwise, it is "repeated" (see
  1504. repeat ) to cover the full src and then subtracted. Type of the delta
  1505. matrix, when it is not empty, must be the same as the type of created
  1506. output matrix. See the dtype parameter description below.
  1507. @param scale Optional scale factor for the matrix product.
  1508. @param dtype Optional type of the output matrix. When it is negative,
  1509. the output matrix will have the same type as src . Otherwise, it will be
  1510. type=CV_MAT_DEPTH(dtype) that should be either CV_32F or CV_64F .
  1511. @sa calcCovarMatrix, gemm, repeat, reduce
  1512. */
  1513. CV_EXPORTS_W void mulTransposed( InputArray src, OutputArray dst, bool aTa,
  1514. InputArray delta = noArray(),
  1515. double scale = 1, int dtype = -1 );
  1516. /** @brief Transposes a matrix.
  1517. The function cv::transpose transposes the matrix src :
  1518. \f[\texttt{dst} (i,j) = \texttt{src} (j,i)\f]
  1519. @note No complex conjugation is done in case of a complex matrix. It
  1520. should be done separately if needed.
  1521. @param src input array.
  1522. @param dst output array of the same type as src.
  1523. */
  1524. CV_EXPORTS_W void transpose(InputArray src, OutputArray dst);
  1525. /** @brief Performs the matrix transformation of every array element.
  1526. The function cv::transform performs the matrix transformation of every
  1527. element of the array src and stores the results in dst :
  1528. \f[\texttt{dst} (I) = \texttt{m} \cdot \texttt{src} (I)\f]
  1529. (when m.cols=src.channels() ), or
  1530. \f[\texttt{dst} (I) = \texttt{m} \cdot [ \texttt{src} (I); 1]\f]
  1531. (when m.cols=src.channels()+1 )
  1532. Every element of the N -channel array src is interpreted as N -element
  1533. vector that is transformed using the M x N or M x (N+1) matrix m to
  1534. M-element vector - the corresponding element of the output array dst .
  1535. The function may be used for geometrical transformation of
  1536. N -dimensional points, arbitrary linear color space transformation (such
  1537. as various kinds of RGB to YUV transforms), shuffling the image
  1538. channels, and so forth.
  1539. @param src input array that must have as many channels (1 to 4) as
  1540. m.cols or m.cols-1.
  1541. @param dst output array of the same size and depth as src; it has as
  1542. many channels as m.rows.
  1543. @param m transformation 2x2 or 2x3 floating-point matrix.
  1544. @sa perspectiveTransform, getAffineTransform, estimateAffine2D, warpAffine, warpPerspective
  1545. */
  1546. CV_EXPORTS_W void transform(InputArray src, OutputArray dst, InputArray m );
  1547. /** @brief Performs the perspective matrix transformation of vectors.
  1548. The function cv::perspectiveTransform transforms every element of src by
  1549. treating it as a 2D or 3D vector, in the following way:
  1550. \f[(x, y, z) \rightarrow (x'/w, y'/w, z'/w)\f]
  1551. where
  1552. \f[(x', y', z', w') = \texttt{mat} \cdot \begin{bmatrix} x & y & z & 1 \end{bmatrix}\f]
  1553. and
  1554. \f[w = \fork{w'}{if \(w' \ne 0\)}{\infty}{otherwise}\f]
  1555. Here a 3D vector transformation is shown. In case of a 2D vector
  1556. transformation, the z component is omitted.
  1557. @note The function transforms a sparse set of 2D or 3D vectors. If you
  1558. want to transform an image using perspective transformation, use
  1559. warpPerspective . If you have an inverse problem, that is, you want to
  1560. compute the most probable perspective transformation out of several
  1561. pairs of corresponding points, you can use getPerspectiveTransform or
  1562. findHomography .
  1563. @param src input two-channel or three-channel floating-point array; each
  1564. element is a 2D/3D vector to be transformed.
  1565. @param dst output array of the same size and type as src.
  1566. @param m 3x3 or 4x4 floating-point transformation matrix.
  1567. @sa transform, warpPerspective, getPerspectiveTransform, findHomography
  1568. */
  1569. CV_EXPORTS_W void perspectiveTransform(InputArray src, OutputArray dst, InputArray m );
  1570. /** @brief Copies the lower or the upper half of a square matrix to its another half.
  1571. The function cv::completeSymm copies the lower or the upper half of a square matrix to
  1572. its another half. The matrix diagonal remains unchanged:
  1573. - \f$\texttt{m}_{ij}=\texttt{m}_{ji}\f$ for \f$i > j\f$ if
  1574. lowerToUpper=false
  1575. - \f$\texttt{m}_{ij}=\texttt{m}_{ji}\f$ for \f$i < j\f$ if
  1576. lowerToUpper=true
  1577. @param m input-output floating-point square matrix.
  1578. @param lowerToUpper operation flag; if true, the lower half is copied to
  1579. the upper half. Otherwise, the upper half is copied to the lower half.
  1580. @sa flip, transpose
  1581. */
  1582. CV_EXPORTS_W void completeSymm(InputOutputArray m, bool lowerToUpper = false);
  1583. /** @brief Initializes a scaled identity matrix.
  1584. The function cv::setIdentity initializes a scaled identity matrix:
  1585. \f[\texttt{mtx} (i,j)= \fork{\texttt{value}}{ if \(i=j\)}{0}{otherwise}\f]
  1586. The function can also be emulated using the matrix initializers and the
  1587. matrix expressions:
  1588. @code
  1589. Mat A = Mat::eye(4, 3, CV_32F)*5;
  1590. // A will be set to [[5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0]]
  1591. @endcode
  1592. @param mtx matrix to initialize (not necessarily square).
  1593. @param s value to assign to diagonal elements.
  1594. @sa Mat::zeros, Mat::ones, Mat::setTo, Mat::operator=
  1595. */
  1596. CV_EXPORTS_W void setIdentity(InputOutputArray mtx, const Scalar& s = Scalar(1));
  1597. /** @brief Returns the determinant of a square floating-point matrix.
  1598. The function cv::determinant calculates and returns the determinant of the
  1599. specified matrix. For small matrices ( mtx.cols=mtx.rows\<=3 ), the
  1600. direct method is used. For larger matrices, the function uses LU
  1601. factorization with partial pivoting.
  1602. For symmetric positively-determined matrices, it is also possible to use
  1603. eigen decomposition to calculate the determinant.
  1604. @param mtx input matrix that must have CV_32FC1 or CV_64FC1 type and
  1605. square size.
  1606. @sa trace, invert, solve, eigen, @ref MatrixExpressions
  1607. */
  1608. CV_EXPORTS_W double determinant(InputArray mtx);
  1609. /** @brief Returns the trace of a matrix.
  1610. The function cv::trace returns the sum of the diagonal elements of the
  1611. matrix mtx .
  1612. \f[\mathrm{tr} ( \texttt{mtx} ) = \sum _i \texttt{mtx} (i,i)\f]
  1613. @param mtx input matrix.
  1614. */
  1615. CV_EXPORTS_W Scalar trace(InputArray mtx);
  1616. /** @brief Finds the inverse or pseudo-inverse of a matrix.
  1617. The function cv::invert inverts the matrix src and stores the result in dst
  1618. . When the matrix src is singular or non-square, the function calculates
  1619. the pseudo-inverse matrix (the dst matrix) so that norm(src\*dst - I) is
  1620. minimal, where I is an identity matrix.
  1621. In case of the #DECOMP_LU method, the function returns non-zero value if
  1622. the inverse has been successfully calculated and 0 if src is singular.
  1623. In case of the #DECOMP_SVD method, the function returns the inverse
  1624. condition number of src (the ratio of the smallest singular value to the
  1625. largest singular value) and 0 if src is singular. The SVD method
  1626. calculates a pseudo-inverse matrix if src is singular.
  1627. Similarly to #DECOMP_LU, the method #DECOMP_CHOLESKY works only with
  1628. non-singular square matrices that should also be symmetrical and
  1629. positively defined. In this case, the function stores the inverted
  1630. matrix in dst and returns non-zero. Otherwise, it returns 0.
  1631. @param src input floating-point M x N matrix.
  1632. @param dst output matrix of N x M size and the same type as src.
  1633. @param flags inversion method (cv::DecompTypes)
  1634. @sa solve, SVD
  1635. */
  1636. CV_EXPORTS_W double invert(InputArray src, OutputArray dst, int flags = DECOMP_LU);
  1637. /** @brief Solves one or more linear systems or least-squares problems.
  1638. The function cv::solve solves a linear system or least-squares problem (the
  1639. latter is possible with SVD or QR methods, or by specifying the flag
  1640. #DECOMP_NORMAL ):
  1641. \f[\texttt{dst} = \arg \min _X \| \texttt{src1} \cdot \texttt{X} - \texttt{src2} \|\f]
  1642. If #DECOMP_LU or #DECOMP_CHOLESKY method is used, the function returns 1
  1643. if src1 (or \f$\texttt{src1}^T\texttt{src1}\f$ ) is non-singular. Otherwise,
  1644. it returns 0. In the latter case, dst is not valid. Other methods find a
  1645. pseudo-solution in case of a singular left-hand side part.
  1646. @note If you want to find a unity-norm solution of an under-defined
  1647. singular system \f$\texttt{src1}\cdot\texttt{dst}=0\f$ , the function solve
  1648. will not do the work. Use SVD::solveZ instead.
  1649. @param src1 input matrix on the left-hand side of the system.
  1650. @param src2 input matrix on the right-hand side of the system.
  1651. @param dst output solution.
  1652. @param flags solution (matrix inversion) method (#DecompTypes)
  1653. @sa invert, SVD, eigen
  1654. */
  1655. CV_EXPORTS_W bool solve(InputArray src1, InputArray src2,
  1656. OutputArray dst, int flags = DECOMP_LU);
  1657. /** @brief Sorts each row or each column of a matrix.
  1658. The function cv::sort sorts each matrix row or each matrix column in
  1659. ascending or descending order. So you should pass two operation flags to
  1660. get desired behaviour. If you want to sort matrix rows or columns
  1661. lexicographically, you can use STL std::sort generic function with the
  1662. proper comparison predicate.
  1663. @param src input single-channel array.
  1664. @param dst output array of the same size and type as src.
  1665. @param flags operation flags, a combination of #SortFlags
  1666. @sa sortIdx, randShuffle
  1667. */
  1668. CV_EXPORTS_W void sort(InputArray src, OutputArray dst, int flags);
  1669. /** @brief Sorts each row or each column of a matrix.
  1670. The function cv::sortIdx sorts each matrix row or each matrix column in the
  1671. ascending or descending order. So you should pass two operation flags to
  1672. get desired behaviour. Instead of reordering the elements themselves, it
  1673. stores the indices of sorted elements in the output array. For example:
  1674. @code
  1675. Mat A = Mat::eye(3,3,CV_32F), B;
  1676. sortIdx(A, B, SORT_EVERY_ROW + SORT_ASCENDING);
  1677. // B will probably contain
  1678. // (because of equal elements in A some permutations are possible):
  1679. // [[1, 2, 0], [0, 2, 1], [0, 1, 2]]
  1680. @endcode
  1681. @param src input single-channel array.
  1682. @param dst output integer array of the same size as src.
  1683. @param flags operation flags that could be a combination of cv::SortFlags
  1684. @sa sort, randShuffle
  1685. */
  1686. CV_EXPORTS_W void sortIdx(InputArray src, OutputArray dst, int flags);
  1687. /** @brief Finds the real roots of a cubic equation.
  1688. The function solveCubic finds the real roots of a cubic equation:
  1689. - if coeffs is a 4-element vector:
  1690. \f[\texttt{coeffs} [0] x^3 + \texttt{coeffs} [1] x^2 + \texttt{coeffs} [2] x + \texttt{coeffs} [3] = 0\f]
  1691. - if coeffs is a 3-element vector:
  1692. \f[x^3 + \texttt{coeffs} [0] x^2 + \texttt{coeffs} [1] x + \texttt{coeffs} [2] = 0\f]
  1693. The roots are stored in the roots array.
  1694. @param coeffs equation coefficients, an array of 3 or 4 elements.
  1695. @param roots output array of real roots that has 1 or 3 elements.
  1696. @return number of real roots. It can be 0, 1 or 2.
  1697. */
  1698. CV_EXPORTS_W int solveCubic(InputArray coeffs, OutputArray roots);
  1699. /** @brief Finds the real or complex roots of a polynomial equation.
  1700. The function cv::solvePoly finds real and complex roots of a polynomial equation:
  1701. \f[\texttt{coeffs} [n] x^{n} + \texttt{coeffs} [n-1] x^{n-1} + ... + \texttt{coeffs} [1] x + \texttt{coeffs} [0] = 0\f]
  1702. @param coeffs array of polynomial coefficients.
  1703. @param roots output (complex) array of roots.
  1704. @param maxIters maximum number of iterations the algorithm does.
  1705. */
  1706. CV_EXPORTS_W double solvePoly(InputArray coeffs, OutputArray roots, int maxIters = 300);
  1707. /** @brief Calculates eigenvalues and eigenvectors of a symmetric matrix.
  1708. The function cv::eigen calculates just eigenvalues, or eigenvalues and eigenvectors of the symmetric
  1709. matrix src:
  1710. @code
  1711. src*eigenvectors.row(i).t() = eigenvalues.at<srcType>(i)*eigenvectors.row(i).t()
  1712. @endcode
  1713. @note Use cv::eigenNonSymmetric for calculation of real eigenvalues and eigenvectors of non-symmetric matrix.
  1714. @param src input matrix that must have CV_32FC1 or CV_64FC1 type, square size and be symmetrical
  1715. (src ^T^ == src).
  1716. @param eigenvalues output vector of eigenvalues of the same type as src; the eigenvalues are stored
  1717. in the descending order.
  1718. @param eigenvectors output matrix of eigenvectors; it has the same size and type as src; the
  1719. eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding
  1720. eigenvalues.
  1721. @sa eigenNonSymmetric, completeSymm , PCA
  1722. */
  1723. CV_EXPORTS_W bool eigen(InputArray src, OutputArray eigenvalues,
  1724. OutputArray eigenvectors = noArray());
  1725. /** @brief Calculates eigenvalues and eigenvectors of a non-symmetric matrix (real eigenvalues only).
  1726. @note Assumes real eigenvalues.
  1727. The function calculates eigenvalues and eigenvectors (optional) of the square matrix src:
  1728. @code
  1729. src*eigenvectors.row(i).t() = eigenvalues.at<srcType>(i)*eigenvectors.row(i).t()
  1730. @endcode
  1731. @param src input matrix (CV_32FC1 or CV_64FC1 type).
  1732. @param eigenvalues output vector of eigenvalues (type is the same type as src).
  1733. @param eigenvectors output matrix of eigenvectors (type is the same type as src). The eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding eigenvalues.
  1734. @sa eigen
  1735. */
  1736. CV_EXPORTS_W void eigenNonSymmetric(InputArray src, OutputArray eigenvalues,
  1737. OutputArray eigenvectors);
  1738. /** @brief Calculates the covariance matrix of a set of vectors.
  1739. The function cv::calcCovarMatrix calculates the covariance matrix and, optionally, the mean vector of
  1740. the set of input vectors.
  1741. @param samples samples stored as separate matrices
  1742. @param nsamples number of samples
  1743. @param covar output covariance matrix of the type ctype and square size.
  1744. @param mean input or output (depending on the flags) array as the average value of the input vectors.
  1745. @param flags operation flags as a combination of #CovarFlags
  1746. @param ctype type of the matrixl; it equals 'CV_64F' by default.
  1747. @sa PCA, mulTransposed, Mahalanobis
  1748. @todo InputArrayOfArrays
  1749. */
  1750. CV_EXPORTS void calcCovarMatrix( const Mat* samples, int nsamples, Mat& covar, Mat& mean,
  1751. int flags, int ctype = CV_64F);
  1752. /** @overload
  1753. @note use #COVAR_ROWS or #COVAR_COLS flag
  1754. @param samples samples stored as rows/columns of a single matrix.
  1755. @param covar output covariance matrix of the type ctype and square size.
  1756. @param mean input or output (depending on the flags) array as the average value of the input vectors.
  1757. @param flags operation flags as a combination of #CovarFlags
  1758. @param ctype type of the matrixl; it equals 'CV_64F' by default.
  1759. */
  1760. CV_EXPORTS_W void calcCovarMatrix( InputArray samples, OutputArray covar,
  1761. InputOutputArray mean, int flags, int ctype = CV_64F);
  1762. /** wrap PCA::operator() */
  1763. CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean,
  1764. OutputArray eigenvectors, int maxComponents = 0);
  1765. /** wrap PCA::operator() and add eigenvalues output parameter */
  1766. CV_EXPORTS_AS(PCACompute2) void PCACompute(InputArray data, InputOutputArray mean,
  1767. OutputArray eigenvectors, OutputArray eigenvalues,
  1768. int maxComponents = 0);
  1769. /** wrap PCA::operator() */
  1770. CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean,
  1771. OutputArray eigenvectors, double retainedVariance);
  1772. /** wrap PCA::operator() and add eigenvalues output parameter */
  1773. CV_EXPORTS_AS(PCACompute2) void PCACompute(InputArray data, InputOutputArray mean,
  1774. OutputArray eigenvectors, OutputArray eigenvalues,
  1775. double retainedVariance);
  1776. /** wrap PCA::project */
  1777. CV_EXPORTS_W void PCAProject(InputArray data, InputArray mean,
  1778. InputArray eigenvectors, OutputArray result);
  1779. /** wrap PCA::backProject */
  1780. CV_EXPORTS_W void PCABackProject(InputArray data, InputArray mean,
  1781. InputArray eigenvectors, OutputArray result);
  1782. /** wrap SVD::compute */
  1783. CV_EXPORTS_W void SVDecomp( InputArray src, OutputArray w, OutputArray u, OutputArray vt, int flags = 0 );
  1784. /** wrap SVD::backSubst */
  1785. CV_EXPORTS_W void SVBackSubst( InputArray w, InputArray u, InputArray vt,
  1786. InputArray rhs, OutputArray dst );
  1787. /** @brief Calculates the Mahalanobis distance between two vectors.
  1788. The function cv::Mahalanobis calculates and returns the weighted distance between two vectors:
  1789. \f[d( \texttt{vec1} , \texttt{vec2} )= \sqrt{\sum_{i,j}{\texttt{icovar(i,j)}\cdot(\texttt{vec1}(I)-\texttt{vec2}(I))\cdot(\texttt{vec1(j)}-\texttt{vec2(j)})} }\f]
  1790. The covariance matrix may be calculated using the #calcCovarMatrix function and then inverted using
  1791. the invert function (preferably using the #DECOMP_SVD method, as the most accurate).
  1792. @param v1 first 1D input vector.
  1793. @param v2 second 1D input vector.
  1794. @param icovar inverse covariance matrix.
  1795. */
  1796. CV_EXPORTS_W double Mahalanobis(InputArray v1, InputArray v2, InputArray icovar);
  1797. /** @brief Performs a forward or inverse Discrete Fourier transform of a 1D or 2D floating-point array.
  1798. The function cv::dft performs one of the following:
  1799. - Forward the Fourier transform of a 1D vector of N elements:
  1800. \f[Y = F^{(N)} \cdot X,\f]
  1801. where \f$F^{(N)}_{jk}=\exp(-2\pi i j k/N)\f$ and \f$i=\sqrt{-1}\f$
  1802. - Inverse the Fourier transform of a 1D vector of N elements:
  1803. \f[\begin{array}{l} X'= \left (F^{(N)} \right )^{-1} \cdot Y = \left (F^{(N)} \right )^* \cdot y \\ X = (1/N) \cdot X, \end{array}\f]
  1804. where \f$F^*=\left(\textrm{Re}(F^{(N)})-\textrm{Im}(F^{(N)})\right)^T\f$
  1805. - Forward the 2D Fourier transform of a M x N matrix:
  1806. \f[Y = F^{(M)} \cdot X \cdot F^{(N)}\f]
  1807. - Inverse the 2D Fourier transform of a M x N matrix:
  1808. \f[\begin{array}{l} X'= \left (F^{(M)} \right )^* \cdot Y \cdot \left (F^{(N)} \right )^* \\ X = \frac{1}{M \cdot N} \cdot X' \end{array}\f]
  1809. In case of real (single-channel) data, the output spectrum of the forward Fourier transform or input
  1810. spectrum of the inverse Fourier transform can be represented in a packed format called *CCS*
  1811. (complex-conjugate-symmetrical). It was borrowed from IPL (Intel\* Image Processing Library). Here
  1812. is how 2D *CCS* spectrum looks:
  1813. \f[\begin{bmatrix} Re Y_{0,0} & Re Y_{0,1} & Im Y_{0,1} & Re Y_{0,2} & Im Y_{0,2} & \cdots & Re Y_{0,N/2-1} & Im Y_{0,N/2-1} & Re Y_{0,N/2} \\ Re Y_{1,0} & Re Y_{1,1} & Im Y_{1,1} & Re Y_{1,2} & Im Y_{1,2} & \cdots & Re Y_{1,N/2-1} & Im Y_{1,N/2-1} & Re Y_{1,N/2} \\ Im Y_{1,0} & Re Y_{2,1} & Im Y_{2,1} & Re Y_{2,2} & Im Y_{2,2} & \cdots & Re Y_{2,N/2-1} & Im Y_{2,N/2-1} & Im Y_{1,N/2} \\ \hdotsfor{9} \\ Re Y_{M/2-1,0} & Re Y_{M-3,1} & Im Y_{M-3,1} & \hdotsfor{3} & Re Y_{M-3,N/2-1} & Im Y_{M-3,N/2-1}& Re Y_{M/2-1,N/2} \\ Im Y_{M/2-1,0} & Re Y_{M-2,1} & Im Y_{M-2,1} & \hdotsfor{3} & Re Y_{M-2,N/2-1} & Im Y_{M-2,N/2-1}& Im Y_{M/2-1,N/2} \\ Re Y_{M/2,0} & Re Y_{M-1,1} & Im Y_{M-1,1} & \hdotsfor{3} & Re Y_{M-1,N/2-1} & Im Y_{M-1,N/2-1}& Re Y_{M/2,N/2} \end{bmatrix}\f]
  1814. In case of 1D transform of a real vector, the output looks like the first row of the matrix above.
  1815. So, the function chooses an operation mode depending on the flags and size of the input array:
  1816. - If #DFT_ROWS is set or the input array has a single row or single column, the function
  1817. performs a 1D forward or inverse transform of each row of a matrix when #DFT_ROWS is set.
  1818. Otherwise, it performs a 2D transform.
  1819. - If the input array is real and #DFT_INVERSE is not set, the function performs a forward 1D or
  1820. 2D transform:
  1821. - When #DFT_COMPLEX_OUTPUT is set, the output is a complex matrix of the same size as
  1822. input.
  1823. - When #DFT_COMPLEX_OUTPUT is not set, the output is a real matrix of the same size as
  1824. input. In case of 2D transform, it uses the packed format as shown above. In case of a
  1825. single 1D transform, it looks like the first row of the matrix above. In case of
  1826. multiple 1D transforms (when using the #DFT_ROWS flag), each row of the output matrix
  1827. looks like the first row of the matrix above.
  1828. - If the input array is complex and either #DFT_INVERSE or #DFT_REAL_OUTPUT are not set, the
  1829. output is a complex array of the same size as input. The function performs a forward or
  1830. inverse 1D or 2D transform of the whole input array or each row of the input array
  1831. independently, depending on the flags DFT_INVERSE and DFT_ROWS.
  1832. - When #DFT_INVERSE is set and the input array is real, or it is complex but #DFT_REAL_OUTPUT
  1833. is set, the output is a real array of the same size as input. The function performs a 1D or 2D
  1834. inverse transformation of the whole input array or each individual row, depending on the flags
  1835. #DFT_INVERSE and #DFT_ROWS.
  1836. If #DFT_SCALE is set, the scaling is done after the transformation.
  1837. Unlike dct , the function supports arrays of arbitrary size. But only those arrays are processed
  1838. efficiently, whose sizes can be factorized in a product of small prime numbers (2, 3, and 5 in the
  1839. current implementation). Such an efficient DFT size can be calculated using the getOptimalDFTSize
  1840. method.
  1841. The sample below illustrates how to calculate a DFT-based convolution of two 2D real arrays:
  1842. @code
  1843. void convolveDFT(InputArray A, InputArray B, OutputArray C)
  1844. {
  1845. // reallocate the output array if needed
  1846. C.create(abs(A.rows - B.rows)+1, abs(A.cols - B.cols)+1, A.type());
  1847. Size dftSize;
  1848. // calculate the size of DFT transform
  1849. dftSize.width = getOptimalDFTSize(A.cols + B.cols - 1);
  1850. dftSize.height = getOptimalDFTSize(A.rows + B.rows - 1);
  1851. // allocate temporary buffers and initialize them with 0's
  1852. Mat tempA(dftSize, A.type(), Scalar::all(0));
  1853. Mat tempB(dftSize, B.type(), Scalar::all(0));
  1854. // copy A and B to the top-left corners of tempA and tempB, respectively
  1855. Mat roiA(tempA, Rect(0,0,A.cols,A.rows));
  1856. A.copyTo(roiA);
  1857. Mat roiB(tempB, Rect(0,0,B.cols,B.rows));
  1858. B.copyTo(roiB);
  1859. // now transform the padded A & B in-place;
  1860. // use "nonzeroRows" hint for faster processing
  1861. dft(tempA, tempA, 0, A.rows);
  1862. dft(tempB, tempB, 0, B.rows);
  1863. // multiply the spectrums;
  1864. // the function handles packed spectrum representations well
  1865. mulSpectrums(tempA, tempB, tempA);
  1866. // transform the product back from the frequency domain.
  1867. // Even though all the result rows will be non-zero,
  1868. // you need only the first C.rows of them, and thus you
  1869. // pass nonzeroRows == C.rows
  1870. dft(tempA, tempA, DFT_INVERSE + DFT_SCALE, C.rows);
  1871. // now copy the result back to C.
  1872. tempA(Rect(0, 0, C.cols, C.rows)).copyTo(C);
  1873. // all the temporary buffers will be deallocated automatically
  1874. }
  1875. @endcode
  1876. To optimize this sample, consider the following approaches:
  1877. - Since nonzeroRows != 0 is passed to the forward transform calls and since A and B are copied to
  1878. the top-left corners of tempA and tempB, respectively, it is not necessary to clear the whole
  1879. tempA and tempB. It is only necessary to clear the tempA.cols - A.cols ( tempB.cols - B.cols)
  1880. rightmost columns of the matrices.
  1881. - This DFT-based convolution does not have to be applied to the whole big arrays, especially if B
  1882. is significantly smaller than A or vice versa. Instead, you can calculate convolution by parts.
  1883. To do this, you need to split the output array C into multiple tiles. For each tile, estimate
  1884. which parts of A and B are required to calculate convolution in this tile. If the tiles in C are
  1885. too small, the speed will decrease a lot because of repeated work. In the ultimate case, when
  1886. each tile in C is a single pixel, the algorithm becomes equivalent to the naive convolution
  1887. algorithm. If the tiles are too big, the temporary arrays tempA and tempB become too big and
  1888. there is also a slowdown because of bad cache locality. So, there is an optimal tile size
  1889. somewhere in the middle.
  1890. - If different tiles in C can be calculated in parallel and, thus, the convolution is done by
  1891. parts, the loop can be threaded.
  1892. All of the above improvements have been implemented in #matchTemplate and #filter2D . Therefore, by
  1893. using them, you can get the performance even better than with the above theoretically optimal
  1894. implementation. Though, those two functions actually calculate cross-correlation, not convolution,
  1895. so you need to "flip" the second convolution operand B vertically and horizontally using flip .
  1896. @note
  1897. - An example using the discrete fourier transform can be found at
  1898. opencv_source_code/samples/cpp/dft.cpp
  1899. - (Python) An example using the dft functionality to perform Wiener deconvolution can be found
  1900. at opencv_source/samples/python/deconvolution.py
  1901. - (Python) An example rearranging the quadrants of a Fourier image can be found at
  1902. opencv_source/samples/python/dft.py
  1903. @param src input array that could be real or complex.
  1904. @param dst output array whose size and type depends on the flags .
  1905. @param flags transformation flags, representing a combination of the #DftFlags
  1906. @param nonzeroRows when the parameter is not zero, the function assumes that only the first
  1907. nonzeroRows rows of the input array (#DFT_INVERSE is not set) or only the first nonzeroRows of the
  1908. output array (#DFT_INVERSE is set) contain non-zeros, thus, the function can handle the rest of the
  1909. rows more efficiently and save some time; this technique is very useful for calculating array
  1910. cross-correlation or convolution using DFT.
  1911. @sa dct , getOptimalDFTSize , mulSpectrums, filter2D , matchTemplate , flip , cartToPolar ,
  1912. magnitude , phase
  1913. */
  1914. CV_EXPORTS_W void dft(InputArray src, OutputArray dst, int flags = 0, int nonzeroRows = 0);
  1915. /** @brief Calculates the inverse Discrete Fourier Transform of a 1D or 2D array.
  1916. idft(src, dst, flags) is equivalent to dft(src, dst, flags | #DFT_INVERSE) .
  1917. @note None of dft and idft scales the result by default. So, you should pass #DFT_SCALE to one of
  1918. dft or idft explicitly to make these transforms mutually inverse.
  1919. @sa dft, dct, idct, mulSpectrums, getOptimalDFTSize
  1920. @param src input floating-point real or complex array.
  1921. @param dst output array whose size and type depend on the flags.
  1922. @param flags operation flags (see dft and #DftFlags).
  1923. @param nonzeroRows number of dst rows to process; the rest of the rows have undefined content (see
  1924. the convolution sample in dft description.
  1925. */
  1926. CV_EXPORTS_W void idft(InputArray src, OutputArray dst, int flags = 0, int nonzeroRows = 0);
  1927. /** @brief Performs a forward or inverse discrete Cosine transform of 1D or 2D array.
  1928. The function cv::dct performs a forward or inverse discrete Cosine transform (DCT) of a 1D or 2D
  1929. floating-point array:
  1930. - Forward Cosine transform of a 1D vector of N elements:
  1931. \f[Y = C^{(N)} \cdot X\f]
  1932. where
  1933. \f[C^{(N)}_{jk}= \sqrt{\alpha_j/N} \cos \left ( \frac{\pi(2k+1)j}{2N} \right )\f]
  1934. and
  1935. \f$\alpha_0=1\f$, \f$\alpha_j=2\f$ for *j \> 0*.
  1936. - Inverse Cosine transform of a 1D vector of N elements:
  1937. \f[X = \left (C^{(N)} \right )^{-1} \cdot Y = \left (C^{(N)} \right )^T \cdot Y\f]
  1938. (since \f$C^{(N)}\f$ is an orthogonal matrix, \f$C^{(N)} \cdot \left(C^{(N)}\right)^T = I\f$ )
  1939. - Forward 2D Cosine transform of M x N matrix:
  1940. \f[Y = C^{(N)} \cdot X \cdot \left (C^{(N)} \right )^T\f]
  1941. - Inverse 2D Cosine transform of M x N matrix:
  1942. \f[X = \left (C^{(N)} \right )^T \cdot X \cdot C^{(N)}\f]
  1943. The function chooses the mode of operation by looking at the flags and size of the input array:
  1944. - If (flags & #DCT_INVERSE) == 0 , the function does a forward 1D or 2D transform. Otherwise, it
  1945. is an inverse 1D or 2D transform.
  1946. - If (flags & #DCT_ROWS) != 0 , the function performs a 1D transform of each row.
  1947. - If the array is a single column or a single row, the function performs a 1D transform.
  1948. - If none of the above is true, the function performs a 2D transform.
  1949. @note Currently dct supports even-size arrays (2, 4, 6 ...). For data analysis and approximation, you
  1950. can pad the array when necessary.
  1951. Also, the function performance depends very much, and not monotonically, on the array size (see
  1952. getOptimalDFTSize ). In the current implementation DCT of a vector of size N is calculated via DFT
  1953. of a vector of size N/2 . Thus, the optimal DCT size N1 \>= N can be calculated as:
  1954. @code
  1955. size_t getOptimalDCTSize(size_t N) { return 2*getOptimalDFTSize((N+1)/2); }
  1956. N1 = getOptimalDCTSize(N);
  1957. @endcode
  1958. @param src input floating-point array.
  1959. @param dst output array of the same size and type as src .
  1960. @param flags transformation flags as a combination of cv::DftFlags (DCT_*)
  1961. @sa dft , getOptimalDFTSize , idct
  1962. */
  1963. CV_EXPORTS_W void dct(InputArray src, OutputArray dst, int flags = 0);
  1964. /** @brief Calculates the inverse Discrete Cosine Transform of a 1D or 2D array.
  1965. idct(src, dst, flags) is equivalent to dct(src, dst, flags | DCT_INVERSE).
  1966. @param src input floating-point single-channel array.
  1967. @param dst output array of the same size and type as src.
  1968. @param flags operation flags.
  1969. @sa dct, dft, idft, getOptimalDFTSize
  1970. */
  1971. CV_EXPORTS_W void idct(InputArray src, OutputArray dst, int flags = 0);
  1972. /** @brief Performs the per-element multiplication of two Fourier spectrums.
  1973. The function cv::mulSpectrums performs the per-element multiplication of the two CCS-packed or complex
  1974. matrices that are results of a real or complex Fourier transform.
  1975. The function, together with dft and idft , may be used to calculate convolution (pass conjB=false )
  1976. or correlation (pass conjB=true ) of two arrays rapidly. When the arrays are complex, they are
  1977. simply multiplied (per element) with an optional conjugation of the second-array elements. When the
  1978. arrays are real, they are assumed to be CCS-packed (see dft for details).
  1979. @param a first input array.
  1980. @param b second input array of the same size and type as src1 .
  1981. @param c output array of the same size and type as src1 .
  1982. @param flags operation flags; currently, the only supported flag is cv::DFT_ROWS, which indicates that
  1983. each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a `0` as value.
  1984. @param conjB optional flag that conjugates the second input array before the multiplication (true)
  1985. or not (false).
  1986. */
  1987. CV_EXPORTS_W void mulSpectrums(InputArray a, InputArray b, OutputArray c,
  1988. int flags, bool conjB = false);
  1989. /** @brief Returns the optimal DFT size for a given vector size.
  1990. DFT performance is not a monotonic function of a vector size. Therefore, when you calculate
  1991. convolution of two arrays or perform the spectral analysis of an array, it usually makes sense to
  1992. pad the input data with zeros to get a bit larger array that can be transformed much faster than the
  1993. original one. Arrays whose size is a power-of-two (2, 4, 8, 16, 32, ...) are the fastest to process.
  1994. Though, the arrays whose size is a product of 2's, 3's, and 5's (for example, 300 = 5\*5\*3\*2\*2)
  1995. are also processed quite efficiently.
  1996. The function cv::getOptimalDFTSize returns the minimum number N that is greater than or equal to vecsize
  1997. so that the DFT of a vector of size N can be processed efficiently. In the current implementation N
  1998. = 2 ^p^ \* 3 ^q^ \* 5 ^r^ for some integer p, q, r.
  1999. The function returns a negative number if vecsize is too large (very close to INT_MAX ).
  2000. While the function cannot be used directly to estimate the optimal vector size for DCT transform
  2001. (since the current DCT implementation supports only even-size vectors), it can be easily processed
  2002. as getOptimalDFTSize((vecsize+1)/2)\*2.
  2003. @param vecsize vector size.
  2004. @sa dft , dct , idft , idct , mulSpectrums
  2005. */
  2006. CV_EXPORTS_W int getOptimalDFTSize(int vecsize);
  2007. /** @brief Returns the default random number generator.
  2008. The function cv::theRNG returns the default random number generator. For each thread, there is a
  2009. separate random number generator, so you can use the function safely in multi-thread environments.
  2010. If you just need to get a single random number using this generator or initialize an array, you can
  2011. use randu or randn instead. But if you are going to generate many random numbers inside a loop, it
  2012. is much faster to use this function to retrieve the generator and then use RNG::operator _Tp() .
  2013. @sa RNG, randu, randn
  2014. */
  2015. CV_EXPORTS RNG& theRNG();
  2016. /** @brief Sets state of default random number generator.
  2017. The function cv::setRNGSeed sets state of default random number generator to custom value.
  2018. @param seed new state for default random number generator
  2019. @sa RNG, randu, randn
  2020. */
  2021. CV_EXPORTS_W void setRNGSeed(int seed);
  2022. /** @brief Generates a single uniformly-distributed random number or an array of random numbers.
  2023. Non-template variant of the function fills the matrix dst with uniformly-distributed
  2024. random numbers from the specified range:
  2025. \f[\texttt{low} _c \leq \texttt{dst} (I)_c < \texttt{high} _c\f]
  2026. @param dst output array of random numbers; the array must be pre-allocated.
  2027. @param low inclusive lower boundary of the generated random numbers.
  2028. @param high exclusive upper boundary of the generated random numbers.
  2029. @sa RNG, randn, theRNG
  2030. */
  2031. CV_EXPORTS_W void randu(InputOutputArray dst, InputArray low, InputArray high);
  2032. /** @brief Fills the array with normally distributed random numbers.
  2033. The function cv::randn fills the matrix dst with normally distributed random numbers with the specified
  2034. mean vector and the standard deviation matrix. The generated random numbers are clipped to fit the
  2035. value range of the output array data type.
  2036. @param dst output array of random numbers; the array must be pre-allocated and have 1 to 4 channels.
  2037. @param mean mean value (expectation) of the generated random numbers.
  2038. @param stddev standard deviation of the generated random numbers; it can be either a vector (in
  2039. which case a diagonal standard deviation matrix is assumed) or a square matrix.
  2040. @sa RNG, randu
  2041. */
  2042. CV_EXPORTS_W void randn(InputOutputArray dst, InputArray mean, InputArray stddev);
  2043. /** @brief Shuffles the array elements randomly.
  2044. The function cv::randShuffle shuffles the specified 1D array by randomly choosing pairs of elements and
  2045. swapping them. The number of such swap operations will be dst.rows\*dst.cols\*iterFactor .
  2046. @param dst input/output numerical 1D array.
  2047. @param iterFactor scale factor that determines the number of random swap operations (see the details
  2048. below).
  2049. @param rng optional random number generator used for shuffling; if it is zero, theRNG () is used
  2050. instead.
  2051. @sa RNG, sort
  2052. */
  2053. CV_EXPORTS_W void randShuffle(InputOutputArray dst, double iterFactor = 1., RNG* rng = 0);
  2054. /** @brief Principal Component Analysis
  2055. The class is used to calculate a special basis for a set of vectors. The
  2056. basis will consist of eigenvectors of the covariance matrix calculated
  2057. from the input set of vectors. The class %PCA can also transform
  2058. vectors to/from the new coordinate space defined by the basis. Usually,
  2059. in this new coordinate system, each vector from the original set (and
  2060. any linear combination of such vectors) can be quite accurately
  2061. approximated by taking its first few components, corresponding to the
  2062. eigenvectors of the largest eigenvalues of the covariance matrix.
  2063. Geometrically it means that you calculate a projection of the vector to
  2064. a subspace formed by a few eigenvectors corresponding to the dominant
  2065. eigenvalues of the covariance matrix. And usually such a projection is
  2066. very close to the original vector. So, you can represent the original
  2067. vector from a high-dimensional space with a much shorter vector
  2068. consisting of the projected vector's coordinates in the subspace. Such a
  2069. transformation is also known as Karhunen-Loeve Transform, or KLT.
  2070. See http://en.wikipedia.org/wiki/Principal_component_analysis
  2071. The sample below is the function that takes two matrices. The first
  2072. function stores a set of vectors (a row per vector) that is used to
  2073. calculate PCA. The second function stores another "test" set of vectors
  2074. (a row per vector). First, these vectors are compressed with PCA, then
  2075. reconstructed back, and then the reconstruction error norm is computed
  2076. and printed for each vector. :
  2077. @code{.cpp}
  2078. using namespace cv;
  2079. PCA compressPCA(const Mat& pcaset, int maxComponents,
  2080. const Mat& testset, Mat& compressed)
  2081. {
  2082. PCA pca(pcaset, // pass the data
  2083. Mat(), // we do not have a pre-computed mean vector,
  2084. // so let the PCA engine to compute it
  2085. PCA::DATA_AS_ROW, // indicate that the vectors
  2086. // are stored as matrix rows
  2087. // (use PCA::DATA_AS_COL if the vectors are
  2088. // the matrix columns)
  2089. maxComponents // specify, how many principal components to retain
  2090. );
  2091. // if there is no test data, just return the computed basis, ready-to-use
  2092. if( !testset.data )
  2093. return pca;
  2094. CV_Assert( testset.cols == pcaset.cols );
  2095. compressed.create(testset.rows, maxComponents, testset.type());
  2096. Mat reconstructed;
  2097. for( int i = 0; i < testset.rows; i++ )
  2098. {
  2099. Mat vec = testset.row(i), coeffs = compressed.row(i), reconstructed;
  2100. // compress the vector, the result will be stored
  2101. // in the i-th row of the output matrix
  2102. pca.project(vec, coeffs);
  2103. // and then reconstruct it
  2104. pca.backProject(coeffs, reconstructed);
  2105. // and measure the error
  2106. printf("%d. diff = %g\n", i, norm(vec, reconstructed, NORM_L2));
  2107. }
  2108. return pca;
  2109. }
  2110. @endcode
  2111. @sa calcCovarMatrix, mulTransposed, SVD, dft, dct
  2112. */
  2113. class CV_EXPORTS PCA
  2114. {
  2115. public:
  2116. enum Flags { DATA_AS_ROW = 0, //!< indicates that the input samples are stored as matrix rows
  2117. DATA_AS_COL = 1, //!< indicates that the input samples are stored as matrix columns
  2118. USE_AVG = 2 //!
  2119. };
  2120. /** @brief default constructor
  2121. The default constructor initializes an empty %PCA structure. The other
  2122. constructors initialize the structure and call PCA::operator()().
  2123. */
  2124. PCA();
  2125. /** @overload
  2126. @param data input samples stored as matrix rows or matrix columns.
  2127. @param mean optional mean value; if the matrix is empty (@c noArray()),
  2128. the mean is computed from the data.
  2129. @param flags operation flags; currently the parameter is only used to
  2130. specify the data layout (PCA::Flags)
  2131. @param maxComponents maximum number of components that %PCA should
  2132. retain; by default, all the components are retained.
  2133. */
  2134. PCA(InputArray data, InputArray mean, int flags, int maxComponents = 0);
  2135. /** @overload
  2136. @param data input samples stored as matrix rows or matrix columns.
  2137. @param mean optional mean value; if the matrix is empty (noArray()),
  2138. the mean is computed from the data.
  2139. @param flags operation flags; currently the parameter is only used to
  2140. specify the data layout (PCA::Flags)
  2141. @param retainedVariance Percentage of variance that PCA should retain.
  2142. Using this parameter will let the PCA decided how many components to
  2143. retain but it will always keep at least 2.
  2144. */
  2145. PCA(InputArray data, InputArray mean, int flags, double retainedVariance);
  2146. /** @brief performs %PCA
  2147. The operator performs %PCA of the supplied dataset. It is safe to reuse
  2148. the same PCA structure for multiple datasets. That is, if the structure
  2149. has been previously used with another dataset, the existing internal
  2150. data is reclaimed and the new @ref eigenvalues, @ref eigenvectors and @ref
  2151. mean are allocated and computed.
  2152. The computed @ref eigenvalues are sorted from the largest to the smallest and
  2153. the corresponding @ref eigenvectors are stored as eigenvectors rows.
  2154. @param data input samples stored as the matrix rows or as the matrix
  2155. columns.
  2156. @param mean optional mean value; if the matrix is empty (noArray()),
  2157. the mean is computed from the data.
  2158. @param flags operation flags; currently the parameter is only used to
  2159. specify the data layout. (Flags)
  2160. @param maxComponents maximum number of components that PCA should
  2161. retain; by default, all the components are retained.
  2162. */
  2163. PCA& operator()(InputArray data, InputArray mean, int flags, int maxComponents = 0);
  2164. /** @overload
  2165. @param data input samples stored as the matrix rows or as the matrix
  2166. columns.
  2167. @param mean optional mean value; if the matrix is empty (noArray()),
  2168. the mean is computed from the data.
  2169. @param flags operation flags; currently the parameter is only used to
  2170. specify the data layout. (PCA::Flags)
  2171. @param retainedVariance Percentage of variance that %PCA should retain.
  2172. Using this parameter will let the %PCA decided how many components to
  2173. retain but it will always keep at least 2.
  2174. */
  2175. PCA& operator()(InputArray data, InputArray mean, int flags, double retainedVariance);
  2176. /** @brief Projects vector(s) to the principal component subspace.
  2177. The methods project one or more vectors to the principal component
  2178. subspace, where each vector projection is represented by coefficients in
  2179. the principal component basis. The first form of the method returns the
  2180. matrix that the second form writes to the result. So the first form can
  2181. be used as a part of expression while the second form can be more
  2182. efficient in a processing loop.
  2183. @param vec input vector(s); must have the same dimensionality and the
  2184. same layout as the input data used at %PCA phase, that is, if
  2185. DATA_AS_ROW are specified, then `vec.cols==data.cols`
  2186. (vector dimensionality) and `vec.rows` is the number of vectors to
  2187. project, and the same is true for the PCA::DATA_AS_COL case.
  2188. */
  2189. Mat project(InputArray vec) const;
  2190. /** @overload
  2191. @param vec input vector(s); must have the same dimensionality and the
  2192. same layout as the input data used at PCA phase, that is, if
  2193. DATA_AS_ROW are specified, then `vec.cols==data.cols`
  2194. (vector dimensionality) and `vec.rows` is the number of vectors to
  2195. project, and the same is true for the PCA::DATA_AS_COL case.
  2196. @param result output vectors; in case of PCA::DATA_AS_COL, the
  2197. output matrix has as many columns as the number of input vectors, this
  2198. means that `result.cols==vec.cols` and the number of rows match the
  2199. number of principal components (for example, `maxComponents` parameter
  2200. passed to the constructor).
  2201. */
  2202. void project(InputArray vec, OutputArray result) const;
  2203. /** @brief Reconstructs vectors from their PC projections.
  2204. The methods are inverse operations to PCA::project. They take PC
  2205. coordinates of projected vectors and reconstruct the original vectors.
  2206. Unless all the principal components have been retained, the
  2207. reconstructed vectors are different from the originals. But typically,
  2208. the difference is small if the number of components is large enough (but
  2209. still much smaller than the original vector dimensionality). As a
  2210. result, PCA is used.
  2211. @param vec coordinates of the vectors in the principal component
  2212. subspace, the layout and size are the same as of PCA::project output
  2213. vectors.
  2214. */
  2215. Mat backProject(InputArray vec) const;
  2216. /** @overload
  2217. @param vec coordinates of the vectors in the principal component
  2218. subspace, the layout and size are the same as of PCA::project output
  2219. vectors.
  2220. @param result reconstructed vectors; the layout and size are the same as
  2221. of PCA::project input vectors.
  2222. */
  2223. void backProject(InputArray vec, OutputArray result) const;
  2224. /** @brief write PCA objects
  2225. Writes @ref eigenvalues @ref eigenvectors and @ref mean to specified FileStorage
  2226. */
  2227. void write(FileStorage& fs) const;
  2228. /** @brief load PCA objects
  2229. Loads @ref eigenvalues @ref eigenvectors and @ref mean from specified FileNode
  2230. */
  2231. void read(const FileNode& fn);
  2232. Mat eigenvectors; //!< eigenvectors of the covariation matrix
  2233. Mat eigenvalues; //!< eigenvalues of the covariation matrix
  2234. Mat mean; //!< mean value subtracted before the projection and added after the back projection
  2235. };
  2236. /** @example samples/cpp/pca.cpp
  2237. An example using %PCA for dimensionality reduction while maintaining an amount of variance
  2238. */
  2239. /** @example samples/cpp/tutorial_code/ml/introduction_to_pca/introduction_to_pca.cpp
  2240. Check @ref tutorial_introduction_to_pca "the corresponding tutorial" for more details
  2241. */
  2242. /**
  2243. @brief Linear Discriminant Analysis
  2244. @todo document this class
  2245. */
  2246. class CV_EXPORTS LDA
  2247. {
  2248. public:
  2249. /** @brief constructor
  2250. Initializes a LDA with num_components (default 0).
  2251. */
  2252. explicit LDA(int num_components = 0);
  2253. /** Initializes and performs a Discriminant Analysis with Fisher's
  2254. Optimization Criterion on given data in src and corresponding labels
  2255. in labels. If 0 (or less) number of components are given, they are
  2256. automatically determined for given data in computation.
  2257. */
  2258. LDA(InputArrayOfArrays src, InputArray labels, int num_components = 0);
  2259. /** Serializes this object to a given filename.
  2260. */
  2261. void save(const String& filename) const;
  2262. /** Deserializes this object from a given filename.
  2263. */
  2264. void load(const String& filename);
  2265. /** Serializes this object to a given cv::FileStorage.
  2266. */
  2267. void save(FileStorage& fs) const;
  2268. /** Deserializes this object from a given cv::FileStorage.
  2269. */
  2270. void load(const FileStorage& node);
  2271. /** destructor
  2272. */
  2273. ~LDA();
  2274. /** Compute the discriminants for data in src (row aligned) and labels.
  2275. */
  2276. void compute(InputArrayOfArrays src, InputArray labels);
  2277. /** Projects samples into the LDA subspace.
  2278. src may be one or more row aligned samples.
  2279. */
  2280. Mat project(InputArray src);
  2281. /** Reconstructs projections from the LDA subspace.
  2282. src may be one or more row aligned projections.
  2283. */
  2284. Mat reconstruct(InputArray src);
  2285. /** Returns the eigenvectors of this LDA.
  2286. */
  2287. Mat eigenvectors() const { return _eigenvectors; }
  2288. /** Returns the eigenvalues of this LDA.
  2289. */
  2290. Mat eigenvalues() const { return _eigenvalues; }
  2291. static Mat subspaceProject(InputArray W, InputArray mean, InputArray src);
  2292. static Mat subspaceReconstruct(InputArray W, InputArray mean, InputArray src);
  2293. protected:
  2294. int _num_components;
  2295. Mat _eigenvectors;
  2296. Mat _eigenvalues;
  2297. void lda(InputArrayOfArrays src, InputArray labels);
  2298. };
  2299. /** @brief Singular Value Decomposition
  2300. Class for computing Singular Value Decomposition of a floating-point
  2301. matrix. The Singular Value Decomposition is used to solve least-square
  2302. problems, under-determined linear systems, invert matrices, compute
  2303. condition numbers, and so on.
  2304. If you want to compute a condition number of a matrix or an absolute value of
  2305. its determinant, you do not need `u` and `vt`. You can pass
  2306. flags=SVD::NO_UV|... . Another flag SVD::FULL_UV indicates that full-size u
  2307. and vt must be computed, which is not necessary most of the time.
  2308. @sa invert, solve, eigen, determinant
  2309. */
  2310. class CV_EXPORTS SVD
  2311. {
  2312. public:
  2313. enum Flags {
  2314. /** allow the algorithm to modify the decomposed matrix; it can save space and speed up
  2315. processing. currently ignored. */
  2316. MODIFY_A = 1,
  2317. /** indicates that only a vector of singular values `w` is to be processed, while u and vt
  2318. will be set to empty matrices */
  2319. NO_UV = 2,
  2320. /** when the matrix is not square, by default the algorithm produces u and vt matrices of
  2321. sufficiently large size for the further A reconstruction; if, however, FULL_UV flag is
  2322. specified, u and vt will be full-size square orthogonal matrices.*/
  2323. FULL_UV = 4
  2324. };
  2325. /** @brief the default constructor
  2326. initializes an empty SVD structure
  2327. */
  2328. SVD();
  2329. /** @overload
  2330. initializes an empty SVD structure and then calls SVD::operator()
  2331. @param src decomposed matrix. The depth has to be CV_32F or CV_64F.
  2332. @param flags operation flags (SVD::Flags)
  2333. */
  2334. SVD( InputArray src, int flags = 0 );
  2335. /** @brief the operator that performs SVD. The previously allocated u, w and vt are released.
  2336. The operator performs the singular value decomposition of the supplied
  2337. matrix. The u,`vt` , and the vector of singular values w are stored in
  2338. the structure. The same SVD structure can be reused many times with
  2339. different matrices. Each time, if needed, the previous u,`vt` , and w
  2340. are reclaimed and the new matrices are created, which is all handled by
  2341. Mat::create.
  2342. @param src decomposed matrix. The depth has to be CV_32F or CV_64F.
  2343. @param flags operation flags (SVD::Flags)
  2344. */
  2345. SVD& operator ()( InputArray src, int flags = 0 );
  2346. /** @brief decomposes matrix and stores the results to user-provided matrices
  2347. The methods/functions perform SVD of matrix. Unlike SVD::SVD constructor
  2348. and SVD::operator(), they store the results to the user-provided
  2349. matrices:
  2350. @code{.cpp}
  2351. Mat A, w, u, vt;
  2352. SVD::compute(A, w, u, vt);
  2353. @endcode
  2354. @param src decomposed matrix. The depth has to be CV_32F or CV_64F.
  2355. @param w calculated singular values
  2356. @param u calculated left singular vectors
  2357. @param vt transposed matrix of right singular vectors
  2358. @param flags operation flags - see SVD::Flags.
  2359. */
  2360. static void compute( InputArray src, OutputArray w,
  2361. OutputArray u, OutputArray vt, int flags = 0 );
  2362. /** @overload
  2363. computes singular values of a matrix
  2364. @param src decomposed matrix. The depth has to be CV_32F or CV_64F.
  2365. @param w calculated singular values
  2366. @param flags operation flags - see SVD::Flags.
  2367. */
  2368. static void compute( InputArray src, OutputArray w, int flags = 0 );
  2369. /** @brief performs back substitution
  2370. */
  2371. static void backSubst( InputArray w, InputArray u,
  2372. InputArray vt, InputArray rhs,
  2373. OutputArray dst );
  2374. /** @brief solves an under-determined singular linear system
  2375. The method finds a unit-length solution x of a singular linear system
  2376. A\*x = 0. Depending on the rank of A, there can be no solutions, a
  2377. single solution or an infinite number of solutions. In general, the
  2378. algorithm solves the following problem:
  2379. \f[dst = \arg \min _{x: \| x \| =1} \| src \cdot x \|\f]
  2380. @param src left-hand-side matrix.
  2381. @param dst found solution.
  2382. */
  2383. static void solveZ( InputArray src, OutputArray dst );
  2384. /** @brief performs a singular value back substitution.
  2385. The method calculates a back substitution for the specified right-hand
  2386. side:
  2387. \f[\texttt{x} = \texttt{vt} ^T \cdot diag( \texttt{w} )^{-1} \cdot \texttt{u} ^T \cdot \texttt{rhs} \sim \texttt{A} ^{-1} \cdot \texttt{rhs}\f]
  2388. Using this technique you can either get a very accurate solution of the
  2389. convenient linear system, or the best (in the least-squares terms)
  2390. pseudo-solution of an overdetermined linear system.
  2391. @param rhs right-hand side of a linear system (u\*w\*v')\*dst = rhs to
  2392. be solved, where A has been previously decomposed.
  2393. @param dst found solution of the system.
  2394. @note Explicit SVD with the further back substitution only makes sense
  2395. if you need to solve many linear systems with the same left-hand side
  2396. (for example, src ). If all you need is to solve a single system
  2397. (possibly with multiple rhs immediately available), simply call solve
  2398. add pass #DECOMP_SVD there. It does absolutely the same thing.
  2399. */
  2400. void backSubst( InputArray rhs, OutputArray dst ) const;
  2401. /** @todo document */
  2402. template<typename _Tp, int m, int n, int nm> static
  2403. void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt );
  2404. /** @todo document */
  2405. template<typename _Tp, int m, int n, int nm> static
  2406. void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w );
  2407. /** @todo document */
  2408. template<typename _Tp, int m, int n, int nm, int nb> static
  2409. void backSubst( const Matx<_Tp, nm, 1>& w, const Matx<_Tp, m, nm>& u, const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, Matx<_Tp, n, nb>& dst );
  2410. Mat u, w, vt;
  2411. };
  2412. /** @brief Random Number Generator
  2413. Random number generator. It encapsulates the state (currently, a 64-bit
  2414. integer) and has methods to return scalar random values and to fill
  2415. arrays with random values. Currently it supports uniform and Gaussian
  2416. (normal) distributions. The generator uses Multiply-With-Carry
  2417. algorithm, introduced by G. Marsaglia (
  2418. <http://en.wikipedia.org/wiki/Multiply-with-carry> ).
  2419. Gaussian-distribution random numbers are generated using the Ziggurat
  2420. algorithm ( <http://en.wikipedia.org/wiki/Ziggurat_algorithm> ),
  2421. introduced by G. Marsaglia and W. W. Tsang.
  2422. */
  2423. class CV_EXPORTS RNG
  2424. {
  2425. public:
  2426. enum { UNIFORM = 0,
  2427. NORMAL = 1
  2428. };
  2429. /** @brief constructor
  2430. These are the RNG constructors. The first form sets the state to some
  2431. pre-defined value, equal to 2\*\*32-1 in the current implementation. The
  2432. second form sets the state to the specified value. If you passed state=0
  2433. , the constructor uses the above default value instead to avoid the
  2434. singular random number sequence, consisting of all zeros.
  2435. */
  2436. RNG();
  2437. /** @overload
  2438. @param state 64-bit value used to initialize the RNG.
  2439. */
  2440. RNG(uint64 state);
  2441. /**The method updates the state using the MWC algorithm and returns the
  2442. next 32-bit random number.*/
  2443. unsigned next();
  2444. /**Each of the methods updates the state using the MWC algorithm and
  2445. returns the next random number of the specified type. In case of integer
  2446. types, the returned number is from the available value range for the
  2447. specified type. In case of floating-point types, the returned value is
  2448. from [0,1) range.
  2449. */
  2450. operator uchar();
  2451. /** @overload */
  2452. operator schar();
  2453. /** @overload */
  2454. operator ushort();
  2455. /** @overload */
  2456. operator short();
  2457. /** @overload */
  2458. operator unsigned();
  2459. /** @overload */
  2460. operator int();
  2461. /** @overload */
  2462. operator float();
  2463. /** @overload */
  2464. operator double();
  2465. /** @brief returns a random integer sampled uniformly from [0, N).
  2466. The methods transform the state using the MWC algorithm and return the
  2467. next random number. The first form is equivalent to RNG::next . The
  2468. second form returns the random number modulo N , which means that the
  2469. result is in the range [0, N) .
  2470. */
  2471. unsigned operator ()();
  2472. /** @overload
  2473. @param N upper non-inclusive boundary of the returned random number.
  2474. */
  2475. unsigned operator ()(unsigned N);
  2476. /** @brief returns uniformly distributed integer random number from [a,b) range
  2477. The methods transform the state using the MWC algorithm and return the
  2478. next uniformly-distributed random number of the specified type, deduced
  2479. from the input parameter type, from the range [a, b) . There is a nuance
  2480. illustrated by the following sample:
  2481. @code{.cpp}
  2482. RNG rng;
  2483. // always produces 0
  2484. double a = rng.uniform(0, 1);
  2485. // produces double from [0, 1)
  2486. double a1 = rng.uniform((double)0, (double)1);
  2487. // produces float from [0, 1)
  2488. float b = rng.uniform(0.f, 1.f);
  2489. // produces double from [0, 1)
  2490. double c = rng.uniform(0., 1.);
  2491. // may cause compiler error because of ambiguity:
  2492. // RNG::uniform(0, (int)0.999999)? or RNG::uniform((double)0, 0.99999)?
  2493. double d = rng.uniform(0, 0.999999);
  2494. @endcode
  2495. The compiler does not take into account the type of the variable to
  2496. which you assign the result of RNG::uniform . The only thing that
  2497. matters to the compiler is the type of a and b parameters. So, if you
  2498. want a floating-point random number, but the range boundaries are
  2499. integer numbers, either put dots in the end, if they are constants, or
  2500. use explicit type cast operators, as in the a1 initialization above.
  2501. @param a lower inclusive boundary of the returned random number.
  2502. @param b upper non-inclusive boundary of the returned random number.
  2503. */
  2504. int uniform(int a, int b);
  2505. /** @overload */
  2506. float uniform(float a, float b);
  2507. /** @overload */
  2508. double uniform(double a, double b);
  2509. /** @brief Fills arrays with random numbers.
  2510. @param mat 2D or N-dimensional matrix; currently matrices with more than
  2511. 4 channels are not supported by the methods, use Mat::reshape as a
  2512. possible workaround.
  2513. @param distType distribution type, RNG::UNIFORM or RNG::NORMAL.
  2514. @param a first distribution parameter; in case of the uniform
  2515. distribution, this is an inclusive lower boundary, in case of the normal
  2516. distribution, this is a mean value.
  2517. @param b second distribution parameter; in case of the uniform
  2518. distribution, this is a non-inclusive upper boundary, in case of the
  2519. normal distribution, this is a standard deviation (diagonal of the
  2520. standard deviation matrix or the full standard deviation matrix).
  2521. @param saturateRange pre-saturation flag; for uniform distribution only;
  2522. if true, the method will first convert a and b to the acceptable value
  2523. range (according to the mat datatype) and then will generate uniformly
  2524. distributed random numbers within the range [saturate(a), saturate(b)),
  2525. if saturateRange=false, the method will generate uniformly distributed
  2526. random numbers in the original range [a, b) and then will saturate them,
  2527. it means, for example, that
  2528. <tt>theRNG().fill(mat_8u, RNG::UNIFORM, -DBL_MAX, DBL_MAX)</tt> will likely
  2529. produce array mostly filled with 0's and 255's, since the range (0, 255)
  2530. is significantly smaller than [-DBL_MAX, DBL_MAX).
  2531. Each of the methods fills the matrix with the random values from the
  2532. specified distribution. As the new numbers are generated, the RNG state
  2533. is updated accordingly. In case of multiple-channel images, every
  2534. channel is filled independently, which means that RNG cannot generate
  2535. samples from the multi-dimensional Gaussian distribution with
  2536. non-diagonal covariance matrix directly. To do that, the method
  2537. generates samples from multi-dimensional standard Gaussian distribution
  2538. with zero mean and identity covariation matrix, and then transforms them
  2539. using transform to get samples from the specified Gaussian distribution.
  2540. */
  2541. void fill( InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange = false );
  2542. /** @brief Returns the next random number sampled from the Gaussian distribution
  2543. @param sigma standard deviation of the distribution.
  2544. The method transforms the state using the MWC algorithm and returns the
  2545. next random number from the Gaussian distribution N(0,sigma) . That is,
  2546. the mean value of the returned random numbers is zero and the standard
  2547. deviation is the specified sigma .
  2548. */
  2549. double gaussian(double sigma);
  2550. uint64 state;
  2551. bool operator ==(const RNG& other) const;
  2552. };
  2553. /** @brief Mersenne Twister random number generator
  2554. Inspired by http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c
  2555. @todo document
  2556. */
  2557. class CV_EXPORTS RNG_MT19937
  2558. {
  2559. public:
  2560. RNG_MT19937();
  2561. RNG_MT19937(unsigned s);
  2562. void seed(unsigned s);
  2563. unsigned next();
  2564. operator int();
  2565. operator unsigned();
  2566. operator float();
  2567. operator double();
  2568. unsigned operator ()(unsigned N);
  2569. unsigned operator ()();
  2570. /** @brief returns uniformly distributed integer random number from [a,b) range*/
  2571. int uniform(int a, int b);
  2572. /** @brief returns uniformly distributed floating-point random number from [a,b) range*/
  2573. float uniform(float a, float b);
  2574. /** @brief returns uniformly distributed double-precision floating-point random number from [a,b) range*/
  2575. double uniform(double a, double b);
  2576. private:
  2577. enum PeriodParameters {N = 624, M = 397};
  2578. unsigned state[N];
  2579. int mti;
  2580. };
  2581. //! @} core_array
  2582. //! @addtogroup core_cluster
  2583. //! @{
  2584. /** @example samples/cpp/kmeans.cpp
  2585. An example on K-means clustering
  2586. */
  2587. /** @brief Finds centers of clusters and groups input samples around the clusters.
  2588. The function kmeans implements a k-means algorithm that finds the centers of cluster_count clusters
  2589. and groups the input samples around the clusters. As an output, \f$\texttt{bestLabels}_i\f$ contains a
  2590. 0-based cluster index for the sample stored in the \f$i^{th}\f$ row of the samples matrix.
  2591. @note
  2592. - (Python) An example on K-means clustering can be found at
  2593. opencv_source_code/samples/python/kmeans.py
  2594. @param data Data for clustering. An array of N-Dimensional points with float coordinates is needed.
  2595. Examples of this array can be:
  2596. - Mat points(count, 2, CV_32F);
  2597. - Mat points(count, 1, CV_32FC2);
  2598. - Mat points(1, count, CV_32FC2);
  2599. - std::vector\<cv::Point2f\> points(sampleCount);
  2600. @param K Number of clusters to split the set by.
  2601. @param bestLabels Input/output integer array that stores the cluster indices for every sample.
  2602. @param criteria The algorithm termination criteria, that is, the maximum number of iterations and/or
  2603. the desired accuracy. The accuracy is specified as criteria.epsilon. As soon as each of the cluster
  2604. centers moves by less than criteria.epsilon on some iteration, the algorithm stops.
  2605. @param attempts Flag to specify the number of times the algorithm is executed using different
  2606. initial labellings. The algorithm returns the labels that yield the best compactness (see the last
  2607. function parameter).
  2608. @param flags Flag that can take values of cv::KmeansFlags
  2609. @param centers Output matrix of the cluster centers, one row per each cluster center.
  2610. @return The function returns the compactness measure that is computed as
  2611. \f[\sum _i \| \texttt{samples} _i - \texttt{centers} _{ \texttt{labels} _i} \| ^2\f]
  2612. after every attempt. The best (minimum) value is chosen and the corresponding labels and the
  2613. compactness value are returned by the function. Basically, you can use only the core of the
  2614. function, set the number of attempts to 1, initialize labels each time using a custom algorithm,
  2615. pass them with the ( flags = #KMEANS_USE_INITIAL_LABELS ) flag, and then choose the best
  2616. (most-compact) clustering.
  2617. */
  2618. CV_EXPORTS_W double kmeans( InputArray data, int K, InputOutputArray bestLabels,
  2619. TermCriteria criteria, int attempts,
  2620. int flags, OutputArray centers = noArray() );
  2621. //! @} core_cluster
  2622. //! @addtogroup core_basic
  2623. //! @{
  2624. /////////////////////////////// Formatted output of cv::Mat ///////////////////////////
  2625. /** @todo document */
  2626. class CV_EXPORTS Formatted
  2627. {
  2628. public:
  2629. virtual const char* next() = 0;
  2630. virtual void reset() = 0;
  2631. virtual ~Formatted();
  2632. };
  2633. /** @todo document */
  2634. class CV_EXPORTS Formatter
  2635. {
  2636. public:
  2637. enum FormatType {
  2638. FMT_DEFAULT = 0,
  2639. FMT_MATLAB = 1,
  2640. FMT_CSV = 2,
  2641. FMT_PYTHON = 3,
  2642. FMT_NUMPY = 4,
  2643. FMT_C = 5
  2644. };
  2645. virtual ~Formatter();
  2646. virtual Ptr<Formatted> format(const Mat& mtx) const = 0;
  2647. virtual void set16fPrecision(int p = 4) = 0;
  2648. virtual void set32fPrecision(int p = 8) = 0;
  2649. virtual void set64fPrecision(int p = 16) = 0;
  2650. virtual void setMultiline(bool ml = true) = 0;
  2651. static Ptr<Formatter> get(Formatter::FormatType fmt = FMT_DEFAULT);
  2652. };
  2653. static inline
  2654. String& operator << (String& out, Ptr<Formatted> fmtd)
  2655. {
  2656. fmtd->reset();
  2657. for(const char* str = fmtd->next(); str; str = fmtd->next())
  2658. out += cv::String(str);
  2659. return out;
  2660. }
  2661. static inline
  2662. String& operator << (String& out, const Mat& mtx)
  2663. {
  2664. return out << Formatter::get()->format(mtx);
  2665. }
  2666. //////////////////////////////////////// Algorithm ////////////////////////////////////
  2667. class CV_EXPORTS Algorithm;
  2668. template<typename _Tp, typename _EnumTp = void> struct ParamType {};
  2669. /** @brief This is a base class for all more or less complex algorithms in OpenCV
  2670. especially for classes of algorithms, for which there can be multiple implementations. The examples
  2671. are stereo correspondence (for which there are algorithms like block matching, semi-global block
  2672. matching, graph-cut etc.), background subtraction (which can be done using mixture-of-gaussians
  2673. models, codebook-based algorithm etc.), optical flow (block matching, Lucas-Kanade, Horn-Schunck
  2674. etc.).
  2675. Here is example of SimpleBlobDetector use in your application via Algorithm interface:
  2676. @snippet snippets/core_various.cpp Algorithm
  2677. */
  2678. class CV_EXPORTS_W Algorithm
  2679. {
  2680. public:
  2681. Algorithm();
  2682. virtual ~Algorithm();
  2683. /** @brief Clears the algorithm state
  2684. */
  2685. CV_WRAP virtual void clear() {}
  2686. /** @brief Stores algorithm parameters in a file storage
  2687. */
  2688. virtual void write(FileStorage& fs) const { CV_UNUSED(fs); }
  2689. /** @brief simplified API for language bindings
  2690. * @overload
  2691. */
  2692. CV_WRAP void write(const Ptr<FileStorage>& fs, const String& name = String()) const;
  2693. /** @brief Reads algorithm parameters from a file storage
  2694. */
  2695. CV_WRAP virtual void read(const FileNode& fn) { CV_UNUSED(fn); }
  2696. /** @brief Returns true if the Algorithm is empty (e.g. in the very beginning or after unsuccessful read
  2697. */
  2698. CV_WRAP virtual bool empty() const { return false; }
  2699. /** @brief Reads algorithm from the file node
  2700. This is static template method of Algorithm. It's usage is following (in the case of SVM):
  2701. @code
  2702. cv::FileStorage fsRead("example.xml", FileStorage::READ);
  2703. Ptr<SVM> svm = Algorithm::read<SVM>(fsRead.root());
  2704. @endcode
  2705. In order to make this method work, the derived class must overwrite Algorithm::read(const
  2706. FileNode& fn) and also have static create() method without parameters
  2707. (or with all the optional parameters)
  2708. */
  2709. template<typename _Tp> static Ptr<_Tp> read(const FileNode& fn)
  2710. {
  2711. Ptr<_Tp> obj = _Tp::create();
  2712. obj->read(fn);
  2713. return !obj->empty() ? obj : Ptr<_Tp>();
  2714. }
  2715. /** @brief Loads algorithm from the file
  2716. @param filename Name of the file to read.
  2717. @param objname The optional name of the node to read (if empty, the first top-level node will be used)
  2718. This is static template method of Algorithm. It's usage is following (in the case of SVM):
  2719. @code
  2720. Ptr<SVM> svm = Algorithm::load<SVM>("my_svm_model.xml");
  2721. @endcode
  2722. In order to make this method work, the derived class must overwrite Algorithm::read(const
  2723. FileNode& fn).
  2724. */
  2725. template<typename _Tp> static Ptr<_Tp> load(const String& filename, const String& objname=String())
  2726. {
  2727. FileStorage fs(filename, FileStorage::READ);
  2728. CV_Assert(fs.isOpened());
  2729. FileNode fn = objname.empty() ? fs.getFirstTopLevelNode() : fs[objname];
  2730. if (fn.empty()) return Ptr<_Tp>();
  2731. Ptr<_Tp> obj = _Tp::create();
  2732. obj->read(fn);
  2733. return !obj->empty() ? obj : Ptr<_Tp>();
  2734. }
  2735. /** @brief Loads algorithm from a String
  2736. @param strModel The string variable containing the model you want to load.
  2737. @param objname The optional name of the node to read (if empty, the first top-level node will be used)
  2738. This is static template method of Algorithm. It's usage is following (in the case of SVM):
  2739. @code
  2740. Ptr<SVM> svm = Algorithm::loadFromString<SVM>(myStringModel);
  2741. @endcode
  2742. */
  2743. template<typename _Tp> static Ptr<_Tp> loadFromString(const String& strModel, const String& objname=String())
  2744. {
  2745. FileStorage fs(strModel, FileStorage::READ + FileStorage::MEMORY);
  2746. FileNode fn = objname.empty() ? fs.getFirstTopLevelNode() : fs[objname];
  2747. Ptr<_Tp> obj = _Tp::create();
  2748. obj->read(fn);
  2749. return !obj->empty() ? obj : Ptr<_Tp>();
  2750. }
  2751. /** Saves the algorithm to a file.
  2752. In order to make this method work, the derived class must implement Algorithm::write(FileStorage& fs). */
  2753. CV_WRAP virtual void save(const String& filename) const;
  2754. /** Returns the algorithm string identifier.
  2755. This string is used as top level xml/yml node tag when the object is saved to a file or string. */
  2756. CV_WRAP virtual String getDefaultName() const;
  2757. protected:
  2758. void writeFormat(FileStorage& fs) const;
  2759. };
  2760. enum struct Param {
  2761. INT=0, BOOLEAN=1, REAL=2, STRING=3, MAT=4, MAT_VECTOR=5, ALGORITHM=6, FLOAT=7,
  2762. UNSIGNED_INT=8, UINT64=9, UCHAR=11, SCALAR=12
  2763. };
  2764. template<> struct ParamType<bool>
  2765. {
  2766. typedef bool const_param_type;
  2767. typedef bool member_type;
  2768. static const Param type = Param::BOOLEAN;
  2769. };
  2770. template<> struct ParamType<int>
  2771. {
  2772. typedef int const_param_type;
  2773. typedef int member_type;
  2774. static const Param type = Param::INT;
  2775. };
  2776. template<> struct ParamType<double>
  2777. {
  2778. typedef double const_param_type;
  2779. typedef double member_type;
  2780. static const Param type = Param::REAL;
  2781. };
  2782. template<> struct ParamType<String>
  2783. {
  2784. typedef const String& const_param_type;
  2785. typedef String member_type;
  2786. static const Param type = Param::STRING;
  2787. };
  2788. template<> struct ParamType<Mat>
  2789. {
  2790. typedef const Mat& const_param_type;
  2791. typedef Mat member_type;
  2792. static const Param type = Param::MAT;
  2793. };
  2794. template<> struct ParamType<std::vector<Mat> >
  2795. {
  2796. typedef const std::vector<Mat>& const_param_type;
  2797. typedef std::vector<Mat> member_type;
  2798. static const Param type = Param::MAT_VECTOR;
  2799. };
  2800. template<> struct ParamType<Algorithm>
  2801. {
  2802. typedef const Ptr<Algorithm>& const_param_type;
  2803. typedef Ptr<Algorithm> member_type;
  2804. static const Param type = Param::ALGORITHM;
  2805. };
  2806. template<> struct ParamType<float>
  2807. {
  2808. typedef float const_param_type;
  2809. typedef float member_type;
  2810. static const Param type = Param::FLOAT;
  2811. };
  2812. template<> struct ParamType<unsigned>
  2813. {
  2814. typedef unsigned const_param_type;
  2815. typedef unsigned member_type;
  2816. static const Param type = Param::UNSIGNED_INT;
  2817. };
  2818. template<> struct ParamType<uint64>
  2819. {
  2820. typedef uint64 const_param_type;
  2821. typedef uint64 member_type;
  2822. static const Param type = Param::UINT64;
  2823. };
  2824. template<> struct ParamType<uchar>
  2825. {
  2826. typedef uchar const_param_type;
  2827. typedef uchar member_type;
  2828. static const Param type = Param::UCHAR;
  2829. };
  2830. template<> struct ParamType<Scalar>
  2831. {
  2832. typedef const Scalar& const_param_type;
  2833. typedef Scalar member_type;
  2834. static const Param type = Param::SCALAR;
  2835. };
  2836. template<typename _Tp>
  2837. struct ParamType<_Tp, typename std::enable_if< std::is_enum<_Tp>::value >::type>
  2838. {
  2839. typedef typename std::underlying_type<_Tp>::type const_param_type;
  2840. typedef typename std::underlying_type<_Tp>::type member_type;
  2841. static const Param type = Param::INT;
  2842. };
  2843. //! @} core_basic
  2844. } //namespace cv
  2845. #include "opencv2/core/operations.hpp"
  2846. #include "opencv2/core/cvstd.inl.hpp"
  2847. #include "opencv2/core/utility.hpp"
  2848. #include "opencv2/core/optim.hpp"
  2849. #include "opencv2/core/ovx.hpp"
  2850. #endif /*OPENCV_CORE_HPP*/