mat.hpp 152 KB

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