mat.hpp 163 KB

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