mat.hpp 159 KB

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