mat.hpp 161 KB

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