mat.hpp 162 KB

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