mat.hpp 157 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766
  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-2008, Intel Corporation, all rights reserved.
  14. // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
  15. // Copyright (C) 2013, OpenCV Foundation, all rights reserved.
  16. // Third party copyrights are property of their respective owners.
  17. //
  18. // Redistribution and use in source and binary forms, with or without modification,
  19. // are permitted provided that the following conditions are met:
  20. //
  21. // * Redistribution's of source code must retain the above copyright notice,
  22. // this list of conditions and the following disclaimer.
  23. //
  24. // * Redistribution's in binary form must reproduce the above copyright notice,
  25. // this list of conditions and the following disclaimer in the documentation
  26. // and/or other materials provided with the distribution.
  27. //
  28. // * The name of the copyright holders may not be used to endorse or promote products
  29. // derived from this software without specific prior written permission.
  30. //
  31. // This software is provided by the copyright holders and contributors "as is" and
  32. // any express or implied warranties, including, but not limited to, the implied
  33. // warranties of merchantability and fitness for a particular purpose are disclaimed.
  34. // In no event shall the Intel Corporation or contributors be liable for any direct,
  35. // indirect, incidental, special, exemplary, or consequential damages
  36. // (including, but not limited to, procurement of substitute goods or services;
  37. // loss of use, data, or profits; or business interruption) however caused
  38. // and on any theory of liability, whether in contract, strict liability,
  39. // or tort (including negligence or otherwise) arising in any way out of
  40. // the use of this software, even if advised of the possibility of such damage.
  41. //
  42. //M*/
  43. #ifndef OPENCV_CORE_MAT_HPP
  44. #define OPENCV_CORE_MAT_HPP
  45. #ifndef __cplusplus
  46. # error mat.hpp header must be compiled as C++
  47. #endif
  48. #include "opencv2/core/matx.hpp"
  49. #include "opencv2/core/types.hpp"
  50. #include "opencv2/core/bufferpool.hpp"
  51. #ifdef CV_CXX11
  52. #include <type_traits>
  53. #endif
  54. namespace cv
  55. {
  56. //! @addtogroup core_basic
  57. //! @{
  58. enum { ACCESS_READ=1<<24, ACCESS_WRITE=1<<25,
  59. ACCESS_RW=3<<24, ACCESS_MASK=ACCESS_RW, ACCESS_FAST=1<<26 };
  60. CV__DEBUG_NS_BEGIN
  61. class CV_EXPORTS _OutputArray;
  62. //////////////////////// Input/Output Array Arguments /////////////////////////////////
  63. /** @brief This is the proxy class for passing read-only input arrays into OpenCV functions.
  64. It is defined as:
  65. @code
  66. typedef const _InputArray& InputArray;
  67. @endcode
  68. where _InputArray is a class that can be constructed from `Mat`, `Mat_<T>`, `Matx<T, m, n>`,
  69. `std::vector<T>`, `std::vector<std::vector<T> >`, `std::vector<Mat>`, `std::vector<Mat_<T> >`,
  70. `UMat`, `std::vector<UMat>` or `double`. It can also be constructed from a matrix expression.
  71. Since this is mostly implementation-level class, and its interface may change in future versions, we
  72. do not describe it in details. There are a few key things, though, that should be kept in mind:
  73. - When you see in the reference manual or in OpenCV source code a function that takes
  74. InputArray, it means that you can actually pass `Mat`, `Matx`, `vector<T>` etc. (see above the
  75. complete list).
  76. - Optional input arguments: If some of the input arrays may be empty, pass cv::noArray() (or
  77. simply cv::Mat() as you probably did before).
  78. - The class is designed solely for passing parameters. That is, normally you *should not*
  79. declare class members, local and global variables of this type.
  80. - If you want to design your own function or a class method that can operate of arrays of
  81. multiple types, you can use InputArray (or OutputArray) for the respective parameters. Inside
  82. a function you should use _InputArray::getMat() method to construct a matrix header for the
  83. array (without copying data). _InputArray::kind() can be used to distinguish Mat from
  84. `vector<>` etc., but normally it is not needed.
  85. Here is how you can use a function that takes InputArray :
  86. @code
  87. std::vector<Point2f> vec;
  88. // points or a circle
  89. for( int i = 0; i < 30; i++ )
  90. vec.push_back(Point2f((float)(100 + 30*cos(i*CV_PI*2/5)),
  91. (float)(100 - 30*sin(i*CV_PI*2/5))));
  92. cv::transform(vec, vec, cv::Matx23f(0.707, -0.707, 10, 0.707, 0.707, 20));
  93. @endcode
  94. That is, we form an STL vector containing points, and apply in-place affine transformation to the
  95. vector using the 2x3 matrix created inline as `Matx<float, 2, 3>` instance.
  96. Here is how such a function can be implemented (for simplicity, we implement a very specific case of
  97. it, according to the assertion statement inside) :
  98. @code
  99. void myAffineTransform(InputArray _src, OutputArray _dst, InputArray _m)
  100. {
  101. // get Mat headers for input arrays. This is O(1) operation,
  102. // unless _src and/or _m are matrix expressions.
  103. Mat src = _src.getMat(), m = _m.getMat();
  104. CV_Assert( src.type() == CV_32FC2 && m.type() == CV_32F && m.size() == Size(3, 2) );
  105. // [re]create the output array so that it has the proper size and type.
  106. // In case of Mat it calls Mat::create, in case of STL vector it calls vector::resize.
  107. _dst.create(src.size(), src.type());
  108. Mat dst = _dst.getMat();
  109. for( int i = 0; i < src.rows; i++ )
  110. for( int j = 0; j < src.cols; j++ )
  111. {
  112. Point2f pt = src.at<Point2f>(i, j);
  113. dst.at<Point2f>(i, j) = Point2f(m.at<float>(0, 0)*pt.x +
  114. m.at<float>(0, 1)*pt.y +
  115. m.at<float>(0, 2),
  116. m.at<float>(1, 0)*pt.x +
  117. m.at<float>(1, 1)*pt.y +
  118. m.at<float>(1, 2));
  119. }
  120. }
  121. @endcode
  122. There is another related type, InputArrayOfArrays, which is currently defined as a synonym for
  123. InputArray:
  124. @code
  125. typedef InputArray InputArrayOfArrays;
  126. @endcode
  127. It denotes function arguments that are either vectors of vectors or vectors of matrices. A separate
  128. synonym is needed to generate Python/Java etc. wrappers properly. At the function implementation
  129. level their use is similar, but _InputArray::getMat(idx) should be used to get header for the
  130. idx-th component of the outer vector and _InputArray::size().area() should be used to find the
  131. number of components (vectors/matrices) of the outer vector.
  132. In general, type support is limited to cv::Mat types. Other types are forbidden.
  133. But in some cases we need to support passing of custom non-general Mat types, like arrays of cv::KeyPoint, cv::DMatch, etc.
  134. This data is not intended to be interpreted as an image data, or processed somehow like regular cv::Mat.
  135. To pass such custom type use rawIn() / rawOut() / rawInOut() wrappers.
  136. Custom type is wrapped as Mat-compatible `CV_8UC<N>` values (N = sizeof(T), N <= CV_CN_MAX).
  137. */
  138. class CV_EXPORTS _InputArray
  139. {
  140. public:
  141. enum {
  142. KIND_SHIFT = 16,
  143. FIXED_TYPE = 0x8000 << KIND_SHIFT,
  144. FIXED_SIZE = 0x4000 << KIND_SHIFT,
  145. KIND_MASK = 31 << KIND_SHIFT,
  146. NONE = 0 << KIND_SHIFT,
  147. MAT = 1 << KIND_SHIFT,
  148. MATX = 2 << KIND_SHIFT,
  149. STD_VECTOR = 3 << KIND_SHIFT,
  150. STD_VECTOR_VECTOR = 4 << KIND_SHIFT,
  151. STD_VECTOR_MAT = 5 << KIND_SHIFT,
  152. #if OPENCV_ABI_COMPATIBILITY < 500
  153. EXPR = 6 << KIND_SHIFT, //!< removed: https://github.com/opencv/opencv/pull/17046
  154. #endif
  155. OPENGL_BUFFER = 7 << KIND_SHIFT,
  156. CUDA_HOST_MEM = 8 << KIND_SHIFT,
  157. CUDA_GPU_MAT = 9 << KIND_SHIFT,
  158. UMAT =10 << KIND_SHIFT,
  159. STD_VECTOR_UMAT =11 << KIND_SHIFT,
  160. STD_BOOL_VECTOR =12 << KIND_SHIFT,
  161. STD_VECTOR_CUDA_GPU_MAT = 13 << KIND_SHIFT,
  162. #if OPENCV_ABI_COMPATIBILITY < 500
  163. STD_ARRAY =14 << KIND_SHIFT, //!< removed: https://github.com/opencv/opencv/issues/18897
  164. #endif
  165. STD_ARRAY_MAT =15 << KIND_SHIFT
  166. };
  167. _InputArray();
  168. _InputArray(int _flags, void* _obj);
  169. _InputArray(const Mat& m);
  170. _InputArray(const MatExpr& expr);
  171. _InputArray(const std::vector<Mat>& vec);
  172. template<typename _Tp> _InputArray(const Mat_<_Tp>& m);
  173. template<typename _Tp> _InputArray(const std::vector<_Tp>& vec);
  174. _InputArray(const std::vector<bool>& vec);
  175. template<typename _Tp> _InputArray(const std::vector<std::vector<_Tp> >& vec);
  176. _InputArray(const std::vector<std::vector<bool> >&);
  177. template<typename _Tp> _InputArray(const std::vector<Mat_<_Tp> >& vec);
  178. template<typename _Tp> _InputArray(const _Tp* vec, int n);
  179. template<typename _Tp, int m, int n> _InputArray(const Matx<_Tp, m, n>& matx);
  180. _InputArray(const double& val);
  181. _InputArray(const cuda::GpuMat& d_mat);
  182. _InputArray(const std::vector<cuda::GpuMat>& d_mat_array);
  183. _InputArray(const ogl::Buffer& buf);
  184. _InputArray(const cuda::HostMem& cuda_mem);
  185. template<typename _Tp> _InputArray(const cudev::GpuMat_<_Tp>& m);
  186. _InputArray(const UMat& um);
  187. _InputArray(const std::vector<UMat>& umv);
  188. #ifdef CV_CXX_STD_ARRAY
  189. template<typename _Tp, std::size_t _Nm> _InputArray(const std::array<_Tp, _Nm>& arr);
  190. template<std::size_t _Nm> _InputArray(const std::array<Mat, _Nm>& arr);
  191. #endif
  192. template<typename _Tp> static _InputArray rawIn(const std::vector<_Tp>& vec);
  193. #ifdef CV_CXX_STD_ARRAY
  194. template<typename _Tp, std::size_t _Nm> static _InputArray rawIn(const std::array<_Tp, _Nm>& arr);
  195. #endif
  196. Mat getMat(int idx=-1) const;
  197. Mat getMat_(int idx=-1) const;
  198. UMat getUMat(int idx=-1) const;
  199. void getMatVector(std::vector<Mat>& mv) const;
  200. void getUMatVector(std::vector<UMat>& umv) const;
  201. void getGpuMatVector(std::vector<cuda::GpuMat>& gpumv) const;
  202. cuda::GpuMat getGpuMat() const;
  203. ogl::Buffer getOGlBuffer() const;
  204. int getFlags() const;
  205. void* getObj() const;
  206. Size getSz() const;
  207. int kind() const;
  208. int dims(int i=-1) const;
  209. int cols(int i=-1) const;
  210. int rows(int i=-1) const;
  211. Size size(int i=-1) const;
  212. int sizend(int* sz, int i=-1) const;
  213. bool sameSize(const _InputArray& arr) const;
  214. size_t total(int i=-1) const;
  215. int type(int i=-1) const;
  216. int depth(int i=-1) const;
  217. int channels(int i=-1) const;
  218. bool isContinuous(int i=-1) const;
  219. bool isSubmatrix(int i=-1) const;
  220. bool empty() const;
  221. void copyTo(const _OutputArray& arr) const;
  222. void copyTo(const _OutputArray& arr, const _InputArray & mask) const;
  223. size_t offset(int i=-1) const;
  224. size_t step(int i=-1) const;
  225. bool isMat() const;
  226. bool isUMat() const;
  227. bool isMatVector() const;
  228. bool isUMatVector() const;
  229. bool isMatx() const;
  230. bool isVector() const;
  231. bool isGpuMat() const;
  232. bool isGpuMatVector() const;
  233. ~_InputArray();
  234. protected:
  235. int flags;
  236. void* obj;
  237. Size sz;
  238. void init(int _flags, const void* _obj);
  239. void init(int _flags, const void* _obj, Size _sz);
  240. };
  241. /** @brief This type is very similar to InputArray except that it is used for input/output and output function
  242. parameters.
  243. Just like with InputArray, OpenCV users should not care about OutputArray, they just pass `Mat`,
  244. `vector<T>` etc. to the functions. The same limitation as for `InputArray`: *Do not explicitly
  245. create OutputArray instances* applies here too.
  246. If you want to make your function polymorphic (i.e. accept different arrays as output parameters),
  247. it is also not very difficult. Take the sample above as the reference. Note that
  248. _OutputArray::create() needs to be called before _OutputArray::getMat(). This way you guarantee
  249. that the output array is properly allocated.
  250. Optional output parameters. If you do not need certain output array to be computed and returned to
  251. you, pass cv::noArray(), just like you would in the case of optional input array. At the
  252. implementation level, use _OutputArray::needed() to check if certain output array needs to be
  253. computed or not.
  254. There are several synonyms for OutputArray that are used to assist automatic Python/Java/... wrapper
  255. generators:
  256. @code
  257. typedef OutputArray OutputArrayOfArrays;
  258. typedef OutputArray InputOutputArray;
  259. typedef OutputArray InputOutputArrayOfArrays;
  260. @endcode
  261. */
  262. class CV_EXPORTS _OutputArray : public _InputArray
  263. {
  264. public:
  265. enum
  266. {
  267. DEPTH_MASK_8U = 1 << CV_8U,
  268. DEPTH_MASK_8S = 1 << CV_8S,
  269. DEPTH_MASK_16U = 1 << CV_16U,
  270. DEPTH_MASK_16S = 1 << CV_16S,
  271. DEPTH_MASK_32S = 1 << CV_32S,
  272. DEPTH_MASK_32F = 1 << CV_32F,
  273. DEPTH_MASK_64F = 1 << CV_64F,
  274. DEPTH_MASK_ALL = (DEPTH_MASK_64F<<1)-1,
  275. DEPTH_MASK_ALL_BUT_8S = DEPTH_MASK_ALL & ~DEPTH_MASK_8S,
  276. DEPTH_MASK_FLT = DEPTH_MASK_32F + DEPTH_MASK_64F
  277. };
  278. _OutputArray();
  279. _OutputArray(int _flags, void* _obj);
  280. _OutputArray(Mat& m);
  281. _OutputArray(std::vector<Mat>& vec);
  282. _OutputArray(cuda::GpuMat& d_mat);
  283. _OutputArray(std::vector<cuda::GpuMat>& d_mat);
  284. _OutputArray(ogl::Buffer& buf);
  285. _OutputArray(cuda::HostMem& cuda_mem);
  286. template<typename _Tp> _OutputArray(cudev::GpuMat_<_Tp>& m);
  287. template<typename _Tp> _OutputArray(std::vector<_Tp>& vec);
  288. _OutputArray(std::vector<bool>& vec);
  289. template<typename _Tp> _OutputArray(std::vector<std::vector<_Tp> >& vec);
  290. _OutputArray(std::vector<std::vector<bool> >&);
  291. template<typename _Tp> _OutputArray(std::vector<Mat_<_Tp> >& vec);
  292. template<typename _Tp> _OutputArray(Mat_<_Tp>& m);
  293. template<typename _Tp> _OutputArray(_Tp* vec, int n);
  294. template<typename _Tp, int m, int n> _OutputArray(Matx<_Tp, m, n>& matx);
  295. _OutputArray(UMat& m);
  296. _OutputArray(std::vector<UMat>& vec);
  297. _OutputArray(const Mat& m);
  298. _OutputArray(const std::vector<Mat>& vec);
  299. _OutputArray(const cuda::GpuMat& d_mat);
  300. _OutputArray(const std::vector<cuda::GpuMat>& d_mat);
  301. _OutputArray(const ogl::Buffer& buf);
  302. _OutputArray(const cuda::HostMem& cuda_mem);
  303. template<typename _Tp> _OutputArray(const cudev::GpuMat_<_Tp>& m);
  304. template<typename _Tp> _OutputArray(const std::vector<_Tp>& vec);
  305. template<typename _Tp> _OutputArray(const std::vector<std::vector<_Tp> >& vec);
  306. template<typename _Tp> _OutputArray(const std::vector<Mat_<_Tp> >& vec);
  307. template<typename _Tp> _OutputArray(const Mat_<_Tp>& m);
  308. template<typename _Tp> _OutputArray(const _Tp* vec, int n);
  309. template<typename _Tp, int m, int n> _OutputArray(const Matx<_Tp, m, n>& matx);
  310. _OutputArray(const UMat& m);
  311. _OutputArray(const std::vector<UMat>& vec);
  312. #ifdef CV_CXX_STD_ARRAY
  313. template<typename _Tp, std::size_t _Nm> _OutputArray(std::array<_Tp, _Nm>& arr);
  314. template<typename _Tp, std::size_t _Nm> _OutputArray(const std::array<_Tp, _Nm>& arr);
  315. template<std::size_t _Nm> _OutputArray(std::array<Mat, _Nm>& arr);
  316. template<std::size_t _Nm> _OutputArray(const std::array<Mat, _Nm>& arr);
  317. #endif
  318. template<typename _Tp> static _OutputArray rawOut(std::vector<_Tp>& vec);
  319. #ifdef CV_CXX_STD_ARRAY
  320. template<typename _Tp, std::size_t _Nm> static _OutputArray rawOut(std::array<_Tp, _Nm>& arr);
  321. #endif
  322. bool fixedSize() const;
  323. bool fixedType() const;
  324. bool needed() const;
  325. Mat& getMatRef(int i=-1) const;
  326. UMat& getUMatRef(int i=-1) const;
  327. cuda::GpuMat& getGpuMatRef() const;
  328. std::vector<cuda::GpuMat>& getGpuMatVecRef() const;
  329. ogl::Buffer& getOGlBufferRef() const;
  330. cuda::HostMem& getHostMemRef() const;
  331. void create(Size sz, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
  332. void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
  333. void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, int fixedDepthMask=0) const;
  334. void createSameSize(const _InputArray& arr, int mtype) const;
  335. void release() const;
  336. void clear() const;
  337. void setTo(const _InputArray& value, const _InputArray & mask = _InputArray()) const;
  338. void assign(const UMat& u) const;
  339. void assign(const Mat& m) const;
  340. void assign(const std::vector<UMat>& v) const;
  341. void assign(const std::vector<Mat>& v) const;
  342. void move(UMat& u) const;
  343. void move(Mat& m) const;
  344. };
  345. class CV_EXPORTS _InputOutputArray : public _OutputArray
  346. {
  347. public:
  348. _InputOutputArray();
  349. _InputOutputArray(int _flags, void* _obj);
  350. _InputOutputArray(Mat& m);
  351. _InputOutputArray(std::vector<Mat>& vec);
  352. _InputOutputArray(cuda::GpuMat& d_mat);
  353. _InputOutputArray(ogl::Buffer& buf);
  354. _InputOutputArray(cuda::HostMem& cuda_mem);
  355. template<typename _Tp> _InputOutputArray(cudev::GpuMat_<_Tp>& m);
  356. template<typename _Tp> _InputOutputArray(std::vector<_Tp>& vec);
  357. _InputOutputArray(std::vector<bool>& vec);
  358. template<typename _Tp> _InputOutputArray(std::vector<std::vector<_Tp> >& vec);
  359. template<typename _Tp> _InputOutputArray(std::vector<Mat_<_Tp> >& vec);
  360. template<typename _Tp> _InputOutputArray(Mat_<_Tp>& m);
  361. template<typename _Tp> _InputOutputArray(_Tp* vec, int n);
  362. template<typename _Tp, int m, int n> _InputOutputArray(Matx<_Tp, m, n>& matx);
  363. _InputOutputArray(UMat& m);
  364. _InputOutputArray(std::vector<UMat>& vec);
  365. _InputOutputArray(const Mat& m);
  366. _InputOutputArray(const std::vector<Mat>& vec);
  367. _InputOutputArray(const cuda::GpuMat& d_mat);
  368. _InputOutputArray(const std::vector<cuda::GpuMat>& d_mat);
  369. _InputOutputArray(const ogl::Buffer& buf);
  370. _InputOutputArray(const cuda::HostMem& cuda_mem);
  371. template<typename _Tp> _InputOutputArray(const cudev::GpuMat_<_Tp>& m);
  372. template<typename _Tp> _InputOutputArray(const std::vector<_Tp>& vec);
  373. template<typename _Tp> _InputOutputArray(const std::vector<std::vector<_Tp> >& vec);
  374. template<typename _Tp> _InputOutputArray(const std::vector<Mat_<_Tp> >& vec);
  375. template<typename _Tp> _InputOutputArray(const Mat_<_Tp>& m);
  376. template<typename _Tp> _InputOutputArray(const _Tp* vec, int n);
  377. template<typename _Tp, int m, int n> _InputOutputArray(const Matx<_Tp, m, n>& matx);
  378. _InputOutputArray(const UMat& m);
  379. _InputOutputArray(const std::vector<UMat>& vec);
  380. #ifdef CV_CXX_STD_ARRAY
  381. template<typename _Tp, std::size_t _Nm> _InputOutputArray(std::array<_Tp, _Nm>& arr);
  382. template<typename _Tp, std::size_t _Nm> _InputOutputArray(const std::array<_Tp, _Nm>& arr);
  383. template<std::size_t _Nm> _InputOutputArray(std::array<Mat, _Nm>& arr);
  384. template<std::size_t _Nm> _InputOutputArray(const std::array<Mat, _Nm>& arr);
  385. #endif
  386. template<typename _Tp> static _InputOutputArray rawInOut(std::vector<_Tp>& vec);
  387. #ifdef CV_CXX_STD_ARRAY
  388. template<typename _Tp, std::size_t _Nm> _InputOutputArray rawInOut(std::array<_Tp, _Nm>& arr);
  389. #endif
  390. };
  391. /** Helper to wrap custom types. @see InputArray */
  392. template<typename _Tp> static inline _InputArray rawIn(_Tp& v);
  393. /** Helper to wrap custom types. @see InputArray */
  394. template<typename _Tp> static inline _OutputArray rawOut(_Tp& v);
  395. /** Helper to wrap custom types. @see InputArray */
  396. template<typename _Tp> static inline _InputOutputArray rawInOut(_Tp& v);
  397. CV__DEBUG_NS_END
  398. typedef const _InputArray& InputArray;
  399. typedef InputArray InputArrayOfArrays;
  400. typedef const _OutputArray& OutputArray;
  401. typedef OutputArray OutputArrayOfArrays;
  402. typedef const _InputOutputArray& InputOutputArray;
  403. typedef InputOutputArray InputOutputArrayOfArrays;
  404. CV_EXPORTS InputOutputArray noArray();
  405. /////////////////////////////////// MatAllocator //////////////////////////////////////
  406. //! Usage flags for allocator
  407. enum UMatUsageFlags
  408. {
  409. USAGE_DEFAULT = 0,
  410. // buffer allocation policy is platform and usage specific
  411. USAGE_ALLOCATE_HOST_MEMORY = 1 << 0,
  412. USAGE_ALLOCATE_DEVICE_MEMORY = 1 << 1,
  413. USAGE_ALLOCATE_SHARED_MEMORY = 1 << 2, // It is not equal to: USAGE_ALLOCATE_HOST_MEMORY | USAGE_ALLOCATE_DEVICE_MEMORY
  414. __UMAT_USAGE_FLAGS_32BIT = 0x7fffffff // Binary compatibility hint
  415. };
  416. struct CV_EXPORTS UMatData;
  417. /** @brief Custom array allocator
  418. */
  419. class CV_EXPORTS MatAllocator
  420. {
  421. public:
  422. MatAllocator() {}
  423. virtual ~MatAllocator() {}
  424. // let's comment it off for now to detect and fix all the uses of allocator
  425. //virtual void allocate(int dims, const int* sizes, int type, int*& refcount,
  426. // uchar*& datastart, uchar*& data, size_t* step) = 0;
  427. //virtual void deallocate(int* refcount, uchar* datastart, uchar* data) = 0;
  428. virtual UMatData* allocate(int dims, const int* sizes, int type,
  429. void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const = 0;
  430. virtual bool allocate(UMatData* data, int accessflags, UMatUsageFlags usageFlags) const = 0;
  431. virtual void deallocate(UMatData* data) const = 0;
  432. virtual void map(UMatData* data, int accessflags) const;
  433. virtual void unmap(UMatData* data) const;
  434. virtual void download(UMatData* data, void* dst, int dims, const size_t sz[],
  435. const size_t srcofs[], const size_t srcstep[],
  436. const size_t dststep[]) const;
  437. virtual void upload(UMatData* data, const void* src, int dims, const size_t sz[],
  438. const size_t dstofs[], const size_t dststep[],
  439. const size_t srcstep[]) const;
  440. virtual void copy(UMatData* srcdata, UMatData* dstdata, int dims, const size_t sz[],
  441. const size_t srcofs[], const size_t srcstep[],
  442. const size_t dstofs[], const size_t dststep[], bool sync) const;
  443. // default implementation returns DummyBufferPoolController
  444. virtual BufferPoolController* getBufferPoolController(const char* id = NULL) const;
  445. };
  446. //////////////////////////////// MatCommaInitializer //////////////////////////////////
  447. /** @brief Comma-separated Matrix Initializer
  448. The class instances are usually not created explicitly.
  449. Instead, they are created on "matrix << firstValue" operator.
  450. The sample below initializes 2x2 rotation matrix:
  451. \code
  452. double angle = 30, a = cos(angle*CV_PI/180), b = sin(angle*CV_PI/180);
  453. Mat R = (Mat_<double>(2,2) << a, -b, b, a);
  454. \endcode
  455. */
  456. template<typename _Tp> class MatCommaInitializer_
  457. {
  458. public:
  459. //! the constructor, created by "matrix << firstValue" operator, where matrix is cv::Mat
  460. MatCommaInitializer_(Mat_<_Tp>* _m);
  461. //! the operator that takes the next value and put it to the matrix
  462. template<typename T2> MatCommaInitializer_<_Tp>& operator , (T2 v);
  463. //! another form of conversion operator
  464. operator Mat_<_Tp>() const;
  465. protected:
  466. MatIterator_<_Tp> it;
  467. };
  468. /////////////////////////////////////// Mat ///////////////////////////////////////////
  469. // note that umatdata might be allocated together
  470. // with the matrix data, not as a separate object.
  471. // therefore, it does not have constructor or destructor;
  472. // it should be explicitly initialized using init().
  473. struct CV_EXPORTS UMatData
  474. {
  475. enum { COPY_ON_MAP=1, HOST_COPY_OBSOLETE=2,
  476. DEVICE_COPY_OBSOLETE=4, TEMP_UMAT=8, TEMP_COPIED_UMAT=24,
  477. USER_ALLOCATED=32, DEVICE_MEM_MAPPED=64,
  478. ASYNC_CLEANUP=128
  479. };
  480. UMatData(const MatAllocator* allocator);
  481. ~UMatData();
  482. // provide atomic access to the structure
  483. void lock();
  484. void unlock();
  485. bool hostCopyObsolete() const;
  486. bool deviceCopyObsolete() const;
  487. bool deviceMemMapped() const;
  488. bool copyOnMap() const;
  489. bool tempUMat() const;
  490. bool tempCopiedUMat() const;
  491. void markHostCopyObsolete(bool flag);
  492. void markDeviceCopyObsolete(bool flag);
  493. void markDeviceMemMapped(bool flag);
  494. const MatAllocator* prevAllocator;
  495. const MatAllocator* currAllocator;
  496. int urefcount;
  497. int refcount;
  498. uchar* data;
  499. uchar* origdata;
  500. size_t size;
  501. int flags;
  502. void* handle;
  503. void* userdata;
  504. int allocatorFlags_;
  505. int mapcount;
  506. UMatData* originalUMatData;
  507. };
  508. struct CV_EXPORTS MatSize
  509. {
  510. explicit MatSize(int* _p) CV_NOEXCEPT;
  511. int dims() const CV_NOEXCEPT;
  512. Size operator()() const;
  513. const int& operator[](int i) const;
  514. int& operator[](int i);
  515. operator const int*() const CV_NOEXCEPT; // TODO OpenCV 4.0: drop this
  516. bool operator == (const MatSize& sz) const CV_NOEXCEPT;
  517. bool operator != (const MatSize& sz) const CV_NOEXCEPT;
  518. int* p;
  519. };
  520. struct CV_EXPORTS MatStep
  521. {
  522. MatStep() CV_NOEXCEPT;
  523. explicit MatStep(size_t s) CV_NOEXCEPT;
  524. const size_t& operator[](int i) const CV_NOEXCEPT;
  525. size_t& operator[](int i) CV_NOEXCEPT;
  526. operator size_t() const;
  527. MatStep& operator = (size_t s);
  528. size_t* p;
  529. size_t buf[2];
  530. protected:
  531. MatStep& operator = (const MatStep&);
  532. };
  533. /** @example samples/cpp/cout_mat.cpp
  534. An example demonstrating the serial out capabilities of cv::Mat
  535. */
  536. /** @brief n-dimensional dense array class \anchor CVMat_Details
  537. The class Mat represents an n-dimensional dense numerical single-channel or multi-channel array. It
  538. can be used to store real or complex-valued vectors and matrices, grayscale or color images, voxel
  539. volumes, vector fields, point clouds, tensors, histograms (though, very high-dimensional histograms
  540. may be better stored in a SparseMat ). The data layout of the array `M` is defined by the array
  541. `M.step[]`, so that the address of element \f$(i_0,...,i_{M.dims-1})\f$, where \f$0\leq i_k<M.size[k]\f$, is
  542. computed as:
  543. \f[addr(M_{i_0,...,i_{M.dims-1}}) = M.data + M.step[0]*i_0 + M.step[1]*i_1 + ... + M.step[M.dims-1]*i_{M.dims-1}\f]
  544. In case of a 2-dimensional array, the above formula is reduced to:
  545. \f[addr(M_{i,j}) = M.data + M.step[0]*i + M.step[1]*j\f]
  546. Note that `M.step[i] >= M.step[i+1]` (in fact, `M.step[i] >= M.step[i+1]*M.size[i+1]` ). This means
  547. that 2-dimensional matrices are stored row-by-row, 3-dimensional matrices are stored plane-by-plane,
  548. and so on. M.step[M.dims-1] is minimal and always equal to the element size M.elemSize() .
  549. So, the data layout in Mat is fully compatible with CvMat, IplImage, and CvMatND types from OpenCV
  550. 1.x. It is also compatible with the majority of dense array types from the standard toolkits and
  551. SDKs, such as Numpy (ndarray), Win32 (independent device bitmaps), and others, that is, with any
  552. array that uses *steps* (or *strides*) to compute the position of a pixel. Due to this
  553. compatibility, it is possible to make a Mat header for user-allocated data and process it in-place
  554. using OpenCV functions.
  555. There are many different ways to create a Mat object. The most popular options are listed below:
  556. - Use the create(nrows, ncols, type) method or the similar Mat(nrows, ncols, type[, fillValue])
  557. constructor. A new array of the specified size and type is allocated. type has the same meaning as
  558. in the cvCreateMat method. For example, CV_8UC1 means a 8-bit single-channel array, CV_32FC2
  559. means a 2-channel (complex) floating-point array, and so on.
  560. @code
  561. // make a 7x7 complex matrix filled with 1+3j.
  562. Mat M(7,7,CV_32FC2,Scalar(1,3));
  563. // and now turn M to a 100x60 15-channel 8-bit matrix.
  564. // The old content will be deallocated
  565. M.create(100,60,CV_8UC(15));
  566. @endcode
  567. As noted in the introduction to this chapter, create() allocates only a new array when the shape
  568. or type of the current array are different from the specified ones.
  569. - Create a multi-dimensional array:
  570. @code
  571. // create a 100x100x100 8-bit array
  572. int sz[] = {100, 100, 100};
  573. Mat bigCube(3, sz, CV_8U, Scalar::all(0));
  574. @endcode
  575. It passes the number of dimensions =1 to the Mat constructor but the created array will be
  576. 2-dimensional with the number of columns set to 1. So, Mat::dims is always \>= 2 (can also be 0
  577. when the array is empty).
  578. - Use a copy constructor or assignment operator where there can be an array or expression on the
  579. right side (see below). As noted in the introduction, the array assignment is an O(1) operation
  580. because it only copies the header and increases the reference counter. The Mat::clone() method can
  581. be used to get a full (deep) copy of the array when you need it.
  582. - Construct a header for a part of another array. It can be a single row, single column, several
  583. rows, several columns, rectangular region in the array (called a *minor* in algebra) or a
  584. diagonal. Such operations are also O(1) because the new header references the same data. You can
  585. actually modify a part of the array using this feature, for example:
  586. @code
  587. // add the 5-th row, multiplied by 3 to the 3rd row
  588. M.row(3) = M.row(3) + M.row(5)*3;
  589. // now copy the 7-th column to the 1-st column
  590. // M.col(1) = M.col(7); // this will not work
  591. Mat M1 = M.col(1);
  592. M.col(7).copyTo(M1);
  593. // create a new 320x240 image
  594. Mat img(Size(320,240),CV_8UC3);
  595. // select a ROI
  596. Mat roi(img, Rect(10,10,100,100));
  597. // fill the ROI with (0,255,0) (which is green in RGB space);
  598. // the original 320x240 image will be modified
  599. roi = Scalar(0,255,0);
  600. @endcode
  601. Due to the additional datastart and dataend members, it is possible to compute a relative
  602. sub-array position in the main *container* array using locateROI():
  603. @code
  604. Mat A = Mat::eye(10, 10, CV_32S);
  605. // extracts A columns, 1 (inclusive) to 3 (exclusive).
  606. Mat B = A(Range::all(), Range(1, 3));
  607. // extracts B rows, 5 (inclusive) to 9 (exclusive).
  608. // that is, C \~ A(Range(5, 9), Range(1, 3))
  609. Mat C = B(Range(5, 9), Range::all());
  610. Size size; Point ofs;
  611. C.locateROI(size, ofs);
  612. // size will be (width=10,height=10) and the ofs will be (x=1, y=5)
  613. @endcode
  614. As in case of whole matrices, if you need a deep copy, use the `clone()` method of the extracted
  615. sub-matrices.
  616. - Make a header for user-allocated data. It can be useful to do the following:
  617. -# Process "foreign" data using OpenCV (for example, when you implement a DirectShow\* filter or
  618. a processing module for gstreamer, and so on). For example:
  619. @code
  620. Mat process_video_frame(const unsigned char* pixels,
  621. int width, int height, int step)
  622. {
  623. // wrap input buffer
  624. Mat img(height, width, CV_8UC3, (unsigned char*)pixels, step);
  625. Mat result;
  626. GaussianBlur(img, result, Size(7, 7), 1.5, 1.5);
  627. return result;
  628. }
  629. @endcode
  630. -# Quickly initialize small matrices and/or get a super-fast element access.
  631. @code
  632. double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}};
  633. Mat M = Mat(3, 3, CV_64F, m).inv();
  634. @endcode
  635. .
  636. Partial yet very common cases of this *user-allocated data* case are conversions from CvMat and
  637. IplImage to Mat. For this purpose, there is function cv::cvarrToMat taking pointers to CvMat or
  638. IplImage and the optional flag indicating whether to copy the data or not.
  639. @snippet samples/cpp/image.cpp iplimage
  640. - Use MATLAB-style array initializers, zeros(), ones(), eye(), for example:
  641. @code
  642. // create a double-precision identity matrix and add it to M.
  643. M += Mat::eye(M.rows, M.cols, CV_64F);
  644. @endcode
  645. - Use a comma-separated initializer:
  646. @code
  647. // create a 3x3 double-precision identity matrix
  648. Mat M = (Mat_<double>(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);
  649. @endcode
  650. With this approach, you first call a constructor of the Mat class with the proper parameters, and
  651. then you just put `<< operator` followed by comma-separated values that can be constants,
  652. variables, expressions, and so on. Also, note the extra parentheses required to avoid compilation
  653. errors.
  654. Once the array is created, it is automatically managed via a reference-counting mechanism. If the
  655. array header is built on top of user-allocated data, you should handle the data by yourself. The
  656. array data is deallocated when no one points to it. If you want to release the data pointed by a
  657. array header before the array destructor is called, use Mat::release().
  658. The next important thing to learn about the array class is element access. This manual already
  659. described how to compute an address of each array element. Normally, you are not required to use the
  660. formula directly in the code. If you know the array element type (which can be retrieved using the
  661. method Mat::type() ), you can access the element \f$M_{ij}\f$ of a 2-dimensional array as:
  662. @code
  663. M.at<double>(i,j) += 1.f;
  664. @endcode
  665. assuming that `M` is a double-precision floating-point array. There are several variants of the method
  666. at for a different number of dimensions.
  667. If you need to process a whole row of a 2D array, the most efficient way is to get the pointer to
  668. the row first, and then just use the plain C operator [] :
  669. @code
  670. // compute sum of positive matrix elements
  671. // (assuming that M is a double-precision matrix)
  672. double sum=0;
  673. for(int i = 0; i < M.rows; i++)
  674. {
  675. const double* Mi = M.ptr<double>(i);
  676. for(int j = 0; j < M.cols; j++)
  677. sum += std::max(Mi[j], 0.);
  678. }
  679. @endcode
  680. Some operations, like the one above, do not actually depend on the array shape. They just process
  681. elements of an array one by one (or elements from multiple arrays that have the same coordinates,
  682. for example, array addition). Such operations are called *element-wise*. It makes sense to check
  683. whether all the input/output arrays are continuous, namely, have no gaps at the end of each row. If
  684. yes, process them as a long single row:
  685. @code
  686. // compute the sum of positive matrix elements, optimized variant
  687. double sum=0;
  688. int cols = M.cols, rows = M.rows;
  689. if(M.isContinuous())
  690. {
  691. cols *= rows;
  692. rows = 1;
  693. }
  694. for(int i = 0; i < rows; i++)
  695. {
  696. const double* Mi = M.ptr<double>(i);
  697. for(int j = 0; j < cols; j++)
  698. sum += std::max(Mi[j], 0.);
  699. }
  700. @endcode
  701. In case of the continuous matrix, the outer loop body is executed just once. So, the overhead is
  702. smaller, which is especially noticeable in case of small matrices.
  703. Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows:
  704. @code
  705. // compute sum of positive matrix elements, iterator-based variant
  706. double sum=0;
  707. MatConstIterator_<double> it = M.begin<double>(), it_end = M.end<double>();
  708. for(; it != it_end; ++it)
  709. sum += std::max(*it, 0.);
  710. @endcode
  711. The matrix iterators are random-access iterators, so they can be passed to any STL algorithm,
  712. including std::sort().
  713. @note Matrix Expressions and arithmetic see MatExpr
  714. */
  715. class CV_EXPORTS Mat
  716. {
  717. public:
  718. /**
  719. These are various constructors that form a matrix. As noted in the AutomaticAllocation, often
  720. the default constructor is enough, and the proper matrix will be allocated by an OpenCV function.
  721. The constructed matrix can further be assigned to another matrix or matrix expression or can be
  722. allocated with Mat::create . In the former case, the old content is de-referenced.
  723. */
  724. Mat() CV_NOEXCEPT;
  725. /** @overload
  726. @param rows Number of rows in a 2D array.
  727. @param cols Number of columns in a 2D array.
  728. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
  729. CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
  730. */
  731. Mat(int rows, int cols, int type);
  732. /** @overload
  733. @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the
  734. number of columns go in the reverse order.
  735. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
  736. CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
  737. */
  738. Mat(Size size, int type);
  739. /** @overload
  740. @param rows Number of rows in a 2D array.
  741. @param cols Number of columns in a 2D array.
  742. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
  743. CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
  744. @param s An optional value to initialize each matrix element with. To set all the matrix elements to
  745. the particular value after the construction, use the assignment operator
  746. Mat::operator=(const Scalar& value) .
  747. */
  748. Mat(int rows, int cols, int type, const Scalar& s);
  749. /** @overload
  750. @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the
  751. number of columns go in the reverse order.
  752. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
  753. CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
  754. @param s An optional value to initialize each matrix element with. To set all the matrix elements to
  755. the particular value after the construction, use the assignment operator
  756. Mat::operator=(const Scalar& value) .
  757. */
  758. Mat(Size size, int type, const Scalar& s);
  759. /** @overload
  760. @param ndims Array dimensionality.
  761. @param sizes Array of integers specifying an n-dimensional array shape.
  762. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
  763. CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
  764. */
  765. Mat(int ndims, const int* sizes, int type);
  766. /** @overload
  767. @param sizes Array of integers specifying an n-dimensional array shape.
  768. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
  769. CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
  770. */
  771. Mat(const std::vector<int>& sizes, int type);
  772. /** @overload
  773. @param ndims Array dimensionality.
  774. @param sizes Array of integers specifying an n-dimensional array shape.
  775. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
  776. CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
  777. @param s An optional value to initialize each matrix element with. To set all the matrix elements to
  778. the particular value after the construction, use the assignment operator
  779. Mat::operator=(const Scalar& value) .
  780. */
  781. Mat(int ndims, const int* sizes, int type, const Scalar& s);
  782. /** @overload
  783. @param sizes Array of integers specifying an n-dimensional array shape.
  784. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
  785. CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
  786. @param s An optional value to initialize each matrix element with. To set all the matrix elements to
  787. the particular value after the construction, use the assignment operator
  788. Mat::operator=(const Scalar& value) .
  789. */
  790. Mat(const std::vector<int>& sizes, int type, const Scalar& s);
  791. /** @overload
  792. @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied
  793. by these constructors. Instead, the header pointing to m data or its sub-array is constructed and
  794. associated with it. The reference counter, if any, is incremented. So, when you modify the matrix
  795. formed using such a constructor, you also modify the corresponding elements of m . If you want to
  796. have an independent copy of the sub-array, use Mat::clone() .
  797. */
  798. Mat(const Mat& m);
  799. /** @overload
  800. @param rows Number of rows in a 2D array.
  801. @param cols Number of columns in a 2D array.
  802. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
  803. CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
  804. @param data Pointer to the user data. Matrix constructors that take data and step parameters do not
  805. allocate matrix data. Instead, they just initialize the matrix header that points to the specified
  806. data, which means that no data is copied. This operation is very efficient and can be used to
  807. process external data using OpenCV functions. The external data is not automatically deallocated, so
  808. you should take care of it.
  809. @param step Number of bytes each matrix row occupies. The value should include the padding bytes at
  810. the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed
  811. and the actual step is calculated as cols*elemSize(). See Mat::elemSize.
  812. */
  813. Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP);
  814. /** @overload
  815. @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the
  816. number of columns go in the reverse order.
  817. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
  818. CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
  819. @param data Pointer to the user data. Matrix constructors that take data and step parameters do not
  820. allocate matrix data. Instead, they just initialize the matrix header that points to the specified
  821. data, which means that no data is copied. This operation is very efficient and can be used to
  822. process external data using OpenCV functions. The external data is not automatically deallocated, so
  823. you should take care of it.
  824. @param step Number of bytes each matrix row occupies. The value should include the padding bytes at
  825. the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed
  826. and the actual step is calculated as cols*elemSize(). See Mat::elemSize.
  827. */
  828. Mat(Size size, int type, void* data, size_t step=AUTO_STEP);
  829. /** @overload
  830. @param ndims Array dimensionality.
  831. @param sizes Array of integers specifying an n-dimensional array shape.
  832. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
  833. CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
  834. @param data Pointer to the user data. Matrix constructors that take data and step parameters do not
  835. allocate matrix data. Instead, they just initialize the matrix header that points to the specified
  836. data, which means that no data is copied. This operation is very efficient and can be used to
  837. process external data using OpenCV functions. The external data is not automatically deallocated, so
  838. you should take care of it.
  839. @param steps Array of ndims-1 steps in case of a multi-dimensional array (the last step is always
  840. set to the element size). If not specified, the matrix is assumed to be continuous.
  841. */
  842. Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0);
  843. /** @overload
  844. @param sizes Array of integers specifying an n-dimensional array shape.
  845. @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or
  846. CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices.
  847. @param data Pointer to the user data. Matrix constructors that take data and step parameters do not
  848. allocate matrix data. Instead, they just initialize the matrix header that points to the specified
  849. data, which means that no data is copied. This operation is very efficient and can be used to
  850. process external data using OpenCV functions. The external data is not automatically deallocated, so
  851. you should take care of it.
  852. @param steps Array of ndims-1 steps in case of a multi-dimensional array (the last step is always
  853. set to the element size). If not specified, the matrix is assumed to be continuous.
  854. */
  855. Mat(const std::vector<int>& sizes, int type, void* data, const size_t* steps=0);
  856. /** @overload
  857. @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied
  858. by these constructors. Instead, the header pointing to m data or its sub-array is constructed and
  859. associated with it. The reference counter, if any, is incremented. So, when you modify the matrix
  860. formed using such a constructor, you also modify the corresponding elements of m . If you want to
  861. have an independent copy of the sub-array, use Mat::clone() .
  862. @param rowRange Range of the m rows to take. As usual, the range start is inclusive and the range
  863. end is exclusive. Use Range::all() to take all the rows.
  864. @param colRange Range of the m columns to take. Use Range::all() to take all the columns.
  865. */
  866. Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all());
  867. /** @overload
  868. @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied
  869. by these constructors. Instead, the header pointing to m data or its sub-array is constructed and
  870. associated with it. The reference counter, if any, is incremented. So, when you modify the matrix
  871. formed using such a constructor, you also modify the corresponding elements of m . If you want to
  872. have an independent copy of the sub-array, use Mat::clone() .
  873. @param roi Region of interest.
  874. */
  875. Mat(const Mat& m, const Rect& roi);
  876. /** @overload
  877. @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied
  878. by these constructors. Instead, the header pointing to m data or its sub-array is constructed and
  879. associated with it. The reference counter, if any, is incremented. So, when you modify the matrix
  880. formed using such a constructor, you also modify the corresponding elements of m . If you want to
  881. have an independent copy of the sub-array, use Mat::clone() .
  882. @param ranges Array of selected ranges of m along each dimensionality.
  883. */
  884. Mat(const Mat& m, const Range* ranges);
  885. /** @overload
  886. @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied
  887. by these constructors. Instead, the header pointing to m data or its sub-array is constructed and
  888. associated with it. The reference counter, if any, is incremented. So, when you modify the matrix
  889. formed using such a constructor, you also modify the corresponding elements of m . If you want to
  890. have an independent copy of the sub-array, use Mat::clone() .
  891. @param ranges Array of selected ranges of m along each dimensionality.
  892. */
  893. Mat(const Mat& m, const std::vector<Range>& ranges);
  894. /** @overload
  895. @param vec STL vector whose elements form the matrix. The matrix has a single column and the number
  896. of rows equal to the number of vector elements. Type of the matrix matches the type of vector
  897. elements. The constructor can handle arbitrary types, for which there is a properly declared
  898. DataType . This means that the vector elements must be primitive numbers or uni-type numerical
  899. tuples of numbers. Mixed-type structures are not supported. The corresponding constructor is
  900. explicit. Since STL vectors are not automatically converted to Mat instances, you should write
  901. Mat(vec) explicitly. Unless you copy the data into the matrix ( copyData=true ), no new elements
  902. will be added to the vector because it can potentially yield vector data reallocation, and, thus,
  903. the matrix data pointer will be invalid.
  904. @param copyData Flag to specify whether the underlying data of the STL vector should be copied
  905. to (true) or shared with (false) the newly constructed matrix. When the data is copied, the
  906. allocated buffer is managed using Mat reference counting mechanism. While the data is shared,
  907. the reference counter is NULL, and you should not deallocate the data until the matrix is not
  908. destructed.
  909. */
  910. template<typename _Tp> explicit Mat(const std::vector<_Tp>& vec, bool copyData=false);
  911. #ifdef CV_CXX11
  912. /** @overload
  913. */
  914. template<typename _Tp, typename = typename std::enable_if<std::is_arithmetic<_Tp>::value>::type>
  915. explicit Mat(const std::initializer_list<_Tp> list);
  916. /** @overload
  917. */
  918. template<typename _Tp> explicit Mat(const std::initializer_list<int> sizes, const std::initializer_list<_Tp> list);
  919. #endif
  920. #ifdef CV_CXX_STD_ARRAY
  921. /** @overload
  922. */
  923. template<typename _Tp, size_t _Nm> explicit Mat(const std::array<_Tp, _Nm>& arr, bool copyData=false);
  924. #endif
  925. /** @overload
  926. */
  927. template<typename _Tp, int n> explicit Mat(const Vec<_Tp, n>& vec, bool copyData=true);
  928. /** @overload
  929. */
  930. template<typename _Tp, int m, int n> explicit Mat(const Matx<_Tp, m, n>& mtx, bool copyData=true);
  931. /** @overload
  932. */
  933. template<typename _Tp> explicit Mat(const Point_<_Tp>& pt, bool copyData=true);
  934. /** @overload
  935. */
  936. template<typename _Tp> explicit Mat(const Point3_<_Tp>& pt, bool copyData=true);
  937. /** @overload
  938. */
  939. template<typename _Tp> explicit Mat(const MatCommaInitializer_<_Tp>& commaInitializer);
  940. //! download data from GpuMat
  941. explicit Mat(const cuda::GpuMat& m);
  942. //! destructor - calls release()
  943. ~Mat();
  944. /** @brief assignment operators
  945. These are available assignment operators. Since they all are very different, make sure to read the
  946. operator parameters description.
  947. @param m Assigned, right-hand-side matrix. Matrix assignment is an O(1) operation. This means that
  948. no data is copied but the data is shared and the reference counter, if any, is incremented. Before
  949. assigning new data, the old data is de-referenced via Mat::release .
  950. */
  951. Mat& operator = (const Mat& m);
  952. /** @overload
  953. @param expr Assigned matrix expression object. As opposite to the first form of the assignment
  954. operation, the second form can reuse already allocated matrix if it has the right size and type to
  955. fit the matrix expression result. It is automatically handled by the real function that the matrix
  956. expressions is expanded to. For example, C=A+B is expanded to add(A, B, C), and add takes care of
  957. automatic C reallocation.
  958. */
  959. Mat& operator = (const MatExpr& expr);
  960. //! retrieve UMat from Mat
  961. UMat getUMat(int accessFlags, UMatUsageFlags usageFlags = USAGE_DEFAULT) const;
  962. /** @brief Creates a matrix header for the specified matrix row.
  963. The method makes a new header for the specified matrix row and returns it. This is an O(1)
  964. operation, regardless of the matrix size. The underlying data of the new matrix is shared with the
  965. original matrix. Here is the example of one of the classical basic matrix processing operations,
  966. axpy, used by LU and many other algorithms:
  967. @code
  968. inline void matrix_axpy(Mat& A, int i, int j, double alpha)
  969. {
  970. A.row(i) += A.row(j)*alpha;
  971. }
  972. @endcode
  973. @note In the current implementation, the following code does not work as expected:
  974. @code
  975. Mat A;
  976. ...
  977. A.row(i) = A.row(j); // will not work
  978. @endcode
  979. This happens because A.row(i) forms a temporary header that is further assigned to another header.
  980. Remember that each of these operations is O(1), that is, no data is copied. Thus, the above
  981. assignment is not true if you may have expected the j-th row to be copied to the i-th row. To
  982. achieve that, you should either turn this simple assignment into an expression or use the
  983. Mat::copyTo method:
  984. @code
  985. Mat A;
  986. ...
  987. // works, but looks a bit obscure.
  988. A.row(i) = A.row(j) + 0;
  989. // this is a bit longer, but the recommended method.
  990. A.row(j).copyTo(A.row(i));
  991. @endcode
  992. @param y A 0-based row index.
  993. */
  994. Mat row(int y) const;
  995. /** @brief Creates a matrix header for the specified matrix column.
  996. The method makes a new header for the specified matrix column and returns it. This is an O(1)
  997. operation, regardless of the matrix size. The underlying data of the new matrix is shared with the
  998. original matrix. See also the Mat::row description.
  999. @param x A 0-based column index.
  1000. */
  1001. Mat col(int x) const;
  1002. /** @brief Creates a matrix header for the specified row span.
  1003. The method makes a new header for the specified row span of the matrix. Similarly to Mat::row and
  1004. Mat::col , this is an O(1) operation.
  1005. @param startrow An inclusive 0-based start index of the row span.
  1006. @param endrow An exclusive 0-based ending index of the row span.
  1007. */
  1008. Mat rowRange(int startrow, int endrow) const;
  1009. /** @overload
  1010. @param r Range structure containing both the start and the end indices.
  1011. */
  1012. Mat rowRange(const Range& r) const;
  1013. /** @brief Creates a matrix header for the specified column span.
  1014. The method makes a new header for the specified column span of the matrix. Similarly to Mat::row and
  1015. Mat::col , this is an O(1) operation.
  1016. @param startcol An inclusive 0-based start index of the column span.
  1017. @param endcol An exclusive 0-based ending index of the column span.
  1018. */
  1019. Mat colRange(int startcol, int endcol) const;
  1020. /** @overload
  1021. @param r Range structure containing both the start and the end indices.
  1022. */
  1023. Mat colRange(const Range& r) const;
  1024. /** @brief Extracts a diagonal from a matrix
  1025. The method makes a new header for the specified matrix diagonal. The new matrix is represented as a
  1026. single-column matrix. Similarly to Mat::row and Mat::col, this is an O(1) operation.
  1027. @param d index of the diagonal, with the following values:
  1028. - `d=0` is the main diagonal.
  1029. - `d<0` is a diagonal from the lower half. For example, d=-1 means the diagonal is set
  1030. immediately below the main one.
  1031. - `d>0` is a diagonal from the upper half. For example, d=1 means the diagonal is set
  1032. immediately above the main one.
  1033. For example:
  1034. @code
  1035. Mat m = (Mat_<int>(3,3) <<
  1036. 1,2,3,
  1037. 4,5,6,
  1038. 7,8,9);
  1039. Mat d0 = m.diag(0);
  1040. Mat d1 = m.diag(1);
  1041. Mat d_1 = m.diag(-1);
  1042. @endcode
  1043. The resulting matrices are
  1044. @code
  1045. d0 =
  1046. [1;
  1047. 5;
  1048. 9]
  1049. d1 =
  1050. [2;
  1051. 6]
  1052. d_1 =
  1053. [4;
  1054. 8]
  1055. @endcode
  1056. */
  1057. Mat diag(int d=0) const;
  1058. /** @brief creates a diagonal matrix
  1059. The method creates a square diagonal matrix from specified main diagonal.
  1060. @param d One-dimensional matrix that represents the main diagonal.
  1061. */
  1062. static Mat diag(const Mat& d);
  1063. /** @brief Creates a full copy of the array and the underlying data.
  1064. The method creates a full copy of the array. The original step[] is not taken into account. So, the
  1065. array copy is a continuous array occupying total()*elemSize() bytes.
  1066. */
  1067. Mat clone() const CV_NODISCARD;
  1068. /** @brief Copies the matrix to another one.
  1069. The method copies the matrix data to another matrix. Before copying the data, the method invokes :
  1070. @code
  1071. m.create(this->size(), this->type());
  1072. @endcode
  1073. so that the destination matrix is reallocated if needed. While m.copyTo(m); works flawlessly, the
  1074. function does not handle the case of a partial overlap between the source and the destination
  1075. matrices.
  1076. When the operation mask is specified, if the Mat::create call shown above reallocates the matrix,
  1077. the newly allocated matrix is initialized with all zeros before copying the data.
  1078. @param m Destination matrix. If it does not have a proper size or type before the operation, it is
  1079. reallocated.
  1080. */
  1081. void copyTo( OutputArray m ) const;
  1082. /** @overload
  1083. @param m Destination matrix. If it does not have a proper size or type before the operation, it is
  1084. reallocated.
  1085. @param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix
  1086. elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels.
  1087. */
  1088. void copyTo( OutputArray m, InputArray mask ) const;
  1089. /** @brief Converts an array to another data type with optional scaling.
  1090. The method converts source pixel values to the target data type. saturate_cast\<\> is applied at
  1091. the end to avoid possible overflows:
  1092. \f[m(x,y) = saturate \_ cast<rType>( \alpha (*this)(x,y) + \beta )\f]
  1093. @param m output matrix; if it does not have a proper size or type before the operation, it is
  1094. reallocated.
  1095. @param rtype desired output matrix type or, rather, the depth since the number of channels are the
  1096. same as the input has; if rtype is negative, the output matrix will have the same type as the input.
  1097. @param alpha optional scale factor.
  1098. @param beta optional delta added to the scaled values.
  1099. */
  1100. void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const;
  1101. /** @brief Provides a functional form of convertTo.
  1102. This is an internally used method called by the @ref MatrixExpressions engine.
  1103. @param m Destination array.
  1104. @param type Desired destination array depth (or -1 if it should be the same as the source type).
  1105. */
  1106. void assignTo( Mat& m, int type=-1 ) const;
  1107. /** @brief Sets all or some of the array elements to the specified value.
  1108. @param s Assigned scalar converted to the actual array type.
  1109. */
  1110. Mat& operator = (const Scalar& s);
  1111. /** @brief Sets all or some of the array elements to the specified value.
  1112. This is an advanced variant of the Mat::operator=(const Scalar& s) operator.
  1113. @param value Assigned scalar converted to the actual array type.
  1114. @param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix
  1115. elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels
  1116. */
  1117. Mat& setTo(InputArray value, InputArray mask=noArray());
  1118. /** @brief Changes the shape and/or the number of channels of a 2D matrix without copying the data.
  1119. The method makes a new matrix header for \*this elements. The new matrix may have a different size
  1120. and/or different number of channels. Any combination is possible if:
  1121. - No extra elements are included into the new matrix and no elements are excluded. Consequently,
  1122. the product rows\*cols\*channels() must stay the same after the transformation.
  1123. - No data is copied. That is, this is an O(1) operation. Consequently, if you change the number of
  1124. rows, or the operation changes the indices of elements row in some other way, the matrix must be
  1125. continuous. See Mat::isContinuous .
  1126. For example, if there is a set of 3D points stored as an STL vector, and you want to represent the
  1127. points as a 3xN matrix, do the following:
  1128. @code
  1129. std::vector<Point3f> vec;
  1130. ...
  1131. Mat pointMat = Mat(vec). // convert vector to Mat, O(1) operation
  1132. reshape(1). // make Nx3 1-channel matrix out of Nx1 3-channel.
  1133. // Also, an O(1) operation
  1134. t(); // finally, transpose the Nx3 matrix.
  1135. // This involves copying all the elements
  1136. @endcode
  1137. @param cn New number of channels. If the parameter is 0, the number of channels remains the same.
  1138. @param rows New number of rows. If the parameter is 0, the number of rows remains the same.
  1139. */
  1140. Mat reshape(int cn, int rows=0) const;
  1141. /** @overload */
  1142. Mat reshape(int cn, int newndims, const int* newsz) const;
  1143. /** @overload */
  1144. Mat reshape(int cn, const std::vector<int>& newshape) const;
  1145. /** @brief Transposes a matrix.
  1146. The method performs matrix transposition by means of matrix expressions. It does not perform the
  1147. actual transposition but returns a temporary matrix transposition object that can be further used as
  1148. a part of more complex matrix expressions or can be assigned to a matrix:
  1149. @code
  1150. Mat A1 = A + Mat::eye(A.size(), A.type())*lambda;
  1151. Mat C = A1.t()*A1; // compute (A + lambda*I)^t * (A + lamda*I)
  1152. @endcode
  1153. */
  1154. MatExpr t() const;
  1155. /** @brief Inverses a matrix.
  1156. The method performs a matrix inversion by means of matrix expressions. This means that a temporary
  1157. matrix inversion object is returned by the method and can be used further as a part of more complex
  1158. matrix expressions or can be assigned to a matrix.
  1159. @param method Matrix inversion method. One of cv::DecompTypes
  1160. */
  1161. MatExpr inv(int method=DECOMP_LU) const;
  1162. /** @brief Performs an element-wise multiplication or division of the two matrices.
  1163. The method returns a temporary object encoding per-element array multiplication, with optional
  1164. scale. Note that this is not a matrix multiplication that corresponds to a simpler "\*" operator.
  1165. Example:
  1166. @code
  1167. Mat C = A.mul(5/B); // equivalent to divide(A, B, C, 5)
  1168. @endcode
  1169. @param m Another array of the same type and the same size as \*this, or a matrix expression.
  1170. @param scale Optional scale factor.
  1171. */
  1172. MatExpr mul(InputArray m, double scale=1) const;
  1173. /** @brief Computes a cross-product of two 3-element vectors.
  1174. The method computes a cross-product of two 3-element vectors. The vectors must be 3-element
  1175. floating-point vectors of the same shape and size. The result is another 3-element vector of the
  1176. same shape and type as operands.
  1177. @param m Another cross-product operand.
  1178. */
  1179. Mat cross(InputArray m) const;
  1180. /** @brief Computes a dot-product of two vectors.
  1181. The method computes a dot-product of two matrices. If the matrices are not single-column or
  1182. single-row vectors, the top-to-bottom left-to-right scan ordering is used to treat them as 1D
  1183. vectors. The vectors must have the same size and type. If the matrices have more than one channel,
  1184. the dot products from all the channels are summed together.
  1185. @param m another dot-product operand.
  1186. */
  1187. double dot(InputArray m) const;
  1188. /** @brief Returns a zero array of the specified size and type.
  1189. The method returns a Matlab-style zero array initializer. It can be used to quickly form a constant
  1190. array as a function parameter, part of a matrix expression, or as a matrix initializer:
  1191. @code
  1192. Mat A;
  1193. A = Mat::zeros(3, 3, CV_32F);
  1194. @endcode
  1195. In the example above, a new matrix is allocated only if A is not a 3x3 floating-point matrix.
  1196. Otherwise, the existing matrix A is filled with zeros.
  1197. @param rows Number of rows.
  1198. @param cols Number of columns.
  1199. @param type Created matrix type.
  1200. */
  1201. static MatExpr zeros(int rows, int cols, int type);
  1202. /** @overload
  1203. @param size Alternative to the matrix size specification Size(cols, rows) .
  1204. @param type Created matrix type.
  1205. */
  1206. static MatExpr zeros(Size size, int type);
  1207. /** @overload
  1208. @param ndims Array dimensionality.
  1209. @param sz Array of integers specifying the array shape.
  1210. @param type Created matrix type.
  1211. */
  1212. static MatExpr zeros(int ndims, const int* sz, int type);
  1213. /** @brief Returns an array of all 1's of the specified size and type.
  1214. The method returns a Matlab-style 1's array initializer, similarly to Mat::zeros. Note that using
  1215. this method you can initialize an array with an arbitrary value, using the following Matlab idiom:
  1216. @code
  1217. Mat A = Mat::ones(100, 100, CV_8U)*3; // make 100x100 matrix filled with 3.
  1218. @endcode
  1219. The above operation does not form a 100x100 matrix of 1's and then multiply it by 3. Instead, it
  1220. just remembers the scale factor (3 in this case) and use it when actually invoking the matrix
  1221. initializer.
  1222. @note In case of multi-channels type, only the first channel will be initialized with 1's, the
  1223. others will be set to 0's.
  1224. @param rows Number of rows.
  1225. @param cols Number of columns.
  1226. @param type Created matrix type.
  1227. */
  1228. static MatExpr ones(int rows, int cols, int type);
  1229. /** @overload
  1230. @param size Alternative to the matrix size specification Size(cols, rows) .
  1231. @param type Created matrix type.
  1232. */
  1233. static MatExpr ones(Size size, int type);
  1234. /** @overload
  1235. @param ndims Array dimensionality.
  1236. @param sz Array of integers specifying the array shape.
  1237. @param type Created matrix type.
  1238. */
  1239. static MatExpr ones(int ndims, const int* sz, int type);
  1240. /** @brief Returns an identity matrix of the specified size and type.
  1241. The method returns a Matlab-style identity matrix initializer, similarly to Mat::zeros. Similarly to
  1242. Mat::ones, you can use a scale operation to create a scaled identity matrix efficiently:
  1243. @code
  1244. // make a 4x4 diagonal matrix with 0.1's on the diagonal.
  1245. Mat A = Mat::eye(4, 4, CV_32F)*0.1;
  1246. @endcode
  1247. @note In case of multi-channels type, identity matrix will be initialized only for the first channel,
  1248. the others will be set to 0's
  1249. @param rows Number of rows.
  1250. @param cols Number of columns.
  1251. @param type Created matrix type.
  1252. */
  1253. static MatExpr eye(int rows, int cols, int type);
  1254. /** @overload
  1255. @param size Alternative matrix size specification as Size(cols, rows) .
  1256. @param type Created matrix type.
  1257. */
  1258. static MatExpr eye(Size size, int type);
  1259. /** @brief Allocates new array data if needed.
  1260. This is one of the key Mat methods. Most new-style OpenCV functions and methods that produce arrays
  1261. call this method for each output array. The method uses the following algorithm:
  1262. -# If the current array shape and the type match the new ones, return immediately. Otherwise,
  1263. de-reference the previous data by calling Mat::release.
  1264. -# Initialize the new header.
  1265. -# Allocate the new data of total()\*elemSize() bytes.
  1266. -# Allocate the new, associated with the data, reference counter and set it to 1.
  1267. Such a scheme makes the memory management robust and efficient at the same time and helps avoid
  1268. extra typing for you. This means that usually there is no need to explicitly allocate output arrays.
  1269. That is, instead of writing:
  1270. @code
  1271. Mat color;
  1272. ...
  1273. Mat gray(color.rows, color.cols, color.depth());
  1274. cvtColor(color, gray, COLOR_BGR2GRAY);
  1275. @endcode
  1276. you can simply write:
  1277. @code
  1278. Mat color;
  1279. ...
  1280. Mat gray;
  1281. cvtColor(color, gray, COLOR_BGR2GRAY);
  1282. @endcode
  1283. because cvtColor, as well as the most of OpenCV functions, calls Mat::create() for the output array
  1284. internally.
  1285. @param rows New number of rows.
  1286. @param cols New number of columns.
  1287. @param type New matrix type.
  1288. */
  1289. void create(int rows, int cols, int type);
  1290. /** @overload
  1291. @param size Alternative new matrix size specification: Size(cols, rows)
  1292. @param type New matrix type.
  1293. */
  1294. void create(Size size, int type);
  1295. /** @overload
  1296. @param ndims New array dimensionality.
  1297. @param sizes Array of integers specifying a new array shape.
  1298. @param type New matrix type.
  1299. */
  1300. void create(int ndims, const int* sizes, int type);
  1301. /** @overload
  1302. @param sizes Array of integers specifying a new array shape.
  1303. @param type New matrix type.
  1304. */
  1305. void create(const std::vector<int>& sizes, int type);
  1306. /** @brief Increments the reference counter.
  1307. The method increments the reference counter associated with the matrix data. If the matrix header
  1308. points to an external data set (see Mat::Mat ), the reference counter is NULL, and the method has no
  1309. effect in this case. Normally, to avoid memory leaks, the method should not be called explicitly. It
  1310. is called implicitly by the matrix assignment operator. The reference counter increment is an atomic
  1311. operation on the platforms that support it. Thus, it is safe to operate on the same matrices
  1312. asynchronously in different threads.
  1313. */
  1314. void addref();
  1315. /** @brief Decrements the reference counter and deallocates the matrix if needed.
  1316. The method decrements the reference counter associated with the matrix data. When the reference
  1317. counter reaches 0, the matrix data is deallocated and the data and the reference counter pointers
  1318. are set to NULL's. If the matrix header points to an external data set (see Mat::Mat ), the
  1319. reference counter is NULL, and the method has no effect in this case.
  1320. This method can be called manually to force the matrix data deallocation. But since this method is
  1321. automatically called in the destructor, or by any other method that changes the data pointer, it is
  1322. usually not needed. The reference counter decrement and check for 0 is an atomic operation on the
  1323. platforms that support it. Thus, it is safe to operate on the same matrices asynchronously in
  1324. different threads.
  1325. */
  1326. void release();
  1327. //! internal use function, consider to use 'release' method instead; deallocates the matrix data
  1328. void deallocate();
  1329. //! internal use function; properly re-allocates _size, _step arrays
  1330. void copySize(const Mat& m);
  1331. /** @brief Reserves space for the certain number of rows.
  1332. The method reserves space for sz rows. If the matrix already has enough space to store sz rows,
  1333. nothing happens. If the matrix is reallocated, the first Mat::rows rows are preserved. The method
  1334. emulates the corresponding method of the STL vector class.
  1335. @param sz Number of rows.
  1336. */
  1337. void reserve(size_t sz);
  1338. /** @brief Reserves space for the certain number of bytes.
  1339. The method reserves space for sz bytes. If the matrix already has enough space to store sz bytes,
  1340. nothing happens. If matrix has to be reallocated its previous content could be lost.
  1341. @param sz Number of bytes.
  1342. */
  1343. void reserveBuffer(size_t sz);
  1344. /** @brief Changes the number of matrix rows.
  1345. The methods change the number of matrix rows. If the matrix is reallocated, the first
  1346. min(Mat::rows, sz) rows are preserved. The methods emulate the corresponding methods of the STL
  1347. vector class.
  1348. @param sz New number of rows.
  1349. */
  1350. void resize(size_t sz);
  1351. /** @overload
  1352. @param sz New number of rows.
  1353. @param s Value assigned to the newly added elements.
  1354. */
  1355. void resize(size_t sz, const Scalar& s);
  1356. //! internal function
  1357. void push_back_(const void* elem);
  1358. /** @brief Adds elements to the bottom of the matrix.
  1359. The methods add one or more elements to the bottom of the matrix. They emulate the corresponding
  1360. method of the STL vector class. When elem is Mat , its type and the number of columns must be the
  1361. same as in the container matrix.
  1362. @param elem Added element(s).
  1363. */
  1364. template<typename _Tp> void push_back(const _Tp& elem);
  1365. /** @overload
  1366. @param elem Added element(s).
  1367. */
  1368. template<typename _Tp> void push_back(const Mat_<_Tp>& elem);
  1369. /** @overload
  1370. @param elem Added element(s).
  1371. */
  1372. template<typename _Tp> void push_back(const std::vector<_Tp>& elem);
  1373. /** @overload
  1374. @param m Added line(s).
  1375. */
  1376. void push_back(const Mat& m);
  1377. /** @brief Removes elements from the bottom of the matrix.
  1378. The method removes one or more rows from the bottom of the matrix.
  1379. @param nelems Number of removed rows. If it is greater than the total number of rows, an exception
  1380. is thrown.
  1381. */
  1382. void pop_back(size_t nelems=1);
  1383. /** @brief Locates the matrix header within a parent matrix.
  1384. After you extracted a submatrix from a matrix using Mat::row, Mat::col, Mat::rowRange,
  1385. Mat::colRange, and others, the resultant submatrix points just to the part of the original big
  1386. matrix. However, each submatrix contains information (represented by datastart and dataend
  1387. fields) that helps reconstruct the original matrix size and the position of the extracted
  1388. submatrix within the original matrix. The method locateROI does exactly that.
  1389. @param wholeSize Output parameter that contains the size of the whole matrix containing *this*
  1390. as a part.
  1391. @param ofs Output parameter that contains an offset of *this* inside the whole matrix.
  1392. */
  1393. void locateROI( Size& wholeSize, Point& ofs ) const;
  1394. /** @brief Adjusts a submatrix size and position within the parent matrix.
  1395. The method is complimentary to Mat::locateROI . The typical use of these functions is to determine
  1396. the submatrix position within the parent matrix and then shift the position somehow. Typically, it
  1397. can be required for filtering operations when pixels outside of the ROI should be taken into
  1398. account. When all the method parameters are positive, the ROI needs to grow in all directions by the
  1399. specified amount, for example:
  1400. @code
  1401. A.adjustROI(2, 2, 2, 2);
  1402. @endcode
  1403. In this example, the matrix size is increased by 4 elements in each direction. The matrix is shifted
  1404. by 2 elements to the left and 2 elements up, which brings in all the necessary pixels for the
  1405. filtering with the 5x5 kernel.
  1406. adjustROI forces the adjusted ROI to be inside of the parent matrix that is boundaries of the
  1407. adjusted ROI are constrained by boundaries of the parent matrix. For example, if the submatrix A is
  1408. located in the first row of a parent matrix and you called A.adjustROI(2, 2, 2, 2) then A will not
  1409. be increased in the upward direction.
  1410. The function is used internally by the OpenCV filtering functions, like filter2D , morphological
  1411. operations, and so on.
  1412. @param dtop Shift of the top submatrix boundary upwards.
  1413. @param dbottom Shift of the bottom submatrix boundary downwards.
  1414. @param dleft Shift of the left submatrix boundary to the left.
  1415. @param dright Shift of the right submatrix boundary to the right.
  1416. @sa copyMakeBorder
  1417. */
  1418. Mat& adjustROI( int dtop, int dbottom, int dleft, int dright );
  1419. /** @brief Extracts a rectangular submatrix.
  1420. The operators make a new header for the specified sub-array of \*this . They are the most
  1421. generalized forms of Mat::row, Mat::col, Mat::rowRange, and Mat::colRange . For example,
  1422. `A(Range(0, 10), Range::all())` is equivalent to `A.rowRange(0, 10)`. Similarly to all of the above,
  1423. the operators are O(1) operations, that is, no matrix data is copied.
  1424. @param rowRange Start and end row of the extracted submatrix. The upper boundary is not included. To
  1425. select all the rows, use Range::all().
  1426. @param colRange Start and end column of the extracted submatrix. The upper boundary is not included.
  1427. To select all the columns, use Range::all().
  1428. */
  1429. Mat operator()( Range rowRange, Range colRange ) const;
  1430. /** @overload
  1431. @param roi Extracted submatrix specified as a rectangle.
  1432. */
  1433. Mat operator()( const Rect& roi ) const;
  1434. /** @overload
  1435. @param ranges Array of selected ranges along each array dimension.
  1436. */
  1437. Mat operator()( const Range* ranges ) const;
  1438. /** @overload
  1439. @param ranges Array of selected ranges along each array dimension.
  1440. */
  1441. Mat operator()(const std::vector<Range>& ranges) const;
  1442. // //! converts header to CvMat; no data is copied
  1443. // operator CvMat() const;
  1444. // //! converts header to CvMatND; no data is copied
  1445. // operator CvMatND() const;
  1446. // //! converts header to IplImage; no data is copied
  1447. // operator IplImage() const;
  1448. template<typename _Tp> operator std::vector<_Tp>() const;
  1449. template<typename _Tp, int n> operator Vec<_Tp, n>() const;
  1450. template<typename _Tp, int m, int n> operator Matx<_Tp, m, n>() const;
  1451. #ifdef CV_CXX_STD_ARRAY
  1452. template<typename _Tp, std::size_t _Nm> operator std::array<_Tp, _Nm>() const;
  1453. #endif
  1454. /** @brief Reports whether the matrix is continuous or not.
  1455. The method returns true if the matrix elements are stored continuously without gaps at the end of
  1456. each row. Otherwise, it returns false. Obviously, 1x1 or 1xN matrices are always continuous.
  1457. Matrices created with Mat::create are always continuous. But if you extract a part of the matrix
  1458. using Mat::col, Mat::diag, and so on, or constructed a matrix header for externally allocated data,
  1459. such matrices may no longer have this property.
  1460. The continuity flag is stored as a bit in the Mat::flags field and is computed automatically when
  1461. you construct a matrix header. Thus, the continuity check is a very fast operation, though
  1462. theoretically it could be done as follows:
  1463. @code
  1464. // alternative implementation of Mat::isContinuous()
  1465. bool myCheckMatContinuity(const Mat& m)
  1466. {
  1467. //return (m.flags & Mat::CONTINUOUS_FLAG) != 0;
  1468. return m.rows == 1 || m.step == m.cols*m.elemSize();
  1469. }
  1470. @endcode
  1471. The method is used in quite a few of OpenCV functions. The point is that element-wise operations
  1472. (such as arithmetic and logical operations, math functions, alpha blending, color space
  1473. transformations, and others) do not depend on the image geometry. Thus, if all the input and output
  1474. arrays are continuous, the functions can process them as very long single-row vectors. The example
  1475. below illustrates how an alpha-blending function can be implemented:
  1476. @code
  1477. template<typename T>
  1478. void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst)
  1479. {
  1480. const float alpha_scale = (float)std::numeric_limits<T>::max(),
  1481. inv_scale = 1.f/alpha_scale;
  1482. CV_Assert( src1.type() == src2.type() &&
  1483. src1.type() == CV_MAKETYPE(traits::Depth<T>::value, 4) &&
  1484. src1.size() == src2.size());
  1485. Size size = src1.size();
  1486. dst.create(size, src1.type());
  1487. // here is the idiom: check the arrays for continuity and,
  1488. // if this is the case,
  1489. // treat the arrays as 1D vectors
  1490. if( src1.isContinuous() && src2.isContinuous() && dst.isContinuous() )
  1491. {
  1492. size.width *= size.height;
  1493. size.height = 1;
  1494. }
  1495. size.width *= 4;
  1496. for( int i = 0; i < size.height; i++ )
  1497. {
  1498. // when the arrays are continuous,
  1499. // the outer loop is executed only once
  1500. const T* ptr1 = src1.ptr<T>(i);
  1501. const T* ptr2 = src2.ptr<T>(i);
  1502. T* dptr = dst.ptr<T>(i);
  1503. for( int j = 0; j < size.width; j += 4 )
  1504. {
  1505. float alpha = ptr1[j+3]*inv_scale, beta = ptr2[j+3]*inv_scale;
  1506. dptr[j] = saturate_cast<T>(ptr1[j]*alpha + ptr2[j]*beta);
  1507. dptr[j+1] = saturate_cast<T>(ptr1[j+1]*alpha + ptr2[j+1]*beta);
  1508. dptr[j+2] = saturate_cast<T>(ptr1[j+2]*alpha + ptr2[j+2]*beta);
  1509. dptr[j+3] = saturate_cast<T>((1 - (1-alpha)*(1-beta))*alpha_scale);
  1510. }
  1511. }
  1512. }
  1513. @endcode
  1514. This approach, while being very simple, can boost the performance of a simple element-operation by
  1515. 10-20 percents, especially if the image is rather small and the operation is quite simple.
  1516. Another OpenCV idiom in this function, a call of Mat::create for the destination array, that
  1517. allocates the destination array unless it already has the proper size and type. And while the newly
  1518. allocated arrays are always continuous, you still need to check the destination array because
  1519. Mat::create does not always allocate a new matrix.
  1520. */
  1521. bool isContinuous() const;
  1522. //! returns true if the matrix is a submatrix of another matrix
  1523. bool isSubmatrix() const;
  1524. /** @brief Returns the matrix element size in bytes.
  1525. The method returns the matrix element size in bytes. For example, if the matrix type is CV_16SC3 ,
  1526. the method returns 3\*sizeof(short) or 6.
  1527. */
  1528. size_t elemSize() const;
  1529. /** @brief Returns the size of each matrix element channel in bytes.
  1530. The method returns the matrix element channel size in bytes, that is, it ignores the number of
  1531. channels. For example, if the matrix type is CV_16SC3 , the method returns sizeof(short) or 2.
  1532. */
  1533. size_t elemSize1() const;
  1534. /** @brief Returns the type of a matrix element.
  1535. The method returns a matrix element type. This is an identifier compatible with the CvMat type
  1536. system, like CV_16SC3 or 16-bit signed 3-channel array, and so on.
  1537. */
  1538. int type() const;
  1539. /** @brief Returns the depth of a matrix element.
  1540. The method returns the identifier of the matrix element depth (the type of each individual channel).
  1541. For example, for a 16-bit signed element array, the method returns CV_16S . A complete list of
  1542. matrix types contains the following values:
  1543. - CV_8U - 8-bit unsigned integers ( 0..255 )
  1544. - CV_8S - 8-bit signed integers ( -128..127 )
  1545. - CV_16U - 16-bit unsigned integers ( 0..65535 )
  1546. - CV_16S - 16-bit signed integers ( -32768..32767 )
  1547. - CV_32S - 32-bit signed integers ( -2147483648..2147483647 )
  1548. - CV_32F - 32-bit floating-point numbers ( -FLT_MAX..FLT_MAX, INF, NAN )
  1549. - CV_64F - 64-bit floating-point numbers ( -DBL_MAX..DBL_MAX, INF, NAN )
  1550. */
  1551. int depth() const;
  1552. /** @brief Returns the number of matrix channels.
  1553. The method returns the number of matrix channels.
  1554. */
  1555. int channels() const;
  1556. /** @brief Returns a normalized step.
  1557. The method returns a matrix step divided by Mat::elemSize1() . It can be useful to quickly access an
  1558. arbitrary matrix element.
  1559. */
  1560. size_t step1(int i=0) const;
  1561. /** @brief Returns true if the array has no elements.
  1562. The method returns true if Mat::total() is 0 or if Mat::data is NULL. Because of pop_back() and
  1563. resize() methods `M.total() == 0` does not imply that `M.data == NULL`.
  1564. */
  1565. bool empty() const;
  1566. /** @brief Returns the total number of array elements.
  1567. The method returns the number of array elements (a number of pixels if the array represents an
  1568. image).
  1569. */
  1570. size_t total() const;
  1571. /** @brief Returns the total number of array elements.
  1572. The method returns the number of elements within a certain sub-array slice with startDim <= dim < endDim
  1573. */
  1574. size_t total(int startDim, int endDim=INT_MAX) const;
  1575. /**
  1576. * @param elemChannels Number of channels or number of columns the matrix should have.
  1577. * For a 2-D matrix, when the matrix has only 1 column, then it should have
  1578. * elemChannels channels; When the matrix has only 1 channel,
  1579. * then it should have elemChannels columns.
  1580. * For a 3-D matrix, it should have only one channel. Furthermore,
  1581. * if the number of planes is not one, then the number of rows
  1582. * within every plane has to be 1; if the number of rows within
  1583. * every plane is not 1, then the number of planes has to be 1.
  1584. * @param depth The depth the matrix should have. Set it to -1 when any depth is fine.
  1585. * @param requireContinuous Set it to true to require the matrix to be continuous
  1586. * @return -1 if the requirement is not satisfied.
  1587. * Otherwise, it returns the number of elements in the matrix. Note
  1588. * that an element may have multiple channels.
  1589. *
  1590. * The following code demonstrates its usage for a 2-d matrix:
  1591. * @snippet snippets/core_mat_checkVector.cpp example-2d
  1592. *
  1593. * The following code demonstrates its usage for a 3-d matrix:
  1594. * @snippet snippets/core_mat_checkVector.cpp example-3d
  1595. */
  1596. int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const;
  1597. /** @brief Returns a pointer to the specified matrix row.
  1598. The methods return `uchar*` or typed pointer to the specified matrix row. See the sample in
  1599. Mat::isContinuous to know how to use these methods.
  1600. @param i0 A 0-based row index.
  1601. */
  1602. uchar* ptr(int i0=0);
  1603. /** @overload */
  1604. const uchar* ptr(int i0=0) const;
  1605. /** @overload
  1606. @param row Index along the dimension 0
  1607. @param col Index along the dimension 1
  1608. */
  1609. uchar* ptr(int row, int col);
  1610. /** @overload
  1611. @param row Index along the dimension 0
  1612. @param col Index along the dimension 1
  1613. */
  1614. const uchar* ptr(int row, int col) const;
  1615. /** @overload */
  1616. uchar* ptr(int i0, int i1, int i2);
  1617. /** @overload */
  1618. const uchar* ptr(int i0, int i1, int i2) const;
  1619. /** @overload */
  1620. uchar* ptr(const int* idx);
  1621. /** @overload */
  1622. const uchar* ptr(const int* idx) const;
  1623. /** @overload */
  1624. template<int n> uchar* ptr(const Vec<int, n>& idx);
  1625. /** @overload */
  1626. template<int n> const uchar* ptr(const Vec<int, n>& idx) const;
  1627. /** @overload */
  1628. template<typename _Tp> _Tp* ptr(int i0=0);
  1629. /** @overload */
  1630. template<typename _Tp> const _Tp* ptr(int i0=0) const;
  1631. /** @overload
  1632. @param row Index along the dimension 0
  1633. @param col Index along the dimension 1
  1634. */
  1635. template<typename _Tp> _Tp* ptr(int row, int col);
  1636. /** @overload
  1637. @param row Index along the dimension 0
  1638. @param col Index along the dimension 1
  1639. */
  1640. template<typename _Tp> const _Tp* ptr(int row, int col) const;
  1641. /** @overload */
  1642. template<typename _Tp> _Tp* ptr(int i0, int i1, int i2);
  1643. /** @overload */
  1644. template<typename _Tp> const _Tp* ptr(int i0, int i1, int i2) const;
  1645. /** @overload */
  1646. template<typename _Tp> _Tp* ptr(const int* idx);
  1647. /** @overload */
  1648. template<typename _Tp> const _Tp* ptr(const int* idx) const;
  1649. /** @overload */
  1650. template<typename _Tp, int n> _Tp* ptr(const Vec<int, n>& idx);
  1651. /** @overload */
  1652. template<typename _Tp, int n> const _Tp* ptr(const Vec<int, n>& idx) const;
  1653. /** @brief Returns a reference to the specified array element.
  1654. The template methods return a reference to the specified array element. For the sake of higher
  1655. performance, the index range checks are only performed in the Debug configuration.
  1656. Note that the variants with a single index (i) can be used to access elements of single-row or
  1657. single-column 2-dimensional arrays. That is, if, for example, A is a 1 x N floating-point matrix and
  1658. B is an M x 1 integer matrix, you can simply write `A.at<float>(k+4)` and `B.at<int>(2*i+1)`
  1659. instead of `A.at<float>(0,k+4)` and `B.at<int>(2*i+1,0)`, respectively.
  1660. The example below initializes a Hilbert matrix:
  1661. @code
  1662. Mat H(100, 100, CV_64F);
  1663. for(int i = 0; i < H.rows; i++)
  1664. for(int j = 0; j < H.cols; j++)
  1665. H.at<double>(i,j)=1./(i+j+1);
  1666. @endcode
  1667. Keep in mind that the size identifier used in the at operator cannot be chosen at random. It depends
  1668. on the image from which you are trying to retrieve the data. The table below gives a better insight in this:
  1669. - If matrix is of type `CV_8U` then use `Mat.at<uchar>(y,x)`.
  1670. - If matrix is of type `CV_8S` then use `Mat.at<schar>(y,x)`.
  1671. - If matrix is of type `CV_16U` then use `Mat.at<ushort>(y,x)`.
  1672. - If matrix is of type `CV_16S` then use `Mat.at<short>(y,x)`.
  1673. - If matrix is of type `CV_32S` then use `Mat.at<int>(y,x)`.
  1674. - If matrix is of type `CV_32F` then use `Mat.at<float>(y,x)`.
  1675. - If matrix is of type `CV_64F` then use `Mat.at<double>(y,x)`.
  1676. @param i0 Index along the dimension 0
  1677. */
  1678. template<typename _Tp> _Tp& at(int i0=0);
  1679. /** @overload
  1680. @param i0 Index along the dimension 0
  1681. */
  1682. template<typename _Tp> const _Tp& at(int i0=0) const;
  1683. /** @overload
  1684. @param row Index along the dimension 0
  1685. @param col Index along the dimension 1
  1686. */
  1687. template<typename _Tp> _Tp& at(int row, int col);
  1688. /** @overload
  1689. @param row Index along the dimension 0
  1690. @param col Index along the dimension 1
  1691. */
  1692. template<typename _Tp> const _Tp& at(int row, int col) const;
  1693. /** @overload
  1694. @param i0 Index along the dimension 0
  1695. @param i1 Index along the dimension 1
  1696. @param i2 Index along the dimension 2
  1697. */
  1698. template<typename _Tp> _Tp& at(int i0, int i1, int i2);
  1699. /** @overload
  1700. @param i0 Index along the dimension 0
  1701. @param i1 Index along the dimension 1
  1702. @param i2 Index along the dimension 2
  1703. */
  1704. template<typename _Tp> const _Tp& at(int i0, int i1, int i2) const;
  1705. /** @overload
  1706. @param idx Array of Mat::dims indices.
  1707. */
  1708. template<typename _Tp> _Tp& at(const int* idx);
  1709. /** @overload
  1710. @param idx Array of Mat::dims indices.
  1711. */
  1712. template<typename _Tp> const _Tp& at(const int* idx) const;
  1713. /** @overload */
  1714. template<typename _Tp, int n> _Tp& at(const Vec<int, n>& idx);
  1715. /** @overload */
  1716. template<typename _Tp, int n> const _Tp& at(const Vec<int, n>& idx) const;
  1717. /** @overload
  1718. special versions for 2D arrays (especially convenient for referencing image pixels)
  1719. @param pt Element position specified as Point(j,i) .
  1720. */
  1721. template<typename _Tp> _Tp& at(Point pt);
  1722. /** @overload
  1723. special versions for 2D arrays (especially convenient for referencing image pixels)
  1724. @param pt Element position specified as Point(j,i) .
  1725. */
  1726. template<typename _Tp> const _Tp& at(Point pt) const;
  1727. /** @brief Returns the matrix iterator and sets it to the first matrix element.
  1728. The methods return the matrix read-only or read-write iterators. The use of matrix iterators is very
  1729. similar to the use of bi-directional STL iterators. In the example below, the alpha blending
  1730. function is rewritten using the matrix iterators:
  1731. @code
  1732. template<typename T>
  1733. void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst)
  1734. {
  1735. typedef Vec<T, 4> VT;
  1736. const float alpha_scale = (float)std::numeric_limits<T>::max(),
  1737. inv_scale = 1.f/alpha_scale;
  1738. CV_Assert( src1.type() == src2.type() &&
  1739. src1.type() == traits::Type<VT>::value &&
  1740. src1.size() == src2.size());
  1741. Size size = src1.size();
  1742. dst.create(size, src1.type());
  1743. MatConstIterator_<VT> it1 = src1.begin<VT>(), it1_end = src1.end<VT>();
  1744. MatConstIterator_<VT> it2 = src2.begin<VT>();
  1745. MatIterator_<VT> dst_it = dst.begin<VT>();
  1746. for( ; it1 != it1_end; ++it1, ++it2, ++dst_it )
  1747. {
  1748. VT pix1 = *it1, pix2 = *it2;
  1749. float alpha = pix1[3]*inv_scale, beta = pix2[3]*inv_scale;
  1750. *dst_it = VT(saturate_cast<T>(pix1[0]*alpha + pix2[0]*beta),
  1751. saturate_cast<T>(pix1[1]*alpha + pix2[1]*beta),
  1752. saturate_cast<T>(pix1[2]*alpha + pix2[2]*beta),
  1753. saturate_cast<T>((1 - (1-alpha)*(1-beta))*alpha_scale));
  1754. }
  1755. }
  1756. @endcode
  1757. */
  1758. template<typename _Tp> MatIterator_<_Tp> begin();
  1759. template<typename _Tp> MatConstIterator_<_Tp> begin() const;
  1760. /** @brief Returns the matrix iterator and sets it to the after-last matrix element.
  1761. The methods return the matrix read-only or read-write iterators, set to the point following the last
  1762. matrix element.
  1763. */
  1764. template<typename _Tp> MatIterator_<_Tp> end();
  1765. template<typename _Tp> MatConstIterator_<_Tp> end() const;
  1766. /** @brief Runs the given functor over all matrix elements in parallel.
  1767. The operation passed as argument has to be a function pointer, a function object or a lambda(C++11).
  1768. Example 1. All of the operations below put 0xFF the first channel of all matrix elements:
  1769. @code
  1770. Mat image(1920, 1080, CV_8UC3);
  1771. typedef cv::Point3_<uint8_t> Pixel;
  1772. // first. raw pointer access.
  1773. for (int r = 0; r < image.rows; ++r) {
  1774. Pixel* ptr = image.ptr<Pixel>(r, 0);
  1775. const Pixel* ptr_end = ptr + image.cols;
  1776. for (; ptr != ptr_end; ++ptr) {
  1777. ptr->x = 255;
  1778. }
  1779. }
  1780. // Using MatIterator. (Simple but there are a Iterator's overhead)
  1781. for (Pixel &p : cv::Mat_<Pixel>(image)) {
  1782. p.x = 255;
  1783. }
  1784. // Parallel execution with function object.
  1785. struct Operator {
  1786. void operator ()(Pixel &pixel, const int * position) {
  1787. pixel.x = 255;
  1788. }
  1789. };
  1790. image.forEach<Pixel>(Operator());
  1791. // Parallel execution using C++11 lambda.
  1792. image.forEach<Pixel>([](Pixel &p, const int * position) -> void {
  1793. p.x = 255;
  1794. });
  1795. @endcode
  1796. Example 2. Using the pixel's position:
  1797. @code
  1798. // Creating 3D matrix (255 x 255 x 255) typed uint8_t
  1799. // and initialize all elements by the value which equals elements position.
  1800. // i.e. pixels (x,y,z) = (1,2,3) is (b,g,r) = (1,2,3).
  1801. int sizes[] = { 255, 255, 255 };
  1802. typedef cv::Point3_<uint8_t> Pixel;
  1803. Mat_<Pixel> image = Mat::zeros(3, sizes, CV_8UC3);
  1804. image.forEach<Pixel>([&](Pixel& pixel, const int position[]) -> void {
  1805. pixel.x = position[0];
  1806. pixel.y = position[1];
  1807. pixel.z = position[2];
  1808. });
  1809. @endcode
  1810. */
  1811. template<typename _Tp, typename Functor> void forEach(const Functor& operation);
  1812. /** @overload */
  1813. template<typename _Tp, typename Functor> void forEach(const Functor& operation) const;
  1814. #ifdef CV_CXX_MOVE_SEMANTICS
  1815. Mat(Mat&& m);
  1816. Mat& operator = (Mat&& m);
  1817. #endif
  1818. enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG };
  1819. enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 };
  1820. /*! includes several bit-fields:
  1821. - the magic signature
  1822. - continuity flag
  1823. - depth
  1824. - number of channels
  1825. */
  1826. int flags;
  1827. //! the matrix dimensionality, >= 2
  1828. int dims;
  1829. //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
  1830. int rows, cols;
  1831. //! pointer to the data
  1832. uchar* data;
  1833. //! helper fields used in locateROI and adjustROI
  1834. const uchar* datastart;
  1835. const uchar* dataend;
  1836. const uchar* datalimit;
  1837. //! custom allocator
  1838. MatAllocator* allocator;
  1839. //! and the standard allocator
  1840. static MatAllocator* getStdAllocator();
  1841. static MatAllocator* getDefaultAllocator();
  1842. static void setDefaultAllocator(MatAllocator* allocator);
  1843. //! internal use method: updates the continuity flag
  1844. void updateContinuityFlag();
  1845. //! interaction with UMat
  1846. UMatData* u;
  1847. MatSize size;
  1848. MatStep step;
  1849. protected:
  1850. template<typename _Tp, typename Functor> void forEach_impl(const Functor& operation);
  1851. };
  1852. ///////////////////////////////// Mat_<_Tp> ////////////////////////////////////
  1853. /** @brief Template matrix class derived from Mat
  1854. @code{.cpp}
  1855. template<typename _Tp> class Mat_ : public Mat
  1856. {
  1857. public:
  1858. // ... some specific methods
  1859. // and
  1860. // no new extra fields
  1861. };
  1862. @endcode
  1863. The class `Mat_<_Tp>` is a *thin* template wrapper on top of the Mat class. It does not have any
  1864. extra data fields. Nor this class nor Mat has any virtual methods. Thus, references or pointers to
  1865. these two classes can be freely but carefully converted one to another. For example:
  1866. @code{.cpp}
  1867. // create a 100x100 8-bit matrix
  1868. Mat M(100,100,CV_8U);
  1869. // this will be compiled fine. no any data conversion will be done.
  1870. Mat_<float>& M1 = (Mat_<float>&)M;
  1871. // the program is likely to crash at the statement below
  1872. M1(99,99) = 1.f;
  1873. @endcode
  1874. While Mat is sufficient in most cases, Mat_ can be more convenient if you use a lot of element
  1875. access operations and if you know matrix type at the compilation time. Note that
  1876. `Mat::at(int y,int x)` and `Mat_::operator()(int y,int x)` do absolutely the same
  1877. and run at the same speed, but the latter is certainly shorter:
  1878. @code{.cpp}
  1879. Mat_<double> M(20,20);
  1880. for(int i = 0; i < M.rows; i++)
  1881. for(int j = 0; j < M.cols; j++)
  1882. M(i,j) = 1./(i+j+1);
  1883. Mat E, V;
  1884. eigen(M,E,V);
  1885. cout << E.at<double>(0,0)/E.at<double>(M.rows-1,0);
  1886. @endcode
  1887. To use Mat_ for multi-channel images/matrices, pass Vec as a Mat_ parameter:
  1888. @code{.cpp}
  1889. // allocate a 320x240 color image and fill it with green (in RGB space)
  1890. Mat_<Vec3b> img(240, 320, Vec3b(0,255,0));
  1891. // now draw a diagonal white line
  1892. for(int i = 0; i < 100; i++)
  1893. img(i,i)=Vec3b(255,255,255);
  1894. // and now scramble the 2nd (red) channel of each pixel
  1895. for(int i = 0; i < img.rows; i++)
  1896. for(int j = 0; j < img.cols; j++)
  1897. img(i,j)[2] ^= (uchar)(i ^ j);
  1898. @endcode
  1899. Mat_ is fully compatible with C++11 range-based for loop. For example such loop
  1900. can be used to safely apply look-up table:
  1901. @code{.cpp}
  1902. void applyTable(Mat_<uchar>& I, const uchar* const table)
  1903. {
  1904. for(auto& pixel : I)
  1905. {
  1906. pixel = table[pixel];
  1907. }
  1908. }
  1909. @endcode
  1910. */
  1911. template<typename _Tp> class Mat_ : public Mat
  1912. {
  1913. public:
  1914. typedef _Tp value_type;
  1915. typedef typename DataType<_Tp>::channel_type channel_type;
  1916. typedef MatIterator_<_Tp> iterator;
  1917. typedef MatConstIterator_<_Tp> const_iterator;
  1918. //! default constructor
  1919. Mat_() CV_NOEXCEPT;
  1920. //! equivalent to Mat(_rows, _cols, DataType<_Tp>::type)
  1921. Mat_(int _rows, int _cols);
  1922. //! constructor that sets each matrix element to specified value
  1923. Mat_(int _rows, int _cols, const _Tp& value);
  1924. //! equivalent to Mat(_size, DataType<_Tp>::type)
  1925. explicit Mat_(Size _size);
  1926. //! constructor that sets each matrix element to specified value
  1927. Mat_(Size _size, const _Tp& value);
  1928. //! n-dim array constructor
  1929. Mat_(int _ndims, const int* _sizes);
  1930. //! n-dim array constructor that sets each matrix element to specified value
  1931. Mat_(int _ndims, const int* _sizes, const _Tp& value);
  1932. //! copy/conversion constructor. If m is of different type, it's converted
  1933. Mat_(const Mat& m);
  1934. //! copy constructor
  1935. Mat_(const Mat_& m);
  1936. //! constructs a matrix on top of user-allocated data. step is in bytes(!!!), regardless of the type
  1937. Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP);
  1938. //! constructs n-dim matrix on top of user-allocated data. steps are in bytes(!!!), regardless of the type
  1939. Mat_(int _ndims, const int* _sizes, _Tp* _data, const size_t* _steps=0);
  1940. //! selects a submatrix
  1941. Mat_(const Mat_& m, const Range& rowRange, const Range& colRange=Range::all());
  1942. //! selects a submatrix
  1943. Mat_(const Mat_& m, const Rect& roi);
  1944. //! selects a submatrix, n-dim version
  1945. Mat_(const Mat_& m, const Range* ranges);
  1946. //! selects a submatrix, n-dim version
  1947. Mat_(const Mat_& m, const std::vector<Range>& ranges);
  1948. //! from a matrix expression
  1949. explicit Mat_(const MatExpr& e);
  1950. //! makes a matrix out of Vec, std::vector, Point_ or Point3_. The matrix will have a single column
  1951. explicit Mat_(const std::vector<_Tp>& vec, bool copyData=false);
  1952. template<int n> explicit Mat_(const Vec<typename DataType<_Tp>::channel_type, n>& vec, bool copyData=true);
  1953. template<int m, int n> explicit Mat_(const Matx<typename DataType<_Tp>::channel_type, m, n>& mtx, bool copyData=true);
  1954. explicit Mat_(const Point_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
  1955. explicit Mat_(const Point3_<typename DataType<_Tp>::channel_type>& pt, bool copyData=true);
  1956. explicit Mat_(const MatCommaInitializer_<_Tp>& commaInitializer);
  1957. #ifdef CV_CXX11
  1958. Mat_(std::initializer_list<_Tp> values);
  1959. explicit Mat_(const std::initializer_list<int> sizes, const std::initializer_list<_Tp> values);
  1960. #endif
  1961. #ifdef CV_CXX_STD_ARRAY
  1962. template <std::size_t _Nm> explicit Mat_(const std::array<_Tp, _Nm>& arr, bool copyData=false);
  1963. #endif
  1964. Mat_& operator = (const Mat& m);
  1965. Mat_& operator = (const Mat_& m);
  1966. //! set all the elements to s.
  1967. Mat_& operator = (const _Tp& s);
  1968. //! assign a matrix expression
  1969. Mat_& operator = (const MatExpr& e);
  1970. //! iterators; they are smart enough to skip gaps in the end of rows
  1971. iterator begin();
  1972. iterator end();
  1973. const_iterator begin() const;
  1974. const_iterator end() const;
  1975. //! template methods for for operation over all matrix elements.
  1976. // the operations take care of skipping gaps in the end of rows (if any)
  1977. template<typename Functor> void forEach(const Functor& operation);
  1978. template<typename Functor> void forEach(const Functor& operation) const;
  1979. //! equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type)
  1980. void create(int _rows, int _cols);
  1981. //! equivalent to Mat::create(_size, DataType<_Tp>::type)
  1982. void create(Size _size);
  1983. //! equivalent to Mat::create(_ndims, _sizes, DatType<_Tp>::type)
  1984. void create(int _ndims, const int* _sizes);
  1985. //! equivalent to Mat::release()
  1986. void release();
  1987. //! cross-product
  1988. Mat_ cross(const Mat_& m) const;
  1989. //! data type conversion
  1990. template<typename T2> operator Mat_<T2>() const;
  1991. //! overridden forms of Mat::row() etc.
  1992. Mat_ row(int y) const;
  1993. Mat_ col(int x) const;
  1994. Mat_ diag(int d=0) const;
  1995. Mat_ clone() const CV_NODISCARD;
  1996. //! overridden forms of Mat::elemSize() etc.
  1997. size_t elemSize() const;
  1998. size_t elemSize1() const;
  1999. int type() const;
  2000. int depth() const;
  2001. int channels() const;
  2002. size_t step1(int i=0) const;
  2003. //! returns step()/sizeof(_Tp)
  2004. size_t stepT(int i=0) const;
  2005. //! overridden forms of Mat::zeros() etc. Data type is omitted, of course
  2006. static MatExpr zeros(int rows, int cols);
  2007. static MatExpr zeros(Size size);
  2008. static MatExpr zeros(int _ndims, const int* _sizes);
  2009. static MatExpr ones(int rows, int cols);
  2010. static MatExpr ones(Size size);
  2011. static MatExpr ones(int _ndims, const int* _sizes);
  2012. static MatExpr eye(int rows, int cols);
  2013. static MatExpr eye(Size size);
  2014. //! some more overridden methods
  2015. Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright );
  2016. Mat_ operator()( const Range& rowRange, const Range& colRange ) const;
  2017. Mat_ operator()( const Rect& roi ) const;
  2018. Mat_ operator()( const Range* ranges ) const;
  2019. Mat_ operator()(const std::vector<Range>& ranges) const;
  2020. //! more convenient forms of row and element access operators
  2021. _Tp* operator [](int y);
  2022. const _Tp* operator [](int y) const;
  2023. //! returns reference to the specified element
  2024. _Tp& operator ()(const int* idx);
  2025. //! returns read-only reference to the specified element
  2026. const _Tp& operator ()(const int* idx) const;
  2027. //! returns reference to the specified element
  2028. template<int n> _Tp& operator ()(const Vec<int, n>& idx);
  2029. //! returns read-only reference to the specified element
  2030. template<int n> const _Tp& operator ()(const Vec<int, n>& idx) const;
  2031. //! returns reference to the specified element (1D case)
  2032. _Tp& operator ()(int idx0);
  2033. //! returns read-only reference to the specified element (1D case)
  2034. const _Tp& operator ()(int idx0) const;
  2035. //! returns reference to the specified element (2D case)
  2036. _Tp& operator ()(int row, int col);
  2037. //! returns read-only reference to the specified element (2D case)
  2038. const _Tp& operator ()(int row, int col) const;
  2039. //! returns reference to the specified element (3D case)
  2040. _Tp& operator ()(int idx0, int idx1, int idx2);
  2041. //! returns read-only reference to the specified element (3D case)
  2042. const _Tp& operator ()(int idx0, int idx1, int idx2) const;
  2043. _Tp& operator ()(Point pt);
  2044. const _Tp& operator ()(Point pt) const;
  2045. //! conversion to vector.
  2046. operator std::vector<_Tp>() const;
  2047. #ifdef CV_CXX_STD_ARRAY
  2048. //! conversion to array.
  2049. template<std::size_t _Nm> operator std::array<_Tp, _Nm>() const;
  2050. #endif
  2051. //! conversion to Vec
  2052. template<int n> operator Vec<typename DataType<_Tp>::channel_type, n>() const;
  2053. //! conversion to Matx
  2054. template<int m, int n> operator Matx<typename DataType<_Tp>::channel_type, m, n>() const;
  2055. #ifdef CV_CXX_MOVE_SEMANTICS
  2056. Mat_(Mat_&& m);
  2057. Mat_& operator = (Mat_&& m);
  2058. Mat_(Mat&& m);
  2059. Mat_& operator = (Mat&& m);
  2060. Mat_(MatExpr&& e);
  2061. #endif
  2062. };
  2063. typedef Mat_<uchar> Mat1b;
  2064. typedef Mat_<Vec2b> Mat2b;
  2065. typedef Mat_<Vec3b> Mat3b;
  2066. typedef Mat_<Vec4b> Mat4b;
  2067. typedef Mat_<short> Mat1s;
  2068. typedef Mat_<Vec2s> Mat2s;
  2069. typedef Mat_<Vec3s> Mat3s;
  2070. typedef Mat_<Vec4s> Mat4s;
  2071. typedef Mat_<ushort> Mat1w;
  2072. typedef Mat_<Vec2w> Mat2w;
  2073. typedef Mat_<Vec3w> Mat3w;
  2074. typedef Mat_<Vec4w> Mat4w;
  2075. typedef Mat_<int> Mat1i;
  2076. typedef Mat_<Vec2i> Mat2i;
  2077. typedef Mat_<Vec3i> Mat3i;
  2078. typedef Mat_<Vec4i> Mat4i;
  2079. typedef Mat_<float> Mat1f;
  2080. typedef Mat_<Vec2f> Mat2f;
  2081. typedef Mat_<Vec3f> Mat3f;
  2082. typedef Mat_<Vec4f> Mat4f;
  2083. typedef Mat_<double> Mat1d;
  2084. typedef Mat_<Vec2d> Mat2d;
  2085. typedef Mat_<Vec3d> Mat3d;
  2086. typedef Mat_<Vec4d> Mat4d;
  2087. /** @todo document */
  2088. class CV_EXPORTS UMat
  2089. {
  2090. public:
  2091. //! default constructor
  2092. UMat(UMatUsageFlags usageFlags = USAGE_DEFAULT) CV_NOEXCEPT;
  2093. //! constructs 2D matrix of the specified size and type
  2094. // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
  2095. UMat(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
  2096. UMat(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
  2097. //! constructs 2D matrix and fills it with the specified value _s.
  2098. UMat(int rows, int cols, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT);
  2099. UMat(Size size, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT);
  2100. //! constructs n-dimensional matrix
  2101. UMat(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
  2102. UMat(int ndims, const int* sizes, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT);
  2103. //! copy constructor
  2104. UMat(const UMat& m);
  2105. //! creates a matrix header for a part of the bigger matrix
  2106. UMat(const UMat& m, const Range& rowRange, const Range& colRange=Range::all());
  2107. UMat(const UMat& m, const Rect& roi);
  2108. UMat(const UMat& m, const Range* ranges);
  2109. UMat(const UMat& m, const std::vector<Range>& ranges);
  2110. // FIXIT copyData=false is not implemented, drop this in favor of cv::Mat (OpenCV 5.0)
  2111. //! builds matrix from std::vector with or without copying the data
  2112. template<typename _Tp> explicit UMat(const std::vector<_Tp>& vec, bool copyData=false);
  2113. //! destructor - calls release()
  2114. ~UMat();
  2115. //! assignment operators
  2116. UMat& operator = (const UMat& m);
  2117. Mat getMat(int flags) const;
  2118. //! returns a new matrix header for the specified row
  2119. UMat row(int y) const;
  2120. //! returns a new matrix header for the specified column
  2121. UMat col(int x) const;
  2122. //! ... for the specified row span
  2123. UMat rowRange(int startrow, int endrow) const;
  2124. UMat rowRange(const Range& r) const;
  2125. //! ... for the specified column span
  2126. UMat colRange(int startcol, int endcol) const;
  2127. UMat colRange(const Range& r) const;
  2128. //! ... for the specified diagonal
  2129. //! (d=0 - the main diagonal,
  2130. //! >0 - a diagonal from the upper half,
  2131. //! <0 - a diagonal from the lower half)
  2132. UMat diag(int d=0) const;
  2133. //! constructs a square diagonal matrix which main diagonal is vector "d"
  2134. static UMat diag(const UMat& d);
  2135. //! returns deep copy of the matrix, i.e. the data is copied
  2136. UMat clone() const CV_NODISCARD;
  2137. //! copies the matrix content to "m".
  2138. // It calls m.create(this->size(), this->type()).
  2139. void copyTo( OutputArray m ) const;
  2140. //! copies those matrix elements to "m" that are marked with non-zero mask elements.
  2141. void copyTo( OutputArray m, InputArray mask ) const;
  2142. //! converts matrix to another datatype with optional scaling. See cvConvertScale.
  2143. void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const;
  2144. void assignTo( UMat& m, int type=-1 ) const;
  2145. //! sets every matrix element to s
  2146. UMat& operator = (const Scalar& s);
  2147. //! sets some of the matrix elements to s, according to the mask
  2148. UMat& setTo(InputArray value, InputArray mask=noArray());
  2149. //! creates alternative matrix header for the same data, with different
  2150. // number of channels and/or different number of rows. see cvReshape.
  2151. UMat reshape(int cn, int rows=0) const;
  2152. UMat reshape(int cn, int newndims, const int* newsz) const;
  2153. //! matrix transposition by means of matrix expressions
  2154. UMat t() const;
  2155. //! matrix inversion by means of matrix expressions
  2156. UMat inv(int method=DECOMP_LU) const;
  2157. //! per-element matrix multiplication by means of matrix expressions
  2158. UMat mul(InputArray m, double scale=1) const;
  2159. //! computes dot-product
  2160. double dot(InputArray m) const;
  2161. //! Matlab-style matrix initialization
  2162. static UMat zeros(int rows, int cols, int type);
  2163. static UMat zeros(Size size, int type);
  2164. static UMat zeros(int ndims, const int* sz, int type);
  2165. static UMat ones(int rows, int cols, int type);
  2166. static UMat ones(Size size, int type);
  2167. static UMat ones(int ndims, const int* sz, int type);
  2168. static UMat eye(int rows, int cols, int type);
  2169. static UMat eye(Size size, int type);
  2170. //! allocates new matrix data unless the matrix already has specified size and type.
  2171. // previous data is unreferenced if needed.
  2172. void create(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
  2173. void create(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
  2174. void create(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
  2175. void create(const std::vector<int>& sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT);
  2176. //! increases the reference counter; use with care to avoid memleaks
  2177. void addref();
  2178. //! decreases reference counter;
  2179. // deallocates the data when reference counter reaches 0.
  2180. void release();
  2181. //! deallocates the matrix data
  2182. void deallocate();
  2183. //! internal use function; properly re-allocates _size, _step arrays
  2184. void copySize(const UMat& m);
  2185. //! locates matrix header within a parent matrix. See below
  2186. void locateROI( Size& wholeSize, Point& ofs ) const;
  2187. //! moves/resizes the current matrix ROI inside the parent matrix.
  2188. UMat& adjustROI( int dtop, int dbottom, int dleft, int dright );
  2189. //! extracts a rectangular sub-matrix
  2190. // (this is a generalized form of row, rowRange etc.)
  2191. UMat operator()( Range rowRange, Range colRange ) const;
  2192. UMat operator()( const Rect& roi ) const;
  2193. UMat operator()( const Range* ranges ) const;
  2194. UMat operator()(const std::vector<Range>& ranges) const;
  2195. //! returns true iff the matrix data is continuous
  2196. // (i.e. when there are no gaps between successive rows).
  2197. // similar to CV_IS_MAT_CONT(cvmat->type)
  2198. bool isContinuous() const;
  2199. //! returns true if the matrix is a submatrix of another matrix
  2200. bool isSubmatrix() const;
  2201. //! returns element size in bytes,
  2202. // similar to CV_ELEM_SIZE(cvmat->type)
  2203. size_t elemSize() const;
  2204. //! returns the size of element channel in bytes.
  2205. size_t elemSize1() const;
  2206. //! returns element type, similar to CV_MAT_TYPE(cvmat->type)
  2207. int type() const;
  2208. //! returns element type, similar to CV_MAT_DEPTH(cvmat->type)
  2209. int depth() const;
  2210. //! returns element type, similar to CV_MAT_CN(cvmat->type)
  2211. int channels() const;
  2212. //! returns step/elemSize1()
  2213. size_t step1(int i=0) const;
  2214. //! returns true if matrix data is NULL
  2215. bool empty() const;
  2216. //! returns the total number of matrix elements
  2217. size_t total() const;
  2218. //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise
  2219. int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const;
  2220. #ifdef CV_CXX_MOVE_SEMANTICS
  2221. UMat(UMat&& m);
  2222. UMat& operator = (UMat&& m);
  2223. #endif
  2224. /*! Returns the OpenCL buffer handle on which UMat operates on.
  2225. The UMat instance should be kept alive during the use of the handle to prevent the buffer to be
  2226. returned to the OpenCV buffer pool.
  2227. */
  2228. void* handle(int accessFlags) const;
  2229. void ndoffset(size_t* ofs) const;
  2230. enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG };
  2231. enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 };
  2232. /*! includes several bit-fields:
  2233. - the magic signature
  2234. - continuity flag
  2235. - depth
  2236. - number of channels
  2237. */
  2238. int flags;
  2239. //! the matrix dimensionality, >= 2
  2240. int dims;
  2241. //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions
  2242. int rows, cols;
  2243. //! custom allocator
  2244. MatAllocator* allocator;
  2245. UMatUsageFlags usageFlags; // usage flags for allocator
  2246. //! and the standard allocator
  2247. static MatAllocator* getStdAllocator();
  2248. //! internal use method: updates the continuity flag
  2249. void updateContinuityFlag();
  2250. // black-box container of UMat data
  2251. UMatData* u;
  2252. // offset of the submatrix (or 0)
  2253. size_t offset;
  2254. MatSize size;
  2255. MatStep step;
  2256. protected:
  2257. };
  2258. /////////////////////////// multi-dimensional sparse matrix //////////////////////////
  2259. /** @brief The class SparseMat represents multi-dimensional sparse numerical arrays.
  2260. Such a sparse array can store elements of any type that Mat can store. *Sparse* means that only
  2261. non-zero elements are stored (though, as a result of operations on a sparse matrix, some of its
  2262. stored elements can actually become 0. It is up to you to detect such elements and delete them
  2263. using SparseMat::erase ). The non-zero elements are stored in a hash table that grows when it is
  2264. filled so that the search time is O(1) in average (regardless of whether element is there or not).
  2265. Elements can be accessed using the following methods:
  2266. - Query operations (SparseMat::ptr and the higher-level SparseMat::ref, SparseMat::value and
  2267. SparseMat::find), for example:
  2268. @code
  2269. const int dims = 5;
  2270. int size[5] = {10, 10, 10, 10, 10};
  2271. SparseMat sparse_mat(dims, size, CV_32F);
  2272. for(int i = 0; i < 1000; i++)
  2273. {
  2274. int idx[dims];
  2275. for(int k = 0; k < dims; k++)
  2276. idx[k] = rand() % size[k];
  2277. sparse_mat.ref<float>(idx) += 1.f;
  2278. }
  2279. cout << "nnz = " << sparse_mat.nzcount() << endl;
  2280. @endcode
  2281. - Sparse matrix iterators. They are similar to MatIterator but different from NAryMatIterator.
  2282. That is, the iteration loop is familiar to STL users:
  2283. @code
  2284. // prints elements of a sparse floating-point matrix
  2285. // and the sum of elements.
  2286. SparseMatConstIterator_<float>
  2287. it = sparse_mat.begin<float>(),
  2288. it_end = sparse_mat.end<float>();
  2289. double s = 0;
  2290. int dims = sparse_mat.dims();
  2291. for(; it != it_end; ++it)
  2292. {
  2293. // print element indices and the element value
  2294. const SparseMat::Node* n = it.node();
  2295. printf("(");
  2296. for(int i = 0; i < dims; i++)
  2297. printf("%d%s", n->idx[i], i < dims-1 ? ", " : ")");
  2298. printf(": %g\n", it.value<float>());
  2299. s += *it;
  2300. }
  2301. printf("Element sum is %g\n", s);
  2302. @endcode
  2303. If you run this loop, you will notice that elements are not enumerated in a logical order
  2304. (lexicographical, and so on). They come in the same order as they are stored in the hash table
  2305. (semi-randomly). You may collect pointers to the nodes and sort them to get the proper ordering.
  2306. Note, however, that pointers to the nodes may become invalid when you add more elements to the
  2307. matrix. This may happen due to possible buffer reallocation.
  2308. - Combination of the above 2 methods when you need to process 2 or more sparse matrices
  2309. simultaneously. For example, this is how you can compute unnormalized cross-correlation of the 2
  2310. floating-point sparse matrices:
  2311. @code
  2312. double cross_corr(const SparseMat& a, const SparseMat& b)
  2313. {
  2314. const SparseMat *_a = &a, *_b = &b;
  2315. // if b contains less elements than a,
  2316. // it is faster to iterate through b
  2317. if(_a->nzcount() > _b->nzcount())
  2318. std::swap(_a, _b);
  2319. SparseMatConstIterator_<float> it = _a->begin<float>(),
  2320. it_end = _a->end<float>();
  2321. double ccorr = 0;
  2322. for(; it != it_end; ++it)
  2323. {
  2324. // take the next element from the first matrix
  2325. float avalue = *it;
  2326. const Node* anode = it.node();
  2327. // and try to find an element with the same index in the second matrix.
  2328. // since the hash value depends only on the element index,
  2329. // reuse the hash value stored in the node
  2330. float bvalue = _b->value<float>(anode->idx,&anode->hashval);
  2331. ccorr += avalue*bvalue;
  2332. }
  2333. return ccorr;
  2334. }
  2335. @endcode
  2336. */
  2337. class CV_EXPORTS SparseMat
  2338. {
  2339. public:
  2340. typedef SparseMatIterator iterator;
  2341. typedef SparseMatConstIterator const_iterator;
  2342. enum { MAGIC_VAL=0x42FD0000, MAX_DIM=32, HASH_SCALE=0x5bd1e995, HASH_BIT=0x80000000 };
  2343. //! the sparse matrix header
  2344. struct CV_EXPORTS Hdr
  2345. {
  2346. Hdr(int _dims, const int* _sizes, int _type);
  2347. void clear();
  2348. int refcount;
  2349. int dims;
  2350. int valueOffset;
  2351. size_t nodeSize;
  2352. size_t nodeCount;
  2353. size_t freeList;
  2354. std::vector<uchar> pool;
  2355. std::vector<size_t> hashtab;
  2356. int size[MAX_DIM];
  2357. };
  2358. //! sparse matrix node - element of a hash table
  2359. struct CV_EXPORTS Node
  2360. {
  2361. //! hash value
  2362. size_t hashval;
  2363. //! index of the next node in the same hash table entry
  2364. size_t next;
  2365. //! index of the matrix element
  2366. int idx[MAX_DIM];
  2367. };
  2368. /** @brief Various SparseMat constructors.
  2369. */
  2370. SparseMat();
  2371. /** @overload
  2372. @param dims Array dimensionality.
  2373. @param _sizes Sparce matrix size on all dementions.
  2374. @param _type Sparse matrix data type.
  2375. */
  2376. SparseMat(int dims, const int* _sizes, int _type);
  2377. /** @overload
  2378. @param m Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted
  2379. to sparse representation.
  2380. */
  2381. SparseMat(const SparseMat& m);
  2382. /** @overload
  2383. @param m Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted
  2384. to sparse representation.
  2385. */
  2386. explicit SparseMat(const Mat& m);
  2387. //! the destructor
  2388. ~SparseMat();
  2389. //! assignment operator. This is O(1) operation, i.e. no data is copied
  2390. SparseMat& operator = (const SparseMat& m);
  2391. //! equivalent to the corresponding constructor
  2392. SparseMat& operator = (const Mat& m);
  2393. //! creates full copy of the matrix
  2394. SparseMat clone() const CV_NODISCARD;
  2395. //! copies all the data to the destination matrix. All the previous content of m is erased
  2396. void copyTo( SparseMat& m ) const;
  2397. //! converts sparse matrix to dense matrix.
  2398. void copyTo( Mat& m ) const;
  2399. //! multiplies all the matrix elements by the specified scale factor alpha and converts the results to the specified data type
  2400. void convertTo( SparseMat& m, int rtype, double alpha=1 ) const;
  2401. //! converts sparse matrix to dense n-dim matrix with optional type conversion and scaling.
  2402. /*!
  2403. @param [out] m - output matrix; if it does not have a proper size or type before the operation,
  2404. it is reallocated
  2405. @param [in] rtype - desired output matrix type or, rather, the depth since the number of channels
  2406. are the same as the input has; if rtype is negative, the output matrix will have the
  2407. same type as the input.
  2408. @param [in] alpha - optional scale factor
  2409. @param [in] beta - optional delta added to the scaled values
  2410. */
  2411. void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const;
  2412. // not used now
  2413. void assignTo( SparseMat& m, int type=-1 ) const;
  2414. //! reallocates sparse matrix.
  2415. /*!
  2416. If the matrix already had the proper size and type,
  2417. it is simply cleared with clear(), otherwise,
  2418. the old matrix is released (using release()) and the new one is allocated.
  2419. */
  2420. void create(int dims, const int* _sizes, int _type);
  2421. //! sets all the sparse matrix elements to 0, which means clearing the hash table.
  2422. void clear();
  2423. //! manually increments the reference counter to the header.
  2424. void addref();
  2425. // decrements the header reference counter. When the counter reaches 0, the header and all the underlying data are deallocated.
  2426. void release();
  2427. //! converts sparse matrix to the old-style representation; all the elements are copied.
  2428. //operator CvSparseMat*() const;
  2429. //! returns the size of each element in bytes (not including the overhead - the space occupied by SparseMat::Node elements)
  2430. size_t elemSize() const;
  2431. //! returns elemSize()/channels()
  2432. size_t elemSize1() const;
  2433. //! returns type of sparse matrix elements
  2434. int type() const;
  2435. //! returns the depth of sparse matrix elements
  2436. int depth() const;
  2437. //! returns the number of channels
  2438. int channels() const;
  2439. //! returns the array of sizes, or NULL if the matrix is not allocated
  2440. const int* size() const;
  2441. //! returns the size of i-th matrix dimension (or 0)
  2442. int size(int i) const;
  2443. //! returns the matrix dimensionality
  2444. int dims() const;
  2445. //! returns the number of non-zero elements (=the number of hash table nodes)
  2446. size_t nzcount() const;
  2447. //! computes the element hash value (1D case)
  2448. size_t hash(int i0) const;
  2449. //! computes the element hash value (2D case)
  2450. size_t hash(int i0, int i1) const;
  2451. //! computes the element hash value (3D case)
  2452. size_t hash(int i0, int i1, int i2) const;
  2453. //! computes the element hash value (nD case)
  2454. size_t hash(const int* idx) const;
  2455. //!@{
  2456. /*!
  2457. specialized variants for 1D, 2D, 3D cases and the generic_type one for n-D case.
  2458. return pointer to the matrix element.
  2459. - if the element is there (it's non-zero), the pointer to it is returned
  2460. - if it's not there and createMissing=false, NULL pointer is returned
  2461. - if it's not there and createMissing=true, then the new element
  2462. is created and initialized with 0. Pointer to it is returned
  2463. - if the optional hashval pointer is not NULL, the element hash value is
  2464. not computed, but *hashval is taken instead.
  2465. */
  2466. //! returns pointer to the specified element (1D case)
  2467. uchar* ptr(int i0, bool createMissing, size_t* hashval=0);
  2468. //! returns pointer to the specified element (2D case)
  2469. uchar* ptr(int i0, int i1, bool createMissing, size_t* hashval=0);
  2470. //! returns pointer to the specified element (3D case)
  2471. uchar* ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0);
  2472. //! returns pointer to the specified element (nD case)
  2473. uchar* ptr(const int* idx, bool createMissing, size_t* hashval=0);
  2474. //!@}
  2475. //!@{
  2476. /*!
  2477. return read-write reference to the specified sparse matrix element.
  2478. `ref<_Tp>(i0,...[,hashval])` is equivalent to `*(_Tp*)ptr(i0,...,true[,hashval])`.
  2479. The methods always return a valid reference.
  2480. If the element did not exist, it is created and initialized with 0.
  2481. */
  2482. //! returns reference to the specified element (1D case)
  2483. template<typename _Tp> _Tp& ref(int i0, size_t* hashval=0);
  2484. //! returns reference to the specified element (2D case)
  2485. template<typename _Tp> _Tp& ref(int i0, int i1, size_t* hashval=0);
  2486. //! returns reference to the specified element (3D case)
  2487. template<typename _Tp> _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
  2488. //! returns reference to the specified element (nD case)
  2489. template<typename _Tp> _Tp& ref(const int* idx, size_t* hashval=0);
  2490. //!@}
  2491. //!@{
  2492. /*!
  2493. return value of the specified sparse matrix element.
  2494. `value<_Tp>(i0,...[,hashval])` is equivalent to
  2495. @code
  2496. { const _Tp* p = find<_Tp>(i0,...[,hashval]); return p ? *p : _Tp(); }
  2497. @endcode
  2498. That is, if the element did not exist, the methods return 0.
  2499. */
  2500. //! returns value of the specified element (1D case)
  2501. template<typename _Tp> _Tp value(int i0, size_t* hashval=0) const;
  2502. //! returns value of the specified element (2D case)
  2503. template<typename _Tp> _Tp value(int i0, int i1, size_t* hashval=0) const;
  2504. //! returns value of the specified element (3D case)
  2505. template<typename _Tp> _Tp value(int i0, int i1, int i2, size_t* hashval=0) const;
  2506. //! returns value of the specified element (nD case)
  2507. template<typename _Tp> _Tp value(const int* idx, size_t* hashval=0) const;
  2508. //!@}
  2509. //!@{
  2510. /*!
  2511. Return pointer to the specified sparse matrix element if it exists
  2512. `find<_Tp>(i0,...[,hashval])` is equivalent to `(_const Tp*)ptr(i0,...false[,hashval])`.
  2513. If the specified element does not exist, the methods return NULL.
  2514. */
  2515. //! returns pointer to the specified element (1D case)
  2516. template<typename _Tp> const _Tp* find(int i0, size_t* hashval=0) const;
  2517. //! returns pointer to the specified element (2D case)
  2518. template<typename _Tp> const _Tp* find(int i0, int i1, size_t* hashval=0) const;
  2519. //! returns pointer to the specified element (3D case)
  2520. template<typename _Tp> const _Tp* find(int i0, int i1, int i2, size_t* hashval=0) const;
  2521. //! returns pointer to the specified element (nD case)
  2522. template<typename _Tp> const _Tp* find(const int* idx, size_t* hashval=0) const;
  2523. //!@}
  2524. //! erases the specified element (2D case)
  2525. void erase(int i0, int i1, size_t* hashval=0);
  2526. //! erases the specified element (3D case)
  2527. void erase(int i0, int i1, int i2, size_t* hashval=0);
  2528. //! erases the specified element (nD case)
  2529. void erase(const int* idx, size_t* hashval=0);
  2530. //!@{
  2531. /*!
  2532. return the sparse matrix iterator pointing to the first sparse matrix element
  2533. */
  2534. //! returns the sparse matrix iterator at the matrix beginning
  2535. SparseMatIterator begin();
  2536. //! returns the sparse matrix iterator at the matrix beginning
  2537. template<typename _Tp> SparseMatIterator_<_Tp> begin();
  2538. //! returns the read-only sparse matrix iterator at the matrix beginning
  2539. SparseMatConstIterator begin() const;
  2540. //! returns the read-only sparse matrix iterator at the matrix beginning
  2541. template<typename _Tp> SparseMatConstIterator_<_Tp> begin() const;
  2542. //!@}
  2543. /*!
  2544. return the sparse matrix iterator pointing to the element following the last sparse matrix element
  2545. */
  2546. //! returns the sparse matrix iterator at the matrix end
  2547. SparseMatIterator end();
  2548. //! returns the read-only sparse matrix iterator at the matrix end
  2549. SparseMatConstIterator end() const;
  2550. //! returns the typed sparse matrix iterator at the matrix end
  2551. template<typename _Tp> SparseMatIterator_<_Tp> end();
  2552. //! returns the typed read-only sparse matrix iterator at the matrix end
  2553. template<typename _Tp> SparseMatConstIterator_<_Tp> end() const;
  2554. //! returns the value stored in the sparse martix node
  2555. template<typename _Tp> _Tp& value(Node* n);
  2556. //! returns the value stored in the sparse martix node
  2557. template<typename _Tp> const _Tp& value(const Node* n) const;
  2558. ////////////// some internal-use methods ///////////////
  2559. Node* node(size_t nidx);
  2560. const Node* node(size_t nidx) const;
  2561. uchar* newNode(const int* idx, size_t hashval);
  2562. void removeNode(size_t hidx, size_t nidx, size_t previdx);
  2563. void resizeHashTab(size_t newsize);
  2564. int flags;
  2565. Hdr* hdr;
  2566. };
  2567. ///////////////////////////////// SparseMat_<_Tp> ////////////////////////////////////
  2568. /** @brief Template sparse n-dimensional array class derived from SparseMat
  2569. SparseMat_ is a thin wrapper on top of SparseMat created in the same way as Mat_ . It simplifies
  2570. notation of some operations:
  2571. @code
  2572. int sz[] = {10, 20, 30};
  2573. SparseMat_<double> M(3, sz);
  2574. ...
  2575. M.ref(1, 2, 3) = M(4, 5, 6) + M(7, 8, 9);
  2576. @endcode
  2577. */
  2578. template<typename _Tp> class SparseMat_ : public SparseMat
  2579. {
  2580. public:
  2581. typedef SparseMatIterator_<_Tp> iterator;
  2582. typedef SparseMatConstIterator_<_Tp> const_iterator;
  2583. //! the default constructor
  2584. SparseMat_();
  2585. //! the full constructor equivalent to SparseMat(dims, _sizes, DataType<_Tp>::type)
  2586. SparseMat_(int dims, const int* _sizes);
  2587. //! the copy constructor. If DataType<_Tp>.type != m.type(), the m elements are converted
  2588. SparseMat_(const SparseMat& m);
  2589. //! the copy constructor. This is O(1) operation - no data is copied
  2590. SparseMat_(const SparseMat_& m);
  2591. //! converts dense matrix to the sparse form
  2592. SparseMat_(const Mat& m);
  2593. //! converts the old-style sparse matrix to the C++ class. All the elements are copied
  2594. //SparseMat_(const CvSparseMat* m);
  2595. //! the assignment operator. If DataType<_Tp>.type != m.type(), the m elements are converted
  2596. SparseMat_& operator = (const SparseMat& m);
  2597. //! the assignment operator. This is O(1) operation - no data is copied
  2598. SparseMat_& operator = (const SparseMat_& m);
  2599. //! converts dense matrix to the sparse form
  2600. SparseMat_& operator = (const Mat& m);
  2601. //! makes full copy of the matrix. All the elements are duplicated
  2602. SparseMat_ clone() const CV_NODISCARD;
  2603. //! equivalent to cv::SparseMat::create(dims, _sizes, DataType<_Tp>::type)
  2604. void create(int dims, const int* _sizes);
  2605. //! converts sparse matrix to the old-style CvSparseMat. All the elements are copied
  2606. //operator CvSparseMat*() const;
  2607. //! returns type of the matrix elements
  2608. int type() const;
  2609. //! returns depth of the matrix elements
  2610. int depth() const;
  2611. //! returns the number of channels in each matrix element
  2612. int channels() const;
  2613. //! equivalent to SparseMat::ref<_Tp>(i0, hashval)
  2614. _Tp& ref(int i0, size_t* hashval=0);
  2615. //! equivalent to SparseMat::ref<_Tp>(i0, i1, hashval)
  2616. _Tp& ref(int i0, int i1, size_t* hashval=0);
  2617. //! equivalent to SparseMat::ref<_Tp>(i0, i1, i2, hashval)
  2618. _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
  2619. //! equivalent to SparseMat::ref<_Tp>(idx, hashval)
  2620. _Tp& ref(const int* idx, size_t* hashval=0);
  2621. //! equivalent to SparseMat::value<_Tp>(i0, hashval)
  2622. _Tp operator()(int i0, size_t* hashval=0) const;
  2623. //! equivalent to SparseMat::value<_Tp>(i0, i1, hashval)
  2624. _Tp operator()(int i0, int i1, size_t* hashval=0) const;
  2625. //! equivalent to SparseMat::value<_Tp>(i0, i1, i2, hashval)
  2626. _Tp operator()(int i0, int i1, int i2, size_t* hashval=0) const;
  2627. //! equivalent to SparseMat::value<_Tp>(idx, hashval)
  2628. _Tp operator()(const int* idx, size_t* hashval=0) const;
  2629. //! returns sparse matrix iterator pointing to the first sparse matrix element
  2630. SparseMatIterator_<_Tp> begin();
  2631. //! returns read-only sparse matrix iterator pointing to the first sparse matrix element
  2632. SparseMatConstIterator_<_Tp> begin() const;
  2633. //! returns sparse matrix iterator pointing to the element following the last sparse matrix element
  2634. SparseMatIterator_<_Tp> end();
  2635. //! returns read-only sparse matrix iterator pointing to the element following the last sparse matrix element
  2636. SparseMatConstIterator_<_Tp> end() const;
  2637. };
  2638. ////////////////////////////////// MatConstIterator //////////////////////////////////
  2639. class CV_EXPORTS MatConstIterator
  2640. {
  2641. public:
  2642. typedef uchar* value_type;
  2643. typedef ptrdiff_t difference_type;
  2644. typedef const uchar** pointer;
  2645. typedef uchar* reference;
  2646. typedef std::random_access_iterator_tag iterator_category;
  2647. //! default constructor
  2648. MatConstIterator();
  2649. //! constructor that sets the iterator to the beginning of the matrix
  2650. MatConstIterator(const Mat* _m);
  2651. //! constructor that sets the iterator to the specified element of the matrix
  2652. MatConstIterator(const Mat* _m, int _row, int _col=0);
  2653. //! constructor that sets the iterator to the specified element of the matrix
  2654. MatConstIterator(const Mat* _m, Point _pt);
  2655. //! constructor that sets the iterator to the specified element of the matrix
  2656. MatConstIterator(const Mat* _m, const int* _idx);
  2657. //! copy constructor
  2658. MatConstIterator(const MatConstIterator& it);
  2659. //! copy operator
  2660. MatConstIterator& operator = (const MatConstIterator& it);
  2661. //! returns the current matrix element
  2662. const uchar* operator *() const;
  2663. //! returns the i-th matrix element, relative to the current
  2664. const uchar* operator [](ptrdiff_t i) const;
  2665. //! shifts the iterator forward by the specified number of elements
  2666. MatConstIterator& operator += (ptrdiff_t ofs);
  2667. //! shifts the iterator backward by the specified number of elements
  2668. MatConstIterator& operator -= (ptrdiff_t ofs);
  2669. //! decrements the iterator
  2670. MatConstIterator& operator --();
  2671. //! decrements the iterator
  2672. MatConstIterator operator --(int);
  2673. //! increments the iterator
  2674. MatConstIterator& operator ++();
  2675. //! increments the iterator
  2676. MatConstIterator operator ++(int);
  2677. //! returns the current iterator position
  2678. Point pos() const;
  2679. //! returns the current iterator position
  2680. void pos(int* _idx) const;
  2681. ptrdiff_t lpos() const;
  2682. void seek(ptrdiff_t ofs, bool relative = false);
  2683. void seek(const int* _idx, bool relative = false);
  2684. const Mat* m;
  2685. size_t elemSize;
  2686. const uchar* ptr;
  2687. const uchar* sliceStart;
  2688. const uchar* sliceEnd;
  2689. };
  2690. ////////////////////////////////// MatConstIterator_ /////////////////////////////////
  2691. /** @brief Matrix read-only iterator
  2692. */
  2693. template<typename _Tp>
  2694. class MatConstIterator_ : public MatConstIterator
  2695. {
  2696. public:
  2697. typedef _Tp value_type;
  2698. typedef ptrdiff_t difference_type;
  2699. typedef const _Tp* pointer;
  2700. typedef const _Tp& reference;
  2701. typedef std::random_access_iterator_tag iterator_category;
  2702. //! default constructor
  2703. MatConstIterator_();
  2704. //! constructor that sets the iterator to the beginning of the matrix
  2705. MatConstIterator_(const Mat_<_Tp>* _m);
  2706. //! constructor that sets the iterator to the specified element of the matrix
  2707. MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col=0);
  2708. //! constructor that sets the iterator to the specified element of the matrix
  2709. MatConstIterator_(const Mat_<_Tp>* _m, Point _pt);
  2710. //! constructor that sets the iterator to the specified element of the matrix
  2711. MatConstIterator_(const Mat_<_Tp>* _m, const int* _idx);
  2712. //! copy constructor
  2713. MatConstIterator_(const MatConstIterator_& it);
  2714. //! copy operator
  2715. MatConstIterator_& operator = (const MatConstIterator_& it);
  2716. //! returns the current matrix element
  2717. const _Tp& operator *() const;
  2718. //! returns the i-th matrix element, relative to the current
  2719. const _Tp& operator [](ptrdiff_t i) const;
  2720. //! shifts the iterator forward by the specified number of elements
  2721. MatConstIterator_& operator += (ptrdiff_t ofs);
  2722. //! shifts the iterator backward by the specified number of elements
  2723. MatConstIterator_& operator -= (ptrdiff_t ofs);
  2724. //! decrements the iterator
  2725. MatConstIterator_& operator --();
  2726. //! decrements the iterator
  2727. MatConstIterator_ operator --(int);
  2728. //! increments the iterator
  2729. MatConstIterator_& operator ++();
  2730. //! increments the iterator
  2731. MatConstIterator_ operator ++(int);
  2732. //! returns the current iterator position
  2733. Point pos() const;
  2734. };
  2735. //////////////////////////////////// MatIterator_ ////////////////////////////////////
  2736. /** @brief Matrix read-write iterator
  2737. */
  2738. template<typename _Tp>
  2739. class MatIterator_ : public MatConstIterator_<_Tp>
  2740. {
  2741. public:
  2742. typedef _Tp* pointer;
  2743. typedef _Tp& reference;
  2744. typedef std::random_access_iterator_tag iterator_category;
  2745. //! the default constructor
  2746. MatIterator_();
  2747. //! constructor that sets the iterator to the beginning of the matrix
  2748. MatIterator_(Mat_<_Tp>* _m);
  2749. //! constructor that sets the iterator to the specified element of the matrix
  2750. MatIterator_(Mat_<_Tp>* _m, int _row, int _col=0);
  2751. //! constructor that sets the iterator to the specified element of the matrix
  2752. MatIterator_(Mat_<_Tp>* _m, Point _pt);
  2753. //! constructor that sets the iterator to the specified element of the matrix
  2754. MatIterator_(Mat_<_Tp>* _m, const int* _idx);
  2755. //! copy constructor
  2756. MatIterator_(const MatIterator_& it);
  2757. //! copy operator
  2758. MatIterator_& operator = (const MatIterator_<_Tp>& it );
  2759. //! returns the current matrix element
  2760. _Tp& operator *() const;
  2761. //! returns the i-th matrix element, relative to the current
  2762. _Tp& operator [](ptrdiff_t i) const;
  2763. //! shifts the iterator forward by the specified number of elements
  2764. MatIterator_& operator += (ptrdiff_t ofs);
  2765. //! shifts the iterator backward by the specified number of elements
  2766. MatIterator_& operator -= (ptrdiff_t ofs);
  2767. //! decrements the iterator
  2768. MatIterator_& operator --();
  2769. //! decrements the iterator
  2770. MatIterator_ operator --(int);
  2771. //! increments the iterator
  2772. MatIterator_& operator ++();
  2773. //! increments the iterator
  2774. MatIterator_ operator ++(int);
  2775. };
  2776. /////////////////////////////// SparseMatConstIterator ///////////////////////////////
  2777. /** @brief Read-Only Sparse Matrix Iterator.
  2778. Here is how to use the iterator to compute the sum of floating-point sparse matrix elements:
  2779. \code
  2780. SparseMatConstIterator it = m.begin(), it_end = m.end();
  2781. double s = 0;
  2782. CV_Assert( m.type() == CV_32F );
  2783. for( ; it != it_end; ++it )
  2784. s += it.value<float>();
  2785. \endcode
  2786. */
  2787. class CV_EXPORTS SparseMatConstIterator
  2788. {
  2789. public:
  2790. //! the default constructor
  2791. SparseMatConstIterator();
  2792. //! the full constructor setting the iterator to the first sparse matrix element
  2793. SparseMatConstIterator(const SparseMat* _m);
  2794. //! the copy constructor
  2795. SparseMatConstIterator(const SparseMatConstIterator& it);
  2796. //! the assignment operator
  2797. SparseMatConstIterator& operator = (const SparseMatConstIterator& it);
  2798. //! template method returning the current matrix element
  2799. template<typename _Tp> const _Tp& value() const;
  2800. //! returns the current node of the sparse matrix. it.node->idx is the current element index
  2801. const SparseMat::Node* node() const;
  2802. //! moves iterator to the previous element
  2803. SparseMatConstIterator& operator --();
  2804. //! moves iterator to the previous element
  2805. SparseMatConstIterator operator --(int);
  2806. //! moves iterator to the next element
  2807. SparseMatConstIterator& operator ++();
  2808. //! moves iterator to the next element
  2809. SparseMatConstIterator operator ++(int);
  2810. //! moves iterator to the element after the last element
  2811. void seekEnd();
  2812. const SparseMat* m;
  2813. size_t hashidx;
  2814. uchar* ptr;
  2815. };
  2816. ////////////////////////////////// SparseMatIterator /////////////////////////////////
  2817. /** @brief Read-write Sparse Matrix Iterator
  2818. The class is similar to cv::SparseMatConstIterator,
  2819. but can be used for in-place modification of the matrix elements.
  2820. */
  2821. class CV_EXPORTS SparseMatIterator : public SparseMatConstIterator
  2822. {
  2823. public:
  2824. //! the default constructor
  2825. SparseMatIterator();
  2826. //! the full constructor setting the iterator to the first sparse matrix element
  2827. SparseMatIterator(SparseMat* _m);
  2828. //! the full constructor setting the iterator to the specified sparse matrix element
  2829. SparseMatIterator(SparseMat* _m, const int* idx);
  2830. //! the copy constructor
  2831. SparseMatIterator(const SparseMatIterator& it);
  2832. //! the assignment operator
  2833. SparseMatIterator& operator = (const SparseMatIterator& it);
  2834. //! returns read-write reference to the current sparse matrix element
  2835. template<typename _Tp> _Tp& value() const;
  2836. //! returns pointer to the current sparse matrix node. it.node->idx is the index of the current element (do not modify it!)
  2837. SparseMat::Node* node() const;
  2838. //! moves iterator to the next element
  2839. SparseMatIterator& operator ++();
  2840. //! moves iterator to the next element
  2841. SparseMatIterator operator ++(int);
  2842. };
  2843. /////////////////////////////// SparseMatConstIterator_ //////////////////////////////
  2844. /** @brief Template Read-Only Sparse Matrix Iterator Class.
  2845. This is the derived from SparseMatConstIterator class that
  2846. introduces more convenient operator *() for accessing the current element.
  2847. */
  2848. template<typename _Tp> class SparseMatConstIterator_ : public SparseMatConstIterator
  2849. {
  2850. public:
  2851. typedef std::forward_iterator_tag iterator_category;
  2852. //! the default constructor
  2853. SparseMatConstIterator_();
  2854. //! the full constructor setting the iterator to the first sparse matrix element
  2855. SparseMatConstIterator_(const SparseMat_<_Tp>* _m);
  2856. SparseMatConstIterator_(const SparseMat* _m);
  2857. //! the copy constructor
  2858. SparseMatConstIterator_(const SparseMatConstIterator_& it);
  2859. //! the assignment operator
  2860. SparseMatConstIterator_& operator = (const SparseMatConstIterator_& it);
  2861. //! the element access operator
  2862. const _Tp& operator *() const;
  2863. //! moves iterator to the next element
  2864. SparseMatConstIterator_& operator ++();
  2865. //! moves iterator to the next element
  2866. SparseMatConstIterator_ operator ++(int);
  2867. };
  2868. ///////////////////////////////// SparseMatIterator_ /////////////////////////////////
  2869. /** @brief Template Read-Write Sparse Matrix Iterator Class.
  2870. This is the derived from cv::SparseMatConstIterator_ class that
  2871. introduces more convenient operator *() for accessing the current element.
  2872. */
  2873. template<typename _Tp> class SparseMatIterator_ : public SparseMatConstIterator_<_Tp>
  2874. {
  2875. public:
  2876. typedef std::forward_iterator_tag iterator_category;
  2877. //! the default constructor
  2878. SparseMatIterator_();
  2879. //! the full constructor setting the iterator to the first sparse matrix element
  2880. SparseMatIterator_(SparseMat_<_Tp>* _m);
  2881. SparseMatIterator_(SparseMat* _m);
  2882. //! the copy constructor
  2883. SparseMatIterator_(const SparseMatIterator_& it);
  2884. //! the assignment operator
  2885. SparseMatIterator_& operator = (const SparseMatIterator_& it);
  2886. //! returns the reference to the current element
  2887. _Tp& operator *() const;
  2888. //! moves the iterator to the next element
  2889. SparseMatIterator_& operator ++();
  2890. //! moves the iterator to the next element
  2891. SparseMatIterator_ operator ++(int);
  2892. };
  2893. /////////////////////////////////// NAryMatIterator //////////////////////////////////
  2894. /** @brief n-ary multi-dimensional array iterator.
  2895. Use the class to implement unary, binary, and, generally, n-ary element-wise operations on
  2896. multi-dimensional arrays. Some of the arguments of an n-ary function may be continuous arrays, some
  2897. may be not. It is possible to use conventional MatIterator 's for each array but incrementing all of
  2898. the iterators after each small operations may be a big overhead. In this case consider using
  2899. NAryMatIterator to iterate through several matrices simultaneously as long as they have the same
  2900. geometry (dimensionality and all the dimension sizes are the same). On each iteration `it.planes[0]`,
  2901. `it.planes[1]`,... will be the slices of the corresponding matrices.
  2902. The example below illustrates how you can compute a normalized and threshold 3D color histogram:
  2903. @code
  2904. void computeNormalizedColorHist(const Mat& image, Mat& hist, int N, double minProb)
  2905. {
  2906. const int histSize[] = {N, N, N};
  2907. // make sure that the histogram has a proper size and type
  2908. hist.create(3, histSize, CV_32F);
  2909. // and clear it
  2910. hist = Scalar(0);
  2911. // the loop below assumes that the image
  2912. // is a 8-bit 3-channel. check it.
  2913. CV_Assert(image.type() == CV_8UC3);
  2914. MatConstIterator_<Vec3b> it = image.begin<Vec3b>(),
  2915. it_end = image.end<Vec3b>();
  2916. for( ; it != it_end; ++it )
  2917. {
  2918. const Vec3b& pix = *it;
  2919. hist.at<float>(pix[0]*N/256, pix[1]*N/256, pix[2]*N/256) += 1.f;
  2920. }
  2921. minProb *= image.rows*image.cols;
  2922. // initialize iterator (the style is different from STL).
  2923. // after initialization the iterator will contain
  2924. // the number of slices or planes the iterator will go through.
  2925. // it simultaneously increments iterators for several matrices
  2926. // supplied as a null terminated list of pointers
  2927. const Mat* arrays[] = {&hist, 0};
  2928. Mat planes[1];
  2929. NAryMatIterator itNAry(arrays, planes, 1);
  2930. double s = 0;
  2931. // iterate through the matrix. on each iteration
  2932. // itNAry.planes[i] (of type Mat) will be set to the current plane
  2933. // of the i-th n-dim matrix passed to the iterator constructor.
  2934. for(int p = 0; p < itNAry.nplanes; p++, ++itNAry)
  2935. {
  2936. threshold(itNAry.planes[0], itNAry.planes[0], minProb, 0, THRESH_TOZERO);
  2937. s += sum(itNAry.planes[0])[0];
  2938. }
  2939. s = 1./s;
  2940. itNAry = NAryMatIterator(arrays, planes, 1);
  2941. for(int p = 0; p < itNAry.nplanes; p++, ++itNAry)
  2942. itNAry.planes[0] *= s;
  2943. }
  2944. @endcode
  2945. */
  2946. class CV_EXPORTS NAryMatIterator
  2947. {
  2948. public:
  2949. //! the default constructor
  2950. NAryMatIterator();
  2951. //! the full constructor taking arbitrary number of n-dim matrices
  2952. NAryMatIterator(const Mat** arrays, uchar** ptrs, int narrays=-1);
  2953. //! the full constructor taking arbitrary number of n-dim matrices
  2954. NAryMatIterator(const Mat** arrays, Mat* planes, int narrays=-1);
  2955. //! the separate iterator initialization method
  2956. void init(const Mat** arrays, Mat* planes, uchar** ptrs, int narrays=-1);
  2957. //! proceeds to the next plane of every iterated matrix
  2958. NAryMatIterator& operator ++();
  2959. //! proceeds to the next plane of every iterated matrix (postfix increment operator)
  2960. NAryMatIterator operator ++(int);
  2961. //! the iterated arrays
  2962. const Mat** arrays;
  2963. //! the current planes
  2964. Mat* planes;
  2965. //! data pointers
  2966. uchar** ptrs;
  2967. //! the number of arrays
  2968. int narrays;
  2969. //! the number of hyper-planes that the iterator steps through
  2970. size_t nplanes;
  2971. //! the size of each segment (in elements)
  2972. size_t size;
  2973. protected:
  2974. int iterdepth;
  2975. size_t idx;
  2976. };
  2977. ///////////////////////////////// Matrix Expressions /////////////////////////////////
  2978. class CV_EXPORTS MatOp
  2979. {
  2980. public:
  2981. MatOp();
  2982. virtual ~MatOp();
  2983. virtual bool elementWise(const MatExpr& expr) const;
  2984. virtual void assign(const MatExpr& expr, Mat& m, int type=-1) const = 0;
  2985. virtual void roi(const MatExpr& expr, const Range& rowRange,
  2986. const Range& colRange, MatExpr& res) const;
  2987. virtual void diag(const MatExpr& expr, int d, MatExpr& res) const;
  2988. virtual void augAssignAdd(const MatExpr& expr, Mat& m) const;
  2989. virtual void augAssignSubtract(const MatExpr& expr, Mat& m) const;
  2990. virtual void augAssignMultiply(const MatExpr& expr, Mat& m) const;
  2991. virtual void augAssignDivide(const MatExpr& expr, Mat& m) const;
  2992. virtual void augAssignAnd(const MatExpr& expr, Mat& m) const;
  2993. virtual void augAssignOr(const MatExpr& expr, Mat& m) const;
  2994. virtual void augAssignXor(const MatExpr& expr, Mat& m) const;
  2995. virtual void add(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
  2996. virtual void add(const MatExpr& expr1, const Scalar& s, MatExpr& res) const;
  2997. virtual void subtract(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
  2998. virtual void subtract(const Scalar& s, const MatExpr& expr, MatExpr& res) const;
  2999. virtual void multiply(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const;
  3000. virtual void multiply(const MatExpr& expr1, double s, MatExpr& res) const;
  3001. virtual void divide(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const;
  3002. virtual void divide(double s, const MatExpr& expr, MatExpr& res) const;
  3003. virtual void abs(const MatExpr& expr, MatExpr& res) const;
  3004. virtual void transpose(const MatExpr& expr, MatExpr& res) const;
  3005. virtual void matmul(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const;
  3006. virtual void invert(const MatExpr& expr, int method, MatExpr& res) const;
  3007. virtual Size size(const MatExpr& expr) const;
  3008. virtual int type(const MatExpr& expr) const;
  3009. };
  3010. /** @brief Matrix expression representation
  3011. @anchor MatrixExpressions
  3012. This is a list of implemented matrix operations that can be combined in arbitrary complex
  3013. expressions (here A, B stand for matrices ( Mat ), s for a scalar ( Scalar ), alpha for a
  3014. real-valued scalar ( double )):
  3015. - Addition, subtraction, negation: `A+B`, `A-B`, `A+s`, `A-s`, `s+A`, `s-A`, `-A`
  3016. - Scaling: `A*alpha`
  3017. - Per-element multiplication and division: `A.mul(B)`, `A/B`, `alpha/A`
  3018. - Matrix multiplication: `A*B`
  3019. - Transposition: `A.t()` (means A<sup>T</sup>)
  3020. - Matrix inversion and pseudo-inversion, solving linear systems and least-squares problems:
  3021. `A.inv([method]) (~ A<sup>-1</sup>)`, `A.inv([method])*B (~ X: AX=B)`
  3022. - Comparison: `A cmpop B`, `A cmpop alpha`, `alpha cmpop A`, where *cmpop* is one of
  3023. `>`, `>=`, `==`, `!=`, `<=`, `<`. The result of comparison is an 8-bit single channel mask whose
  3024. elements are set to 255 (if the particular element or pair of elements satisfy the condition) or
  3025. 0.
  3026. - Bitwise logical operations: `A logicop B`, `A logicop s`, `s logicop A`, `~A`, where *logicop* is one of
  3027. `&`, `|`, `^`.
  3028. - Element-wise minimum and maximum: `min(A, B)`, `min(A, alpha)`, `max(A, B)`, `max(A, alpha)`
  3029. - Element-wise absolute value: `abs(A)`
  3030. - Cross-product, dot-product: `A.cross(B)`, `A.dot(B)`
  3031. - Any function of matrix or matrices and scalars that returns a matrix or a scalar, such as norm,
  3032. mean, sum, countNonZero, trace, determinant, repeat, and others.
  3033. - Matrix initializers ( Mat::eye(), Mat::zeros(), Mat::ones() ), matrix comma-separated
  3034. initializers, matrix constructors and operators that extract sub-matrices (see Mat description).
  3035. - Mat_<destination_type>() constructors to cast the result to the proper type.
  3036. @note Comma-separated initializers and probably some other operations may require additional
  3037. explicit Mat() or Mat_<T>() constructor calls to resolve a possible ambiguity.
  3038. Here are examples of matrix expressions:
  3039. @code
  3040. // compute pseudo-inverse of A, equivalent to A.inv(DECOMP_SVD)
  3041. SVD svd(A);
  3042. Mat pinvA = svd.vt.t()*Mat::diag(1./svd.w)*svd.u.t();
  3043. // compute the new vector of parameters in the Levenberg-Marquardt algorithm
  3044. x -= (A.t()*A + lambda*Mat::eye(A.cols,A.cols,A.type())).inv(DECOMP_CHOLESKY)*(A.t()*err);
  3045. // sharpen image using "unsharp mask" algorithm
  3046. Mat blurred; double sigma = 1, threshold = 5, amount = 1;
  3047. GaussianBlur(img, blurred, Size(), sigma, sigma);
  3048. Mat lowContrastMask = abs(img - blurred) < threshold;
  3049. Mat sharpened = img*(1+amount) + blurred*(-amount);
  3050. img.copyTo(sharpened, lowContrastMask);
  3051. @endcode
  3052. */
  3053. class CV_EXPORTS MatExpr
  3054. {
  3055. public:
  3056. MatExpr();
  3057. explicit MatExpr(const Mat& m);
  3058. MatExpr(const MatOp* _op, int _flags, const Mat& _a = Mat(), const Mat& _b = Mat(),
  3059. const Mat& _c = Mat(), double _alpha = 1, double _beta = 1, const Scalar& _s = Scalar());
  3060. operator Mat() const;
  3061. template<typename _Tp> operator Mat_<_Tp>() const;
  3062. Size size() const;
  3063. int type() const;
  3064. MatExpr row(int y) const;
  3065. MatExpr col(int x) const;
  3066. MatExpr diag(int d = 0) const;
  3067. MatExpr operator()( const Range& rowRange, const Range& colRange ) const;
  3068. MatExpr operator()( const Rect& roi ) const;
  3069. MatExpr t() const;
  3070. MatExpr inv(int method = DECOMP_LU) const;
  3071. MatExpr mul(const MatExpr& e, double scale=1) const;
  3072. MatExpr mul(const Mat& m, double scale=1) const;
  3073. Mat cross(const Mat& m) const;
  3074. double dot(const Mat& m) const;
  3075. void swap(MatExpr& b);
  3076. const MatOp* op;
  3077. int flags;
  3078. Mat a, b, c;
  3079. double alpha, beta;
  3080. Scalar s;
  3081. };
  3082. //! @} core_basic
  3083. //! @relates cv::MatExpr
  3084. //! @{
  3085. CV_EXPORTS MatExpr operator + (const Mat& a, const Mat& b);
  3086. CV_EXPORTS MatExpr operator + (const Mat& a, const Scalar& s);
  3087. CV_EXPORTS MatExpr operator + (const Scalar& s, const Mat& a);
  3088. CV_EXPORTS MatExpr operator + (const MatExpr& e, const Mat& m);
  3089. CV_EXPORTS MatExpr operator + (const Mat& m, const MatExpr& e);
  3090. CV_EXPORTS MatExpr operator + (const MatExpr& e, const Scalar& s);
  3091. CV_EXPORTS MatExpr operator + (const Scalar& s, const MatExpr& e);
  3092. CV_EXPORTS MatExpr operator + (const MatExpr& e1, const MatExpr& e2);
  3093. template<typename _Tp, int m, int n> static inline
  3094. MatExpr operator + (const Mat& a, const Matx<_Tp, m, n>& b) { return a + Mat(b); }
  3095. template<typename _Tp, int m, int n> static inline
  3096. MatExpr operator + (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) + b; }
  3097. CV_EXPORTS MatExpr operator - (const Mat& a, const Mat& b);
  3098. CV_EXPORTS MatExpr operator - (const Mat& a, const Scalar& s);
  3099. CV_EXPORTS MatExpr operator - (const Scalar& s, const Mat& a);
  3100. CV_EXPORTS MatExpr operator - (const MatExpr& e, const Mat& m);
  3101. CV_EXPORTS MatExpr operator - (const Mat& m, const MatExpr& e);
  3102. CV_EXPORTS MatExpr operator - (const MatExpr& e, const Scalar& s);
  3103. CV_EXPORTS MatExpr operator - (const Scalar& s, const MatExpr& e);
  3104. CV_EXPORTS MatExpr operator - (const MatExpr& e1, const MatExpr& e2);
  3105. template<typename _Tp, int m, int n> static inline
  3106. MatExpr operator - (const Mat& a, const Matx<_Tp, m, n>& b) { return a - Mat(b); }
  3107. template<typename _Tp, int m, int n> static inline
  3108. MatExpr operator - (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) - b; }
  3109. CV_EXPORTS MatExpr operator - (const Mat& m);
  3110. CV_EXPORTS MatExpr operator - (const MatExpr& e);
  3111. CV_EXPORTS MatExpr operator * (const Mat& a, const Mat& b);
  3112. CV_EXPORTS MatExpr operator * (const Mat& a, double s);
  3113. CV_EXPORTS MatExpr operator * (double s, const Mat& a);
  3114. CV_EXPORTS MatExpr operator * (const MatExpr& e, const Mat& m);
  3115. CV_EXPORTS MatExpr operator * (const Mat& m, const MatExpr& e);
  3116. CV_EXPORTS MatExpr operator * (const MatExpr& e, double s);
  3117. CV_EXPORTS MatExpr operator * (double s, const MatExpr& e);
  3118. CV_EXPORTS MatExpr operator * (const MatExpr& e1, const MatExpr& e2);
  3119. template<typename _Tp, int m, int n> static inline
  3120. MatExpr operator * (const Mat& a, const Matx<_Tp, m, n>& b) { return a * Mat(b); }
  3121. template<typename _Tp, int m, int n> static inline
  3122. MatExpr operator * (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) * b; }
  3123. CV_EXPORTS MatExpr operator / (const Mat& a, const Mat& b);
  3124. CV_EXPORTS MatExpr operator / (const Mat& a, double s);
  3125. CV_EXPORTS MatExpr operator / (double s, const Mat& a);
  3126. CV_EXPORTS MatExpr operator / (const MatExpr& e, const Mat& m);
  3127. CV_EXPORTS MatExpr operator / (const Mat& m, const MatExpr& e);
  3128. CV_EXPORTS MatExpr operator / (const MatExpr& e, double s);
  3129. CV_EXPORTS MatExpr operator / (double s, const MatExpr& e);
  3130. CV_EXPORTS MatExpr operator / (const MatExpr& e1, const MatExpr& e2);
  3131. template<typename _Tp, int m, int n> static inline
  3132. MatExpr operator / (const Mat& a, const Matx<_Tp, m, n>& b) { return a / Mat(b); }
  3133. template<typename _Tp, int m, int n> static inline
  3134. MatExpr operator / (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) / b; }
  3135. CV_EXPORTS MatExpr operator < (const Mat& a, const Mat& b);
  3136. CV_EXPORTS MatExpr operator < (const Mat& a, double s);
  3137. CV_EXPORTS MatExpr operator < (double s, const Mat& a);
  3138. template<typename _Tp, int m, int n> static inline
  3139. MatExpr operator < (const Mat& a, const Matx<_Tp, m, n>& b) { return a < Mat(b); }
  3140. template<typename _Tp, int m, int n> static inline
  3141. MatExpr operator < (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) < b; }
  3142. CV_EXPORTS MatExpr operator <= (const Mat& a, const Mat& b);
  3143. CV_EXPORTS MatExpr operator <= (const Mat& a, double s);
  3144. CV_EXPORTS MatExpr operator <= (double s, const Mat& a);
  3145. template<typename _Tp, int m, int n> static inline
  3146. MatExpr operator <= (const Mat& a, const Matx<_Tp, m, n>& b) { return a <= Mat(b); }
  3147. template<typename _Tp, int m, int n> static inline
  3148. MatExpr operator <= (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) <= b; }
  3149. CV_EXPORTS MatExpr operator == (const Mat& a, const Mat& b);
  3150. CV_EXPORTS MatExpr operator == (const Mat& a, double s);
  3151. CV_EXPORTS MatExpr operator == (double s, const Mat& a);
  3152. template<typename _Tp, int m, int n> static inline
  3153. MatExpr operator == (const Mat& a, const Matx<_Tp, m, n>& b) { return a == Mat(b); }
  3154. template<typename _Tp, int m, int n> static inline
  3155. MatExpr operator == (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) == b; }
  3156. CV_EXPORTS MatExpr operator != (const Mat& a, const Mat& b);
  3157. CV_EXPORTS MatExpr operator != (const Mat& a, double s);
  3158. CV_EXPORTS MatExpr operator != (double s, const Mat& a);
  3159. template<typename _Tp, int m, int n> static inline
  3160. MatExpr operator != (const Mat& a, const Matx<_Tp, m, n>& b) { return a != Mat(b); }
  3161. template<typename _Tp, int m, int n> static inline
  3162. MatExpr operator != (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) != b; }
  3163. CV_EXPORTS MatExpr operator >= (const Mat& a, const Mat& b);
  3164. CV_EXPORTS MatExpr operator >= (const Mat& a, double s);
  3165. CV_EXPORTS MatExpr operator >= (double s, const Mat& a);
  3166. template<typename _Tp, int m, int n> static inline
  3167. MatExpr operator >= (const Mat& a, const Matx<_Tp, m, n>& b) { return a >= Mat(b); }
  3168. template<typename _Tp, int m, int n> static inline
  3169. MatExpr operator >= (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) >= b; }
  3170. CV_EXPORTS MatExpr operator > (const Mat& a, const Mat& b);
  3171. CV_EXPORTS MatExpr operator > (const Mat& a, double s);
  3172. CV_EXPORTS MatExpr operator > (double s, const Mat& a);
  3173. template<typename _Tp, int m, int n> static inline
  3174. MatExpr operator > (const Mat& a, const Matx<_Tp, m, n>& b) { return a > Mat(b); }
  3175. template<typename _Tp, int m, int n> static inline
  3176. MatExpr operator > (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) > b; }
  3177. CV_EXPORTS MatExpr operator & (const Mat& a, const Mat& b);
  3178. CV_EXPORTS MatExpr operator & (const Mat& a, const Scalar& s);
  3179. CV_EXPORTS MatExpr operator & (const Scalar& s, const Mat& a);
  3180. template<typename _Tp, int m, int n> static inline
  3181. MatExpr operator & (const Mat& a, const Matx<_Tp, m, n>& b) { return a & Mat(b); }
  3182. template<typename _Tp, int m, int n> static inline
  3183. MatExpr operator & (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) & b; }
  3184. CV_EXPORTS MatExpr operator | (const Mat& a, const Mat& b);
  3185. CV_EXPORTS MatExpr operator | (const Mat& a, const Scalar& s);
  3186. CV_EXPORTS MatExpr operator | (const Scalar& s, const Mat& a);
  3187. template<typename _Tp, int m, int n> static inline
  3188. MatExpr operator | (const Mat& a, const Matx<_Tp, m, n>& b) { return a | Mat(b); }
  3189. template<typename _Tp, int m, int n> static inline
  3190. MatExpr operator | (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) | b; }
  3191. CV_EXPORTS MatExpr operator ^ (const Mat& a, const Mat& b);
  3192. CV_EXPORTS MatExpr operator ^ (const Mat& a, const Scalar& s);
  3193. CV_EXPORTS MatExpr operator ^ (const Scalar& s, const Mat& a);
  3194. template<typename _Tp, int m, int n> static inline
  3195. MatExpr operator ^ (const Mat& a, const Matx<_Tp, m, n>& b) { return a ^ Mat(b); }
  3196. template<typename _Tp, int m, int n> static inline
  3197. MatExpr operator ^ (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) ^ b; }
  3198. CV_EXPORTS MatExpr operator ~(const Mat& m);
  3199. CV_EXPORTS MatExpr min(const Mat& a, const Mat& b);
  3200. CV_EXPORTS MatExpr min(const Mat& a, double s);
  3201. CV_EXPORTS MatExpr min(double s, const Mat& a);
  3202. template<typename _Tp, int m, int n> static inline
  3203. MatExpr min (const Mat& a, const Matx<_Tp, m, n>& b) { return min(a, Mat(b)); }
  3204. template<typename _Tp, int m, int n> static inline
  3205. MatExpr min (const Matx<_Tp, m, n>& a, const Mat& b) { return min(Mat(a), b); }
  3206. CV_EXPORTS MatExpr max(const Mat& a, const Mat& b);
  3207. CV_EXPORTS MatExpr max(const Mat& a, double s);
  3208. CV_EXPORTS MatExpr max(double s, const Mat& a);
  3209. template<typename _Tp, int m, int n> static inline
  3210. MatExpr max (const Mat& a, const Matx<_Tp, m, n>& b) { return max(a, Mat(b)); }
  3211. template<typename _Tp, int m, int n> static inline
  3212. MatExpr max (const Matx<_Tp, m, n>& a, const Mat& b) { return max(Mat(a), b); }
  3213. /** @brief Calculates an absolute value of each matrix element.
  3214. abs is a meta-function that is expanded to one of absdiff or convertScaleAbs forms:
  3215. - C = abs(A-B) is equivalent to `absdiff(A, B, C)`
  3216. - C = abs(A) is equivalent to `absdiff(A, Scalar::all(0), C)`
  3217. - C = `Mat_<Vec<uchar,n> >(abs(A*alpha + beta))` is equivalent to `convertScaleAbs(A, C, alpha,
  3218. beta)`
  3219. The output matrix has the same size and the same type as the input one except for the last case,
  3220. where C is depth=CV_8U .
  3221. @param m matrix.
  3222. @sa @ref MatrixExpressions, absdiff, convertScaleAbs
  3223. */
  3224. CV_EXPORTS MatExpr abs(const Mat& m);
  3225. /** @overload
  3226. @param e matrix expression.
  3227. */
  3228. CV_EXPORTS MatExpr abs(const MatExpr& e);
  3229. //! @} relates cv::MatExpr
  3230. } // cv
  3231. #include "opencv2/core/mat.inl.hpp"
  3232. #endif // OPENCV_CORE_MAT_HPP