calib3d.hpp 213 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044
  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_CALIB3D_HPP
  44. #define OPENCV_CALIB3D_HPP
  45. #include "opencv2/core.hpp"
  46. #include "opencv2/core/types.hpp"
  47. #include "opencv2/features2d.hpp"
  48. #include "opencv2/core/affine.hpp"
  49. /**
  50. @defgroup calib3d Camera Calibration and 3D Reconstruction
  51. The functions in this section use a so-called pinhole camera model. The view of a scene
  52. is obtained by projecting a scene's 3D point \f$P_w\f$ into the image plane using a perspective
  53. transformation which forms the corresponding pixel \f$p\f$. Both \f$P_w\f$ and \f$p\f$ are
  54. represented in homogeneous coordinates, i.e. as 3D and 2D homogeneous vector respectively. You will
  55. find a brief introduction to projective geometry, homogeneous vectors and homogeneous
  56. transformations at the end of this section's introduction. For more succinct notation, we often drop
  57. the 'homogeneous' and say vector instead of homogeneous vector.
  58. The distortion-free projective transformation given by a pinhole camera model is shown below.
  59. \f[s \; p = A \begin{bmatrix} R|t \end{bmatrix} P_w,\f]
  60. where \f$P_w\f$ is a 3D point expressed with respect to the world coordinate system,
  61. \f$p\f$ is a 2D pixel in the image plane, \f$A\f$ is the camera intrinsic matrix,
  62. \f$R\f$ and \f$t\f$ are the rotation and translation that describe the change of coordinates from
  63. world to camera coordinate systems (or camera frame) and \f$s\f$ is the projective transformation's
  64. arbitrary scaling and not part of the camera model.
  65. The camera intrinsic matrix \f$A\f$ (notation used as in @cite Zhang2000 and also generally notated
  66. as \f$K\f$) projects 3D points given in the camera coordinate system to 2D pixel coordinates, i.e.
  67. \f[p = A P_c.\f]
  68. The camera intrinsic matrix \f$A\f$ is composed of the focal lengths \f$f_x\f$ and \f$f_y\f$, which are
  69. expressed in pixel units, and the principal point \f$(c_x, c_y)\f$, that is usually close to the
  70. image center:
  71. \f[A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1},\f]
  72. and thus
  73. \f[s \vecthree{u}{v}{1} = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1} \vecthree{X_c}{Y_c}{Z_c}.\f]
  74. The matrix of intrinsic parameters does not depend on the scene viewed. So, once estimated, it can
  75. be re-used as long as the focal length is fixed (in case of a zoom lens). Thus, if an image from the
  76. camera is scaled by a factor, all of these parameters need to be scaled (multiplied/divided,
  77. respectively) by the same factor.
  78. The joint rotation-translation matrix \f$[R|t]\f$ is the matrix product of a projective
  79. transformation and a homogeneous transformation. The 3-by-4 projective transformation maps 3D points
  80. represented in camera coordinates to 2D points in the image plane and represented in normalized
  81. camera coordinates \f$x' = X_c / Z_c\f$ and \f$y' = Y_c / Z_c\f$:
  82. \f[Z_c \begin{bmatrix}
  83. x' \\
  84. y' \\
  85. 1
  86. \end{bmatrix} = \begin{bmatrix}
  87. 1 & 0 & 0 & 0 \\
  88. 0 & 1 & 0 & 0 \\
  89. 0 & 0 & 1 & 0
  90. \end{bmatrix}
  91. \begin{bmatrix}
  92. X_c \\
  93. Y_c \\
  94. Z_c \\
  95. 1
  96. \end{bmatrix}.\f]
  97. The homogeneous transformation is encoded by the extrinsic parameters \f$R\f$ and \f$t\f$ and
  98. represents the change of basis from world coordinate system \f$w\f$ to the camera coordinate sytem
  99. \f$c\f$. Thus, given the representation of the point \f$P\f$ in world coordinates, \f$P_w\f$, we
  100. obtain \f$P\f$'s representation in the camera coordinate system, \f$P_c\f$, by
  101. \f[P_c = \begin{bmatrix}
  102. R & t \\
  103. 0 & 1
  104. \end{bmatrix} P_w,\f]
  105. This homogeneous transformation is composed out of \f$R\f$, a 3-by-3 rotation matrix, and \f$t\f$, a
  106. 3-by-1 translation vector:
  107. \f[\begin{bmatrix}
  108. R & t \\
  109. 0 & 1
  110. \end{bmatrix} = \begin{bmatrix}
  111. r_{11} & r_{12} & r_{13} & t_x \\
  112. r_{21} & r_{22} & r_{23} & t_y \\
  113. r_{31} & r_{32} & r_{33} & t_z \\
  114. 0 & 0 & 0 & 1
  115. \end{bmatrix},
  116. \f]
  117. and therefore
  118. \f[\begin{bmatrix}
  119. X_c \\
  120. Y_c \\
  121. Z_c \\
  122. 1
  123. \end{bmatrix} = \begin{bmatrix}
  124. r_{11} & r_{12} & r_{13} & t_x \\
  125. r_{21} & r_{22} & r_{23} & t_y \\
  126. r_{31} & r_{32} & r_{33} & t_z \\
  127. 0 & 0 & 0 & 1
  128. \end{bmatrix}
  129. \begin{bmatrix}
  130. X_w \\
  131. Y_w \\
  132. Z_w \\
  133. 1
  134. \end{bmatrix}.\f]
  135. Combining the projective transformation and the homogeneous transformation, we obtain the projective
  136. transformation that maps 3D points in world coordinates into 2D points in the image plane and in
  137. normalized camera coordinates:
  138. \f[Z_c \begin{bmatrix}
  139. x' \\
  140. y' \\
  141. 1
  142. \end{bmatrix} = \begin{bmatrix} R|t \end{bmatrix} \begin{bmatrix}
  143. X_w \\
  144. Y_w \\
  145. Z_w \\
  146. 1
  147. \end{bmatrix} = \begin{bmatrix}
  148. r_{11} & r_{12} & r_{13} & t_x \\
  149. r_{21} & r_{22} & r_{23} & t_y \\
  150. r_{31} & r_{32} & r_{33} & t_z
  151. \end{bmatrix}
  152. \begin{bmatrix}
  153. X_w \\
  154. Y_w \\
  155. Z_w \\
  156. 1
  157. \end{bmatrix},\f]
  158. with \f$x' = X_c / Z_c\f$ and \f$y' = Y_c / Z_c\f$. Putting the equations for instrincs and extrinsics together, we can write out
  159. \f$s \; p = A \begin{bmatrix} R|t \end{bmatrix} P_w\f$ as
  160. \f[s \vecthree{u}{v}{1} = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}
  161. \begin{bmatrix}
  162. r_{11} & r_{12} & r_{13} & t_x \\
  163. r_{21} & r_{22} & r_{23} & t_y \\
  164. r_{31} & r_{32} & r_{33} & t_z
  165. \end{bmatrix}
  166. \begin{bmatrix}
  167. X_w \\
  168. Y_w \\
  169. Z_w \\
  170. 1
  171. \end{bmatrix}.\f]
  172. If \f$Z_c \ne 0\f$, the transformation above is equivalent to the following,
  173. \f[\begin{bmatrix}
  174. u \\
  175. v
  176. \end{bmatrix} = \begin{bmatrix}
  177. f_x X_c/Z_c + c_x \\
  178. f_y Y_c/Z_c + c_y
  179. \end{bmatrix}\f]
  180. with
  181. \f[\vecthree{X_c}{Y_c}{Z_c} = \begin{bmatrix}
  182. R|t
  183. \end{bmatrix} \begin{bmatrix}
  184. X_w \\
  185. Y_w \\
  186. Z_w \\
  187. 1
  188. \end{bmatrix}.\f]
  189. The following figure illustrates the pinhole camera model.
  190. ![Pinhole camera model](pics/pinhole_camera_model.png)
  191. Real lenses usually have some distortion, mostly radial distortion, and slight tangential distortion.
  192. So, the above model is extended as:
  193. \f[\begin{bmatrix}
  194. u \\
  195. v
  196. \end{bmatrix} = \begin{bmatrix}
  197. f_x x'' + c_x \\
  198. f_y y'' + c_y
  199. \end{bmatrix}\f]
  200. where
  201. \f[\begin{bmatrix}
  202. x'' \\
  203. y''
  204. \end{bmatrix} = \begin{bmatrix}
  205. x' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} + 2 p_1 x' y' + p_2(r^2 + 2 x'^2) + s_1 r^2 + s_2 r^4 \\
  206. y' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} + p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' + s_3 r^2 + s_4 r^4 \\
  207. \end{bmatrix}\f]
  208. with
  209. \f[r^2 = x'^2 + y'^2\f]
  210. and
  211. \f[\begin{bmatrix}
  212. x'\\
  213. y'
  214. \end{bmatrix} = \begin{bmatrix}
  215. X_c/Z_c \\
  216. Y_c/Z_c
  217. \end{bmatrix},\f]
  218. if \f$Z_c \ne 0\f$.
  219. The distortion parameters are the radial coefficients \f$k_1\f$, \f$k_2\f$, \f$k_3\f$, \f$k_4\f$, \f$k_5\f$, and \f$k_6\f$
  220. ,\f$p_1\f$ and \f$p_2\f$ are the tangential distortion coefficients, and \f$s_1\f$, \f$s_2\f$, \f$s_3\f$, and \f$s_4\f$,
  221. are the thin prism distortion coefficients. Higher-order coefficients are not considered in OpenCV.
  222. The next figures show two common types of radial distortion: barrel distortion
  223. (\f$ 1 + k_1 r^2 + k_2 r^4 + k_3 r^6 \f$ monotonically decreasing)
  224. and pincushion distortion (\f$ 1 + k_1 r^2 + k_2 r^4 + k_3 r^6 \f$ monotonically increasing).
  225. Radial distortion is always monotonic for real lenses,
  226. and if the estimator produces a non-monotonic result,
  227. this should be considered a calibration failure.
  228. More generally, radial distortion must be monotonic and the distortion function must be bijective.
  229. A failed estimation result may look deceptively good near the image center
  230. but will work poorly in e.g. AR/SFM applications.
  231. The optimization method used in OpenCV camera calibration does not include these constraints as
  232. the framework does not support the required integer programming and polynomial inequalities.
  233. See [issue #15992](https://github.com/opencv/opencv/issues/15992) for additional information.
  234. ![](pics/distortion_examples.png)
  235. ![](pics/distortion_examples2.png)
  236. In some cases, the image sensor may be tilted in order to focus an oblique plane in front of the
  237. camera (Scheimpflug principle). This can be useful for particle image velocimetry (PIV) or
  238. triangulation with a laser fan. The tilt causes a perspective distortion of \f$x''\f$ and
  239. \f$y''\f$. This distortion can be modeled in the following way, see e.g. @cite Louhichi07.
  240. \f[\begin{bmatrix}
  241. u \\
  242. v
  243. \end{bmatrix} = \begin{bmatrix}
  244. f_x x''' + c_x \\
  245. f_y y''' + c_y
  246. \end{bmatrix},\f]
  247. where
  248. \f[s\vecthree{x'''}{y'''}{1} =
  249. \vecthreethree{R_{33}(\tau_x, \tau_y)}{0}{-R_{13}(\tau_x, \tau_y)}
  250. {0}{R_{33}(\tau_x, \tau_y)}{-R_{23}(\tau_x, \tau_y)}
  251. {0}{0}{1} R(\tau_x, \tau_y) \vecthree{x''}{y''}{1}\f]
  252. and the matrix \f$R(\tau_x, \tau_y)\f$ is defined by two rotations with angular parameter
  253. \f$\tau_x\f$ and \f$\tau_y\f$, respectively,
  254. \f[
  255. R(\tau_x, \tau_y) =
  256. \vecthreethree{\cos(\tau_y)}{0}{-\sin(\tau_y)}{0}{1}{0}{\sin(\tau_y)}{0}{\cos(\tau_y)}
  257. \vecthreethree{1}{0}{0}{0}{\cos(\tau_x)}{\sin(\tau_x)}{0}{-\sin(\tau_x)}{\cos(\tau_x)} =
  258. \vecthreethree{\cos(\tau_y)}{\sin(\tau_y)\sin(\tau_x)}{-\sin(\tau_y)\cos(\tau_x)}
  259. {0}{\cos(\tau_x)}{\sin(\tau_x)}
  260. {\sin(\tau_y)}{-\cos(\tau_y)\sin(\tau_x)}{\cos(\tau_y)\cos(\tau_x)}.
  261. \f]
  262. In the functions below the coefficients are passed or returned as
  263. \f[(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f]
  264. vector. That is, if the vector contains four elements, it means that \f$k_3=0\f$ . The distortion
  265. coefficients do not depend on the scene viewed. Thus, they also belong to the intrinsic camera
  266. parameters. And they remain the same regardless of the captured image resolution. If, for example, a
  267. camera has been calibrated on images of 320 x 240 resolution, absolutely the same distortion
  268. coefficients can be used for 640 x 480 images from the same camera while \f$f_x\f$, \f$f_y\f$,
  269. \f$c_x\f$, and \f$c_y\f$ need to be scaled appropriately.
  270. The functions below use the above model to do the following:
  271. - Project 3D points to the image plane given intrinsic and extrinsic parameters.
  272. - Compute extrinsic parameters given intrinsic parameters, a few 3D points, and their
  273. projections.
  274. - Estimate intrinsic and extrinsic camera parameters from several views of a known calibration
  275. pattern (every view is described by several 3D-2D point correspondences).
  276. - Estimate the relative position and orientation of the stereo camera "heads" and compute the
  277. *rectification* transformation that makes the camera optical axes parallel.
  278. <B> Homogeneous Coordinates </B><br>
  279. Homogeneous Coordinates are a system of coordinates that are used in projective geometry. Their use
  280. allows to represent points at infinity by finite coordinates and simplifies formulas when compared
  281. to the cartesian counterparts, e.g. they have the advantage that affine transformations can be
  282. expressed as linear homogeneous transformation.
  283. One obtains the homogeneous vector \f$P_h\f$ by appending a 1 along an n-dimensional cartesian
  284. vector \f$P\f$ e.g. for a 3D cartesian vector the mapping \f$P \rightarrow P_h\f$ is:
  285. \f[\begin{bmatrix}
  286. X \\
  287. Y \\
  288. Z
  289. \end{bmatrix} \rightarrow \begin{bmatrix}
  290. X \\
  291. Y \\
  292. Z \\
  293. 1
  294. \end{bmatrix}.\f]
  295. For the inverse mapping \f$P_h \rightarrow P\f$, one divides all elements of the homogeneous vector
  296. by its last element, e.g. for a 3D homogeneous vector one gets its 2D cartesian counterpart by:
  297. \f[\begin{bmatrix}
  298. X \\
  299. Y \\
  300. W
  301. \end{bmatrix} \rightarrow \begin{bmatrix}
  302. X / W \\
  303. Y / W
  304. \end{bmatrix},\f]
  305. if \f$W \ne 0\f$.
  306. Due to this mapping, all multiples \f$k P_h\f$, for \f$k \ne 0\f$, of a homogeneous point represent
  307. the same point \f$P_h\f$. An intuitive understanding of this property is that under a projective
  308. transformation, all multiples of \f$P_h\f$ are mapped to the same point. This is the physical
  309. observation one does for pinhole cameras, as all points along a ray through the camera's pinhole are
  310. projected to the same image point, e.g. all points along the red ray in the image of the pinhole
  311. camera model above would be mapped to the same image coordinate. This property is also the source
  312. for the scale ambiguity s in the equation of the pinhole camera model.
  313. As mentioned, by using homogeneous coordinates we can express any change of basis parameterized by
  314. \f$R\f$ and \f$t\f$ as a linear transformation, e.g. for the change of basis from coordinate system
  315. 0 to coordinate system 1 becomes:
  316. \f[P_1 = R P_0 + t \rightarrow P_{h_1} = \begin{bmatrix}
  317. R & t \\
  318. 0 & 1
  319. \end{bmatrix} P_{h_0}.\f]
  320. @note
  321. - Many functions in this module take a camera intrinsic matrix as an input parameter. Although all
  322. functions assume the same structure of this parameter, they may name it differently. The
  323. parameter's description, however, will be clear in that a camera intrinsic matrix with the structure
  324. shown above is required.
  325. - A calibration sample for 3 cameras in a horizontal position can be found at
  326. opencv_source_code/samples/cpp/3calibration.cpp
  327. - A calibration sample based on a sequence of images can be found at
  328. opencv_source_code/samples/cpp/calibration.cpp
  329. - A calibration sample in order to do 3D reconstruction can be found at
  330. opencv_source_code/samples/cpp/build3dmodel.cpp
  331. - A calibration example on stereo calibration can be found at
  332. opencv_source_code/samples/cpp/stereo_calib.cpp
  333. - A calibration example on stereo matching can be found at
  334. opencv_source_code/samples/cpp/stereo_match.cpp
  335. - (Python) A camera calibration sample can be found at
  336. opencv_source_code/samples/python/calibrate.py
  337. @{
  338. @defgroup calib3d_fisheye Fisheye camera model
  339. Definitions: Let P be a point in 3D of coordinates X in the world reference frame (stored in the
  340. matrix X) The coordinate vector of P in the camera reference frame is:
  341. \f[Xc = R X + T\f]
  342. where R is the rotation matrix corresponding to the rotation vector om: R = rodrigues(om); call x, y
  343. and z the 3 coordinates of Xc:
  344. \f[x = Xc_1 \\ y = Xc_2 \\ z = Xc_3\f]
  345. The pinhole projection coordinates of P is [a; b] where
  346. \f[a = x / z \ and \ b = y / z \\ r^2 = a^2 + b^2 \\ \theta = atan(r)\f]
  347. Fisheye distortion:
  348. \f[\theta_d = \theta (1 + k_1 \theta^2 + k_2 \theta^4 + k_3 \theta^6 + k_4 \theta^8)\f]
  349. The distorted point coordinates are [x'; y'] where
  350. \f[x' = (\theta_d / r) a \\ y' = (\theta_d / r) b \f]
  351. Finally, conversion into pixel coordinates: The final pixel coordinates vector [u; v] where:
  352. \f[u = f_x (x' + \alpha y') + c_x \\
  353. v = f_y y' + c_y\f]
  354. Summary:
  355. Generic camera model @cite Kannala2006 with perspective projection and without distortion correction
  356. @defgroup calib3d_c C API
  357. @}
  358. */
  359. namespace cv
  360. {
  361. //! @addtogroup calib3d
  362. //! @{
  363. //! type of the robust estimation algorithm
  364. enum { LMEDS = 4, //!< least-median of squares algorithm
  365. RANSAC = 8, //!< RANSAC algorithm
  366. RHO = 16, //!< RHO algorithm
  367. USAC_DEFAULT = 32, //!< USAC algorithm, default settings
  368. USAC_PARALLEL = 33, //!< USAC, parallel version
  369. USAC_FM_8PTS = 34, //!< USAC, fundamental matrix 8 points
  370. USAC_FAST = 35, //!< USAC, fast settings
  371. USAC_ACCURATE = 36, //!< USAC, accurate settings
  372. USAC_PROSAC = 37, //!< USAC, sorted points, runs PROSAC
  373. USAC_MAGSAC = 38 //!< USAC, runs MAGSAC++
  374. };
  375. enum SolvePnPMethod {
  376. SOLVEPNP_ITERATIVE = 0, //!< Pose refinement using non-linear Levenberg-Marquardt minimization scheme @cite Madsen04 @cite Eade13 \n
  377. //!< Initial solution for non-planar "objectPoints" needs at least 6 points and uses the DLT algorithm. \n
  378. //!< Initial solution for planar "objectPoints" needs at least 4 points and uses pose from homography decomposition.
  379. SOLVEPNP_EPNP = 1, //!< EPnP: Efficient Perspective-n-Point Camera Pose Estimation @cite lepetit2009epnp
  380. SOLVEPNP_P3P = 2, //!< Complete Solution Classification for the Perspective-Three-Point Problem @cite gao2003complete
  381. SOLVEPNP_DLS = 3, //!< **Broken implementation. Using this flag will fallback to EPnP.** \n
  382. //!< A Direct Least-Squares (DLS) Method for PnP @cite hesch2011direct
  383. SOLVEPNP_UPNP = 4, //!< **Broken implementation. Using this flag will fallback to EPnP.** \n
  384. //!< Exhaustive Linearization for Robust Camera Pose and Focal Length Estimation @cite penate2013exhaustive
  385. SOLVEPNP_AP3P = 5, //!< An Efficient Algebraic Solution to the Perspective-Three-Point Problem @cite Ke17
  386. SOLVEPNP_IPPE = 6, //!< Infinitesimal Plane-Based Pose Estimation @cite Collins14 \n
  387. //!< Object points must be coplanar.
  388. SOLVEPNP_IPPE_SQUARE = 7, //!< Infinitesimal Plane-Based Pose Estimation @cite Collins14 \n
  389. //!< This is a special case suitable for marker pose estimation.\n
  390. //!< 4 coplanar object points must be defined in the following order:
  391. //!< - point 0: [-squareLength / 2, squareLength / 2, 0]
  392. //!< - point 1: [ squareLength / 2, squareLength / 2, 0]
  393. //!< - point 2: [ squareLength / 2, -squareLength / 2, 0]
  394. //!< - point 3: [-squareLength / 2, -squareLength / 2, 0]
  395. SOLVEPNP_SQPNP = 8, //!< SQPnP: A Consistently Fast and Globally OptimalSolution to the Perspective-n-Point Problem @cite Terzakis2020SQPnP
  396. #ifndef CV_DOXYGEN
  397. SOLVEPNP_MAX_COUNT //!< Used for count
  398. #endif
  399. };
  400. enum { CALIB_CB_ADAPTIVE_THRESH = 1,
  401. CALIB_CB_NORMALIZE_IMAGE = 2,
  402. CALIB_CB_FILTER_QUADS = 4,
  403. CALIB_CB_FAST_CHECK = 8,
  404. CALIB_CB_EXHAUSTIVE = 16,
  405. CALIB_CB_ACCURACY = 32,
  406. CALIB_CB_LARGER = 64,
  407. CALIB_CB_MARKER = 128
  408. };
  409. enum { CALIB_CB_SYMMETRIC_GRID = 1,
  410. CALIB_CB_ASYMMETRIC_GRID = 2,
  411. CALIB_CB_CLUSTERING = 4
  412. };
  413. enum { CALIB_NINTRINSIC = 18,
  414. CALIB_USE_INTRINSIC_GUESS = 0x00001,
  415. CALIB_FIX_ASPECT_RATIO = 0x00002,
  416. CALIB_FIX_PRINCIPAL_POINT = 0x00004,
  417. CALIB_ZERO_TANGENT_DIST = 0x00008,
  418. CALIB_FIX_FOCAL_LENGTH = 0x00010,
  419. CALIB_FIX_K1 = 0x00020,
  420. CALIB_FIX_K2 = 0x00040,
  421. CALIB_FIX_K3 = 0x00080,
  422. CALIB_FIX_K4 = 0x00800,
  423. CALIB_FIX_K5 = 0x01000,
  424. CALIB_FIX_K6 = 0x02000,
  425. CALIB_RATIONAL_MODEL = 0x04000,
  426. CALIB_THIN_PRISM_MODEL = 0x08000,
  427. CALIB_FIX_S1_S2_S3_S4 = 0x10000,
  428. CALIB_TILTED_MODEL = 0x40000,
  429. CALIB_FIX_TAUX_TAUY = 0x80000,
  430. CALIB_USE_QR = 0x100000, //!< use QR instead of SVD decomposition for solving. Faster but potentially less precise
  431. CALIB_FIX_TANGENT_DIST = 0x200000,
  432. // only for stereo
  433. CALIB_FIX_INTRINSIC = 0x00100,
  434. CALIB_SAME_FOCAL_LENGTH = 0x00200,
  435. // for stereo rectification
  436. CALIB_ZERO_DISPARITY = 0x00400,
  437. CALIB_USE_LU = (1 << 17), //!< use LU instead of SVD decomposition for solving. much faster but potentially less precise
  438. CALIB_USE_EXTRINSIC_GUESS = (1 << 22) //!< for stereoCalibrate
  439. };
  440. //! the algorithm for finding fundamental matrix
  441. enum { FM_7POINT = 1, //!< 7-point algorithm
  442. FM_8POINT = 2, //!< 8-point algorithm
  443. FM_LMEDS = 4, //!< least-median algorithm. 7-point algorithm is used.
  444. FM_RANSAC = 8 //!< RANSAC algorithm. It needs at least 15 points. 7-point algorithm is used.
  445. };
  446. enum HandEyeCalibrationMethod
  447. {
  448. CALIB_HAND_EYE_TSAI = 0, //!< A New Technique for Fully Autonomous and Efficient 3D Robotics Hand/Eye Calibration @cite Tsai89
  449. CALIB_HAND_EYE_PARK = 1, //!< Robot Sensor Calibration: Solving AX = XB on the Euclidean Group @cite Park94
  450. CALIB_HAND_EYE_HORAUD = 2, //!< Hand-eye Calibration @cite Horaud95
  451. CALIB_HAND_EYE_ANDREFF = 3, //!< On-line Hand-Eye Calibration @cite Andreff99
  452. CALIB_HAND_EYE_DANIILIDIS = 4 //!< Hand-Eye Calibration Using Dual Quaternions @cite Daniilidis98
  453. };
  454. enum RobotWorldHandEyeCalibrationMethod
  455. {
  456. CALIB_ROBOT_WORLD_HAND_EYE_SHAH = 0, //!< Solving the robot-world/hand-eye calibration problem using the kronecker product @cite Shah2013SolvingTR
  457. CALIB_ROBOT_WORLD_HAND_EYE_LI = 1 //!< Simultaneous robot-world and hand-eye calibration using dual-quaternions and kronecker product @cite Li2010SimultaneousRA
  458. };
  459. enum SamplingMethod { SAMPLING_UNIFORM, SAMPLING_PROGRESSIVE_NAPSAC, SAMPLING_NAPSAC,
  460. SAMPLING_PROSAC };
  461. enum LocalOptimMethod {LOCAL_OPTIM_NULL, LOCAL_OPTIM_INNER_LO, LOCAL_OPTIM_INNER_AND_ITER_LO,
  462. LOCAL_OPTIM_GC, LOCAL_OPTIM_SIGMA};
  463. enum ScoreMethod {SCORE_METHOD_RANSAC, SCORE_METHOD_MSAC, SCORE_METHOD_MAGSAC, SCORE_METHOD_LMEDS};
  464. enum NeighborSearchMethod { NEIGH_FLANN_KNN, NEIGH_GRID, NEIGH_FLANN_RADIUS };
  465. struct CV_EXPORTS_W_SIMPLE UsacParams
  466. { // in alphabetical order
  467. CV_WRAP UsacParams();
  468. CV_PROP_RW double confidence;
  469. CV_PROP_RW bool isParallel;
  470. CV_PROP_RW int loIterations;
  471. CV_PROP_RW LocalOptimMethod loMethod;
  472. CV_PROP_RW int loSampleSize;
  473. CV_PROP_RW int maxIterations;
  474. CV_PROP_RW NeighborSearchMethod neighborsSearch;
  475. CV_PROP_RW int randomGeneratorState;
  476. CV_PROP_RW SamplingMethod sampler;
  477. CV_PROP_RW ScoreMethod score;
  478. CV_PROP_RW double threshold;
  479. };
  480. /** @brief Converts a rotation matrix to a rotation vector or vice versa.
  481. @param src Input rotation vector (3x1 or 1x3) or rotation matrix (3x3).
  482. @param dst Output rotation matrix (3x3) or rotation vector (3x1 or 1x3), respectively.
  483. @param jacobian Optional output Jacobian matrix, 3x9 or 9x3, which is a matrix of partial
  484. derivatives of the output array components with respect to the input array components.
  485. \f[\begin{array}{l} \theta \leftarrow norm(r) \\ r \leftarrow r/ \theta \\ R = \cos(\theta) I + (1- \cos{\theta} ) r r^T + \sin(\theta) \vecthreethree{0}{-r_z}{r_y}{r_z}{0}{-r_x}{-r_y}{r_x}{0} \end{array}\f]
  486. Inverse transformation can be also done easily, since
  487. \f[\sin ( \theta ) \vecthreethree{0}{-r_z}{r_y}{r_z}{0}{-r_x}{-r_y}{r_x}{0} = \frac{R - R^T}{2}\f]
  488. A rotation vector is a convenient and most compact representation of a rotation matrix (since any
  489. rotation matrix has just 3 degrees of freedom). The representation is used in the global 3D geometry
  490. optimization procedures like @ref calibrateCamera, @ref stereoCalibrate, or @ref solvePnP .
  491. @note More information about the computation of the derivative of a 3D rotation matrix with respect to its exponential coordinate
  492. can be found in:
  493. - A Compact Formula for the Derivative of a 3-D Rotation in Exponential Coordinates, Guillermo Gallego, Anthony J. Yezzi @cite Gallego2014ACF
  494. @note Useful information on SE(3) and Lie Groups can be found in:
  495. - A tutorial on SE(3) transformation parameterizations and on-manifold optimization, Jose-Luis Blanco @cite blanco2010tutorial
  496. - Lie Groups for 2D and 3D Transformation, Ethan Eade @cite Eade17
  497. - A micro Lie theory for state estimation in robotics, Joan Solà, Jérémie Deray, Dinesh Atchuthan @cite Sol2018AML
  498. */
  499. CV_EXPORTS_W void Rodrigues( InputArray src, OutputArray dst, OutputArray jacobian = noArray() );
  500. /** Levenberg-Marquardt solver. Starting with the specified vector of parameters it
  501. optimizes the target vector criteria "err"
  502. (finds local minima of each target vector component absolute value).
  503. When needed, it calls user-provided callback.
  504. */
  505. class CV_EXPORTS LMSolver : public Algorithm
  506. {
  507. public:
  508. class CV_EXPORTS Callback
  509. {
  510. public:
  511. virtual ~Callback() {}
  512. /**
  513. computes error and Jacobian for the specified vector of parameters
  514. @param param the current vector of parameters
  515. @param err output vector of errors: err_i = actual_f_i - ideal_f_i
  516. @param J output Jacobian: J_ij = d(err_i)/d(param_j)
  517. when J=noArray(), it means that it does not need to be computed.
  518. Dimensionality of error vector and param vector can be different.
  519. The callback should explicitly allocate (with "create" method) each output array
  520. (unless it's noArray()).
  521. */
  522. virtual bool compute(InputArray param, OutputArray err, OutputArray J) const = 0;
  523. };
  524. /**
  525. Runs Levenberg-Marquardt algorithm using the passed vector of parameters as the start point.
  526. The final vector of parameters (whether the algorithm converged or not) is stored at the same
  527. vector. The method returns the number of iterations used. If it's equal to the previously specified
  528. maxIters, there is a big chance the algorithm did not converge.
  529. @param param initial/final vector of parameters.
  530. Note that the dimensionality of parameter space is defined by the size of param vector,
  531. and the dimensionality of optimized criteria is defined by the size of err vector
  532. computed by the callback.
  533. */
  534. virtual int run(InputOutputArray param) const = 0;
  535. /**
  536. Sets the maximum number of iterations
  537. @param maxIters the number of iterations
  538. */
  539. virtual void setMaxIters(int maxIters) = 0;
  540. /**
  541. Retrieves the current maximum number of iterations
  542. */
  543. virtual int getMaxIters() const = 0;
  544. /**
  545. Creates Levenberg-Marquard solver
  546. @param cb callback
  547. @param maxIters maximum number of iterations that can be further
  548. modified using setMaxIters() method.
  549. */
  550. static Ptr<LMSolver> create(const Ptr<LMSolver::Callback>& cb, int maxIters);
  551. static Ptr<LMSolver> create(const Ptr<LMSolver::Callback>& cb, int maxIters, double eps);
  552. };
  553. /** @example samples/cpp/tutorial_code/features2D/Homography/pose_from_homography.cpp
  554. An example program about pose estimation from coplanar points
  555. Check @ref tutorial_homography "the corresponding tutorial" for more details
  556. */
  557. /** @brief Finds a perspective transformation between two planes.
  558. @param srcPoints Coordinates of the points in the original plane, a matrix of the type CV_32FC2
  559. or vector\<Point2f\> .
  560. @param dstPoints Coordinates of the points in the target plane, a matrix of the type CV_32FC2 or
  561. a vector\<Point2f\> .
  562. @param method Method used to compute a homography matrix. The following methods are possible:
  563. - **0** - a regular method using all the points, i.e., the least squares method
  564. - @ref RANSAC - RANSAC-based robust method
  565. - @ref LMEDS - Least-Median robust method
  566. - @ref RHO - PROSAC-based robust method
  567. @param ransacReprojThreshold Maximum allowed reprojection error to treat a point pair as an inlier
  568. (used in the RANSAC and RHO methods only). That is, if
  569. \f[\| \texttt{dstPoints} _i - \texttt{convertPointsHomogeneous} ( \texttt{H} * \texttt{srcPoints} _i) \|_2 > \texttt{ransacReprojThreshold}\f]
  570. then the point \f$i\f$ is considered as an outlier. If srcPoints and dstPoints are measured in pixels,
  571. it usually makes sense to set this parameter somewhere in the range of 1 to 10.
  572. @param mask Optional output mask set by a robust method ( RANSAC or LMeDS ). Note that the input
  573. mask values are ignored.
  574. @param maxIters The maximum number of RANSAC iterations.
  575. @param confidence Confidence level, between 0 and 1.
  576. The function finds and returns the perspective transformation \f$H\f$ between the source and the
  577. destination planes:
  578. \f[s_i \vecthree{x'_i}{y'_i}{1} \sim H \vecthree{x_i}{y_i}{1}\f]
  579. so that the back-projection error
  580. \f[\sum _i \left ( x'_i- \frac{h_{11} x_i + h_{12} y_i + h_{13}}{h_{31} x_i + h_{32} y_i + h_{33}} \right )^2+ \left ( y'_i- \frac{h_{21} x_i + h_{22} y_i + h_{23}}{h_{31} x_i + h_{32} y_i + h_{33}} \right )^2\f]
  581. is minimized. If the parameter method is set to the default value 0, the function uses all the point
  582. pairs to compute an initial homography estimate with a simple least-squares scheme.
  583. However, if not all of the point pairs ( \f$srcPoints_i\f$, \f$dstPoints_i\f$ ) fit the rigid perspective
  584. transformation (that is, there are some outliers), this initial estimate will be poor. In this case,
  585. you can use one of the three robust methods. The methods RANSAC, LMeDS and RHO try many different
  586. random subsets of the corresponding point pairs (of four pairs each, collinear pairs are discarded), estimate the homography matrix
  587. using this subset and a simple least-squares algorithm, and then compute the quality/goodness of the
  588. computed homography (which is the number of inliers for RANSAC or the least median re-projection error for
  589. LMeDS). The best subset is then used to produce the initial estimate of the homography matrix and
  590. the mask of inliers/outliers.
  591. Regardless of the method, robust or not, the computed homography matrix is refined further (using
  592. inliers only in case of a robust method) with the Levenberg-Marquardt method to reduce the
  593. re-projection error even more.
  594. The methods RANSAC and RHO can handle practically any ratio of outliers but need a threshold to
  595. distinguish inliers from outliers. The method LMeDS does not need any threshold but it works
  596. correctly only when there are more than 50% of inliers. Finally, if there are no outliers and the
  597. noise is rather small, use the default method (method=0).
  598. The function is used to find initial intrinsic and extrinsic matrices. Homography matrix is
  599. determined up to a scale. Thus, it is normalized so that \f$h_{33}=1\f$. Note that whenever an \f$H\f$ matrix
  600. cannot be estimated, an empty one will be returned.
  601. @sa
  602. getAffineTransform, estimateAffine2D, estimateAffinePartial2D, getPerspectiveTransform, warpPerspective,
  603. perspectiveTransform
  604. */
  605. CV_EXPORTS_W Mat findHomography( InputArray srcPoints, InputArray dstPoints,
  606. int method = 0, double ransacReprojThreshold = 3,
  607. OutputArray mask=noArray(), const int maxIters = 2000,
  608. const double confidence = 0.995);
  609. /** @overload */
  610. CV_EXPORTS Mat findHomography( InputArray srcPoints, InputArray dstPoints,
  611. OutputArray mask, int method = 0, double ransacReprojThreshold = 3 );
  612. CV_EXPORTS_W Mat findHomography(InputArray srcPoints, InputArray dstPoints, OutputArray mask,
  613. const UsacParams &params);
  614. /** @brief Computes an RQ decomposition of 3x3 matrices.
  615. @param src 3x3 input matrix.
  616. @param mtxR Output 3x3 upper-triangular matrix.
  617. @param mtxQ Output 3x3 orthogonal matrix.
  618. @param Qx Optional output 3x3 rotation matrix around x-axis.
  619. @param Qy Optional output 3x3 rotation matrix around y-axis.
  620. @param Qz Optional output 3x3 rotation matrix around z-axis.
  621. The function computes a RQ decomposition using the given rotations. This function is used in
  622. #decomposeProjectionMatrix to decompose the left 3x3 submatrix of a projection matrix into a camera
  623. and a rotation matrix.
  624. It optionally returns three rotation matrices, one for each axis, and the three Euler angles in
  625. degrees (as the return value) that could be used in OpenGL. Note, there is always more than one
  626. sequence of rotations about the three principal axes that results in the same orientation of an
  627. object, e.g. see @cite Slabaugh . Returned tree rotation matrices and corresponding three Euler angles
  628. are only one of the possible solutions.
  629. */
  630. CV_EXPORTS_W Vec3d RQDecomp3x3( InputArray src, OutputArray mtxR, OutputArray mtxQ,
  631. OutputArray Qx = noArray(),
  632. OutputArray Qy = noArray(),
  633. OutputArray Qz = noArray());
  634. /** @brief Decomposes a projection matrix into a rotation matrix and a camera intrinsic matrix.
  635. @param projMatrix 3x4 input projection matrix P.
  636. @param cameraMatrix Output 3x3 camera intrinsic matrix \f$\cameramatrix{A}\f$.
  637. @param rotMatrix Output 3x3 external rotation matrix R.
  638. @param transVect Output 4x1 translation vector T.
  639. @param rotMatrixX Optional 3x3 rotation matrix around x-axis.
  640. @param rotMatrixY Optional 3x3 rotation matrix around y-axis.
  641. @param rotMatrixZ Optional 3x3 rotation matrix around z-axis.
  642. @param eulerAngles Optional three-element vector containing three Euler angles of rotation in
  643. degrees.
  644. The function computes a decomposition of a projection matrix into a calibration and a rotation
  645. matrix and the position of a camera.
  646. It optionally returns three rotation matrices, one for each axis, and three Euler angles that could
  647. be used in OpenGL. Note, there is always more than one sequence of rotations about the three
  648. principal axes that results in the same orientation of an object, e.g. see @cite Slabaugh . Returned
  649. tree rotation matrices and corresponding three Euler angles are only one of the possible solutions.
  650. The function is based on RQDecomp3x3 .
  651. */
  652. CV_EXPORTS_W void decomposeProjectionMatrix( InputArray projMatrix, OutputArray cameraMatrix,
  653. OutputArray rotMatrix, OutputArray transVect,
  654. OutputArray rotMatrixX = noArray(),
  655. OutputArray rotMatrixY = noArray(),
  656. OutputArray rotMatrixZ = noArray(),
  657. OutputArray eulerAngles =noArray() );
  658. /** @brief Computes partial derivatives of the matrix product for each multiplied matrix.
  659. @param A First multiplied matrix.
  660. @param B Second multiplied matrix.
  661. @param dABdA First output derivative matrix d(A\*B)/dA of size
  662. \f$\texttt{A.rows*B.cols} \times {A.rows*A.cols}\f$ .
  663. @param dABdB Second output derivative matrix d(A\*B)/dB of size
  664. \f$\texttt{A.rows*B.cols} \times {B.rows*B.cols}\f$ .
  665. The function computes partial derivatives of the elements of the matrix product \f$A*B\f$ with regard to
  666. the elements of each of the two input matrices. The function is used to compute the Jacobian
  667. matrices in #stereoCalibrate but can also be used in any other similar optimization function.
  668. */
  669. CV_EXPORTS_W void matMulDeriv( InputArray A, InputArray B, OutputArray dABdA, OutputArray dABdB );
  670. /** @brief Combines two rotation-and-shift transformations.
  671. @param rvec1 First rotation vector.
  672. @param tvec1 First translation vector.
  673. @param rvec2 Second rotation vector.
  674. @param tvec2 Second translation vector.
  675. @param rvec3 Output rotation vector of the superposition.
  676. @param tvec3 Output translation vector of the superposition.
  677. @param dr3dr1 Optional output derivative of rvec3 with regard to rvec1
  678. @param dr3dt1 Optional output derivative of rvec3 with regard to tvec1
  679. @param dr3dr2 Optional output derivative of rvec3 with regard to rvec2
  680. @param dr3dt2 Optional output derivative of rvec3 with regard to tvec2
  681. @param dt3dr1 Optional output derivative of tvec3 with regard to rvec1
  682. @param dt3dt1 Optional output derivative of tvec3 with regard to tvec1
  683. @param dt3dr2 Optional output derivative of tvec3 with regard to rvec2
  684. @param dt3dt2 Optional output derivative of tvec3 with regard to tvec2
  685. The functions compute:
  686. \f[\begin{array}{l} \texttt{rvec3} = \mathrm{rodrigues} ^{-1} \left ( \mathrm{rodrigues} ( \texttt{rvec2} ) \cdot \mathrm{rodrigues} ( \texttt{rvec1} ) \right ) \\ \texttt{tvec3} = \mathrm{rodrigues} ( \texttt{rvec2} ) \cdot \texttt{tvec1} + \texttt{tvec2} \end{array} ,\f]
  687. where \f$\mathrm{rodrigues}\f$ denotes a rotation vector to a rotation matrix transformation, and
  688. \f$\mathrm{rodrigues}^{-1}\f$ denotes the inverse transformation. See Rodrigues for details.
  689. Also, the functions can compute the derivatives of the output vectors with regards to the input
  690. vectors (see matMulDeriv ). The functions are used inside #stereoCalibrate but can also be used in
  691. your own code where Levenberg-Marquardt or another gradient-based solver is used to optimize a
  692. function that contains a matrix multiplication.
  693. */
  694. CV_EXPORTS_W void composeRT( InputArray rvec1, InputArray tvec1,
  695. InputArray rvec2, InputArray tvec2,
  696. OutputArray rvec3, OutputArray tvec3,
  697. OutputArray dr3dr1 = noArray(), OutputArray dr3dt1 = noArray(),
  698. OutputArray dr3dr2 = noArray(), OutputArray dr3dt2 = noArray(),
  699. OutputArray dt3dr1 = noArray(), OutputArray dt3dt1 = noArray(),
  700. OutputArray dt3dr2 = noArray(), OutputArray dt3dt2 = noArray() );
  701. /** @brief Projects 3D points to an image plane.
  702. @param objectPoints Array of object points expressed wrt. the world coordinate frame. A 3xN/Nx3
  703. 1-channel or 1xN/Nx1 3-channel (or vector\<Point3f\> ), where N is the number of points in the view.
  704. @param rvec The rotation vector (@ref Rodrigues) that, together with tvec, performs a change of
  705. basis from world to camera coordinate system, see @ref calibrateCamera for details.
  706. @param tvec The translation vector, see parameter description above.
  707. @param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ .
  708. @param distCoeffs Input vector of distortion coefficients
  709. \f$\distcoeffs\f$ . If the vector is empty, the zero distortion coefficients are assumed.
  710. @param imagePoints Output array of image points, 1xN/Nx1 2-channel, or
  711. vector\<Point2f\> .
  712. @param jacobian Optional output 2Nx(10+\<numDistCoeffs\>) jacobian matrix of derivatives of image
  713. points with respect to components of the rotation vector, translation vector, focal lengths,
  714. coordinates of the principal point and the distortion coefficients. In the old interface different
  715. components of the jacobian are returned via different output parameters.
  716. @param aspectRatio Optional "fixed aspect ratio" parameter. If the parameter is not 0, the
  717. function assumes that the aspect ratio (\f$f_x / f_y\f$) is fixed and correspondingly adjusts the
  718. jacobian matrix.
  719. The function computes the 2D projections of 3D points to the image plane, given intrinsic and
  720. extrinsic camera parameters. Optionally, the function computes Jacobians -matrices of partial
  721. derivatives of image points coordinates (as functions of all the input parameters) with respect to
  722. the particular parameters, intrinsic and/or extrinsic. The Jacobians are used during the global
  723. optimization in @ref calibrateCamera, @ref solvePnP, and @ref stereoCalibrate. The function itself
  724. can also be used to compute a re-projection error, given the current intrinsic and extrinsic
  725. parameters.
  726. @note By setting rvec = tvec = \f$[0, 0, 0]\f$, or by setting cameraMatrix to a 3x3 identity matrix,
  727. or by passing zero distortion coefficients, one can get various useful partial cases of the
  728. function. This means, one can compute the distorted coordinates for a sparse set of points or apply
  729. a perspective transformation (and also compute the derivatives) in the ideal zero-distortion setup.
  730. */
  731. CV_EXPORTS_W void projectPoints( InputArray objectPoints,
  732. InputArray rvec, InputArray tvec,
  733. InputArray cameraMatrix, InputArray distCoeffs,
  734. OutputArray imagePoints,
  735. OutputArray jacobian = noArray(),
  736. double aspectRatio = 0 );
  737. /** @example samples/cpp/tutorial_code/features2D/Homography/homography_from_camera_displacement.cpp
  738. An example program about homography from the camera displacement
  739. Check @ref tutorial_homography "the corresponding tutorial" for more details
  740. */
  741. /** @brief Finds an object pose from 3D-2D point correspondences.
  742. @see @ref calib3d_solvePnP
  743. This function returns the rotation and the translation vectors that transform a 3D point expressed in the object
  744. coordinate frame to the camera coordinate frame, using different methods:
  745. - P3P methods (@ref SOLVEPNP_P3P, @ref SOLVEPNP_AP3P): need 4 input points to return a unique solution.
  746. - @ref SOLVEPNP_IPPE Input points must be >= 4 and object points must be coplanar.
  747. - @ref SOLVEPNP_IPPE_SQUARE Special case suitable for marker pose estimation.
  748. Number of input points must be 4. Object points must be defined in the following order:
  749. - point 0: [-squareLength / 2, squareLength / 2, 0]
  750. - point 1: [ squareLength / 2, squareLength / 2, 0]
  751. - point 2: [ squareLength / 2, -squareLength / 2, 0]
  752. - point 3: [-squareLength / 2, -squareLength / 2, 0]
  753. - for all the other flags, number of input points must be >= 4 and object points can be in any configuration.
  754. @param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or
  755. 1xN/Nx1 3-channel, where N is the number of points. vector\<Point3d\> can be also passed here.
  756. @param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel,
  757. where N is the number of points. vector\<Point2d\> can be also passed here.
  758. @param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
  759. @param distCoeffs Input vector of distortion coefficients
  760. \f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
  761. assumed.
  762. @param rvec Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from
  763. the model coordinate system to the camera coordinate system.
  764. @param tvec Output translation vector.
  765. @param useExtrinsicGuess Parameter used for #SOLVEPNP_ITERATIVE. If true (1), the function uses
  766. the provided rvec and tvec values as initial approximations of the rotation and translation
  767. vectors, respectively, and further optimizes them.
  768. @param flags Method for solving a PnP problem: see @ref calib3d_solvePnP_flags
  769. More information about Perspective-n-Points is described in @ref calib3d_solvePnP
  770. @note
  771. - An example of how to use solvePnP for planar augmented reality can be found at
  772. opencv_source_code/samples/python/plane_ar.py
  773. - If you are using Python:
  774. - Numpy array slices won't work as input because solvePnP requires contiguous
  775. arrays (enforced by the assertion using cv::Mat::checkVector() around line 55 of
  776. modules/calib3d/src/solvepnp.cpp version 2.4.9)
  777. - The P3P algorithm requires image points to be in an array of shape (N,1,2) due
  778. to its calling of #undistortPoints (around line 75 of modules/calib3d/src/solvepnp.cpp version 2.4.9)
  779. which requires 2-channel information.
  780. - Thus, given some data D = np.array(...) where D.shape = (N,M), in order to use a subset of
  781. it as, e.g., imagePoints, one must effectively copy it into a new array: imagePoints =
  782. np.ascontiguousarray(D[:,:2]).reshape((N,1,2))
  783. - The methods @ref SOLVEPNP_DLS and @ref SOLVEPNP_UPNP cannot be used as the current implementations are
  784. unstable and sometimes give completely wrong results. If you pass one of these two
  785. flags, @ref SOLVEPNP_EPNP method will be used instead.
  786. - The minimum number of points is 4 in the general case. In the case of @ref SOLVEPNP_P3P and @ref SOLVEPNP_AP3P
  787. methods, it is required to use exactly 4 points (the first 3 points are used to estimate all the solutions
  788. of the P3P problem, the last one is used to retain the best solution that minimizes the reprojection error).
  789. - With @ref SOLVEPNP_ITERATIVE method and `useExtrinsicGuess=true`, the minimum number of points is 3 (3 points
  790. are sufficient to compute a pose but there are up to 4 solutions). The initial solution should be close to the
  791. global solution to converge.
  792. - With @ref SOLVEPNP_IPPE input points must be >= 4 and object points must be coplanar.
  793. - With @ref SOLVEPNP_IPPE_SQUARE this is a special case suitable for marker pose estimation.
  794. Number of input points must be 4. Object points must be defined in the following order:
  795. - point 0: [-squareLength / 2, squareLength / 2, 0]
  796. - point 1: [ squareLength / 2, squareLength / 2, 0]
  797. - point 2: [ squareLength / 2, -squareLength / 2, 0]
  798. - point 3: [-squareLength / 2, -squareLength / 2, 0]
  799. - With @ref SOLVEPNP_SQPNP input points must be >= 3
  800. */
  801. CV_EXPORTS_W bool solvePnP( InputArray objectPoints, InputArray imagePoints,
  802. InputArray cameraMatrix, InputArray distCoeffs,
  803. OutputArray rvec, OutputArray tvec,
  804. bool useExtrinsicGuess = false, int flags = SOLVEPNP_ITERATIVE );
  805. /** @brief Finds an object pose from 3D-2D point correspondences using the RANSAC scheme.
  806. @see @ref calib3d_solvePnP
  807. @param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or
  808. 1xN/Nx1 3-channel, where N is the number of points. vector\<Point3d\> can be also passed here.
  809. @param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel,
  810. where N is the number of points. vector\<Point2d\> can be also passed here.
  811. @param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
  812. @param distCoeffs Input vector of distortion coefficients
  813. \f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
  814. assumed.
  815. @param rvec Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from
  816. the model coordinate system to the camera coordinate system.
  817. @param tvec Output translation vector.
  818. @param useExtrinsicGuess Parameter used for @ref SOLVEPNP_ITERATIVE. If true (1), the function uses
  819. the provided rvec and tvec values as initial approximations of the rotation and translation
  820. vectors, respectively, and further optimizes them.
  821. @param iterationsCount Number of iterations.
  822. @param reprojectionError Inlier threshold value used by the RANSAC procedure. The parameter value
  823. is the maximum allowed distance between the observed and computed point projections to consider it
  824. an inlier.
  825. @param confidence The probability that the algorithm produces a useful result.
  826. @param inliers Output vector that contains indices of inliers in objectPoints and imagePoints .
  827. @param flags Method for solving a PnP problem (see @ref solvePnP ).
  828. The function estimates an object pose given a set of object points, their corresponding image
  829. projections, as well as the camera intrinsic matrix and the distortion coefficients. This function finds such
  830. a pose that minimizes reprojection error, that is, the sum of squared distances between the observed
  831. projections imagePoints and the projected (using @ref projectPoints ) objectPoints. The use of RANSAC
  832. makes the function resistant to outliers.
  833. @note
  834. - An example of how to use solvePNPRansac for object detection can be found at
  835. opencv_source_code/samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/
  836. - The default method used to estimate the camera pose for the Minimal Sample Sets step
  837. is #SOLVEPNP_EPNP. Exceptions are:
  838. - if you choose #SOLVEPNP_P3P or #SOLVEPNP_AP3P, these methods will be used.
  839. - if the number of input points is equal to 4, #SOLVEPNP_P3P is used.
  840. - The method used to estimate the camera pose using all the inliers is defined by the
  841. flags parameters unless it is equal to #SOLVEPNP_P3P or #SOLVEPNP_AP3P. In this case,
  842. the method #SOLVEPNP_EPNP will be used instead.
  843. */
  844. CV_EXPORTS_W bool solvePnPRansac( InputArray objectPoints, InputArray imagePoints,
  845. InputArray cameraMatrix, InputArray distCoeffs,
  846. OutputArray rvec, OutputArray tvec,
  847. bool useExtrinsicGuess = false, int iterationsCount = 100,
  848. float reprojectionError = 8.0, double confidence = 0.99,
  849. OutputArray inliers = noArray(), int flags = SOLVEPNP_ITERATIVE );
  850. /*
  851. Finds rotation and translation vector.
  852. If cameraMatrix is given then run P3P. Otherwise run linear P6P and output cameraMatrix too.
  853. */
  854. CV_EXPORTS_W bool solvePnPRansac( InputArray objectPoints, InputArray imagePoints,
  855. InputOutputArray cameraMatrix, InputArray distCoeffs,
  856. OutputArray rvec, OutputArray tvec, OutputArray inliers,
  857. const UsacParams &params=UsacParams());
  858. /** @brief Finds an object pose from 3 3D-2D point correspondences.
  859. @see @ref calib3d_solvePnP
  860. @param objectPoints Array of object points in the object coordinate space, 3x3 1-channel or
  861. 1x3/3x1 3-channel. vector\<Point3f\> can be also passed here.
  862. @param imagePoints Array of corresponding image points, 3x2 1-channel or 1x3/3x1 2-channel.
  863. vector\<Point2f\> can be also passed here.
  864. @param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
  865. @param distCoeffs Input vector of distortion coefficients
  866. \f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
  867. assumed.
  868. @param rvecs Output rotation vectors (see @ref Rodrigues ) that, together with tvecs, brings points from
  869. the model coordinate system to the camera coordinate system. A P3P problem has up to 4 solutions.
  870. @param tvecs Output translation vectors.
  871. @param flags Method for solving a P3P problem:
  872. - @ref SOLVEPNP_P3P Method is based on the paper of X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang
  873. "Complete Solution Classification for the Perspective-Three-Point Problem" (@cite gao2003complete).
  874. - @ref SOLVEPNP_AP3P Method is based on the paper of T. Ke and S. Roumeliotis.
  875. "An Efficient Algebraic Solution to the Perspective-Three-Point Problem" (@cite Ke17).
  876. The function estimates the object pose given 3 object points, their corresponding image
  877. projections, as well as the camera intrinsic matrix and the distortion coefficients.
  878. @note
  879. The solutions are sorted by reprojection errors (lowest to highest).
  880. */
  881. CV_EXPORTS_W int solveP3P( InputArray objectPoints, InputArray imagePoints,
  882. InputArray cameraMatrix, InputArray distCoeffs,
  883. OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs,
  884. int flags );
  885. /** @brief Refine a pose (the translation and the rotation that transform a 3D point expressed in the object coordinate frame
  886. to the camera coordinate frame) from a 3D-2D point correspondences and starting from an initial solution.
  887. @see @ref calib3d_solvePnP
  888. @param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or 1xN/Nx1 3-channel,
  889. where N is the number of points. vector\<Point3d\> can also be passed here.
  890. @param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel,
  891. where N is the number of points. vector\<Point2d\> can also be passed here.
  892. @param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
  893. @param distCoeffs Input vector of distortion coefficients
  894. \f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
  895. assumed.
  896. @param rvec Input/Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from
  897. the model coordinate system to the camera coordinate system. Input values are used as an initial solution.
  898. @param tvec Input/Output translation vector. Input values are used as an initial solution.
  899. @param criteria Criteria when to stop the Levenberg-Marquard iterative algorithm.
  900. The function refines the object pose given at least 3 object points, their corresponding image
  901. projections, an initial solution for the rotation and translation vector,
  902. as well as the camera intrinsic matrix and the distortion coefficients.
  903. The function minimizes the projection error with respect to the rotation and the translation vectors, according
  904. to a Levenberg-Marquardt iterative minimization @cite Madsen04 @cite Eade13 process.
  905. */
  906. CV_EXPORTS_W void solvePnPRefineLM( InputArray objectPoints, InputArray imagePoints,
  907. InputArray cameraMatrix, InputArray distCoeffs,
  908. InputOutputArray rvec, InputOutputArray tvec,
  909. TermCriteria criteria = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 20, FLT_EPSILON));
  910. /** @brief Refine a pose (the translation and the rotation that transform a 3D point expressed in the object coordinate frame
  911. to the camera coordinate frame) from a 3D-2D point correspondences and starting from an initial solution.
  912. @see @ref calib3d_solvePnP
  913. @param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or 1xN/Nx1 3-channel,
  914. where N is the number of points. vector\<Point3d\> can also be passed here.
  915. @param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel,
  916. where N is the number of points. vector\<Point2d\> can also be passed here.
  917. @param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
  918. @param distCoeffs Input vector of distortion coefficients
  919. \f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
  920. assumed.
  921. @param rvec Input/Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from
  922. the model coordinate system to the camera coordinate system. Input values are used as an initial solution.
  923. @param tvec Input/Output translation vector. Input values are used as an initial solution.
  924. @param criteria Criteria when to stop the Levenberg-Marquard iterative algorithm.
  925. @param VVSlambda Gain for the virtual visual servoing control law, equivalent to the \f$\alpha\f$
  926. gain in the Damped Gauss-Newton formulation.
  927. The function refines the object pose given at least 3 object points, their corresponding image
  928. projections, an initial solution for the rotation and translation vector,
  929. as well as the camera intrinsic matrix and the distortion coefficients.
  930. The function minimizes the projection error with respect to the rotation and the translation vectors, using a
  931. virtual visual servoing (VVS) @cite Chaumette06 @cite Marchand16 scheme.
  932. */
  933. CV_EXPORTS_W void solvePnPRefineVVS( InputArray objectPoints, InputArray imagePoints,
  934. InputArray cameraMatrix, InputArray distCoeffs,
  935. InputOutputArray rvec, InputOutputArray tvec,
  936. TermCriteria criteria = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 20, FLT_EPSILON),
  937. double VVSlambda = 1);
  938. /** @brief Finds an object pose from 3D-2D point correspondences.
  939. @see @ref calib3d_solvePnP
  940. This function returns a list of all the possible solutions (a solution is a <rotation vector, translation vector>
  941. couple), depending on the number of input points and the chosen method:
  942. - P3P methods (@ref SOLVEPNP_P3P, @ref SOLVEPNP_AP3P): 3 or 4 input points. Number of returned solutions can be between 0 and 4 with 3 input points.
  943. - @ref SOLVEPNP_IPPE Input points must be >= 4 and object points must be coplanar. Returns 2 solutions.
  944. - @ref SOLVEPNP_IPPE_SQUARE Special case suitable for marker pose estimation.
  945. Number of input points must be 4 and 2 solutions are returned. Object points must be defined in the following order:
  946. - point 0: [-squareLength / 2, squareLength / 2, 0]
  947. - point 1: [ squareLength / 2, squareLength / 2, 0]
  948. - point 2: [ squareLength / 2, -squareLength / 2, 0]
  949. - point 3: [-squareLength / 2, -squareLength / 2, 0]
  950. - for all the other flags, number of input points must be >= 4 and object points can be in any configuration.
  951. Only 1 solution is returned.
  952. @param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or
  953. 1xN/Nx1 3-channel, where N is the number of points. vector\<Point3d\> can be also passed here.
  954. @param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel,
  955. where N is the number of points. vector\<Point2d\> can be also passed here.
  956. @param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
  957. @param distCoeffs Input vector of distortion coefficients
  958. \f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
  959. assumed.
  960. @param rvecs Vector of output rotation vectors (see @ref Rodrigues ) that, together with tvecs, brings points from
  961. the model coordinate system to the camera coordinate system.
  962. @param tvecs Vector of output translation vectors.
  963. @param useExtrinsicGuess Parameter used for #SOLVEPNP_ITERATIVE. If true (1), the function uses
  964. the provided rvec and tvec values as initial approximations of the rotation and translation
  965. vectors, respectively, and further optimizes them.
  966. @param flags Method for solving a PnP problem: see @ref calib3d_solvePnP_flags
  967. @param rvec Rotation vector used to initialize an iterative PnP refinement algorithm, when flag is @ref SOLVEPNP_ITERATIVE
  968. and useExtrinsicGuess is set to true.
  969. @param tvec Translation vector used to initialize an iterative PnP refinement algorithm, when flag is @ref SOLVEPNP_ITERATIVE
  970. and useExtrinsicGuess is set to true.
  971. @param reprojectionError Optional vector of reprojection error, that is the RMS error
  972. (\f$ \text{RMSE} = \sqrt{\frac{\sum_{i}^{N} \left ( \hat{y_i} - y_i \right )^2}{N}} \f$) between the input image points
  973. and the 3D object points projected with the estimated pose.
  974. More information is described in @ref calib3d_solvePnP
  975. @note
  976. - An example of how to use solvePnP for planar augmented reality can be found at
  977. opencv_source_code/samples/python/plane_ar.py
  978. - If you are using Python:
  979. - Numpy array slices won't work as input because solvePnP requires contiguous
  980. arrays (enforced by the assertion using cv::Mat::checkVector() around line 55 of
  981. modules/calib3d/src/solvepnp.cpp version 2.4.9)
  982. - The P3P algorithm requires image points to be in an array of shape (N,1,2) due
  983. to its calling of #undistortPoints (around line 75 of modules/calib3d/src/solvepnp.cpp version 2.4.9)
  984. which requires 2-channel information.
  985. - Thus, given some data D = np.array(...) where D.shape = (N,M), in order to use a subset of
  986. it as, e.g., imagePoints, one must effectively copy it into a new array: imagePoints =
  987. np.ascontiguousarray(D[:,:2]).reshape((N,1,2))
  988. - The methods @ref SOLVEPNP_DLS and @ref SOLVEPNP_UPNP cannot be used as the current implementations are
  989. unstable and sometimes give completely wrong results. If you pass one of these two
  990. flags, @ref SOLVEPNP_EPNP method will be used instead.
  991. - The minimum number of points is 4 in the general case. In the case of @ref SOLVEPNP_P3P and @ref SOLVEPNP_AP3P
  992. methods, it is required to use exactly 4 points (the first 3 points are used to estimate all the solutions
  993. of the P3P problem, the last one is used to retain the best solution that minimizes the reprojection error).
  994. - With @ref SOLVEPNP_ITERATIVE method and `useExtrinsicGuess=true`, the minimum number of points is 3 (3 points
  995. are sufficient to compute a pose but there are up to 4 solutions). The initial solution should be close to the
  996. global solution to converge.
  997. - With @ref SOLVEPNP_IPPE input points must be >= 4 and object points must be coplanar.
  998. - With @ref SOLVEPNP_IPPE_SQUARE this is a special case suitable for marker pose estimation.
  999. Number of input points must be 4. Object points must be defined in the following order:
  1000. - point 0: [-squareLength / 2, squareLength / 2, 0]
  1001. - point 1: [ squareLength / 2, squareLength / 2, 0]
  1002. - point 2: [ squareLength / 2, -squareLength / 2, 0]
  1003. - point 3: [-squareLength / 2, -squareLength / 2, 0]
  1004. */
  1005. CV_EXPORTS_W int solvePnPGeneric( InputArray objectPoints, InputArray imagePoints,
  1006. InputArray cameraMatrix, InputArray distCoeffs,
  1007. OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs,
  1008. bool useExtrinsicGuess = false, SolvePnPMethod flags = SOLVEPNP_ITERATIVE,
  1009. InputArray rvec = noArray(), InputArray tvec = noArray(),
  1010. OutputArray reprojectionError = noArray() );
  1011. /** @brief Finds an initial camera intrinsic matrix from 3D-2D point correspondences.
  1012. @param objectPoints Vector of vectors of the calibration pattern points in the calibration pattern
  1013. coordinate space. In the old interface all the per-view vectors are concatenated. See
  1014. #calibrateCamera for details.
  1015. @param imagePoints Vector of vectors of the projections of the calibration pattern points. In the
  1016. old interface all the per-view vectors are concatenated.
  1017. @param imageSize Image size in pixels used to initialize the principal point.
  1018. @param aspectRatio If it is zero or negative, both \f$f_x\f$ and \f$f_y\f$ are estimated independently.
  1019. Otherwise, \f$f_x = f_y * \texttt{aspectRatio}\f$ .
  1020. The function estimates and returns an initial camera intrinsic matrix for the camera calibration process.
  1021. Currently, the function only supports planar calibration patterns, which are patterns where each
  1022. object point has z-coordinate =0.
  1023. */
  1024. CV_EXPORTS_W Mat initCameraMatrix2D( InputArrayOfArrays objectPoints,
  1025. InputArrayOfArrays imagePoints,
  1026. Size imageSize, double aspectRatio = 1.0 );
  1027. /** @brief Finds the positions of internal corners of the chessboard.
  1028. @param image Source chessboard view. It must be an 8-bit grayscale or color image.
  1029. @param patternSize Number of inner corners per a chessboard row and column
  1030. ( patternSize = cv::Size(points_per_row,points_per_colum) = cv::Size(columns,rows) ).
  1031. @param corners Output array of detected corners.
  1032. @param flags Various operation flags that can be zero or a combination of the following values:
  1033. - @ref CALIB_CB_ADAPTIVE_THRESH Use adaptive thresholding to convert the image to black
  1034. and white, rather than a fixed threshold level (computed from the average image brightness).
  1035. - @ref CALIB_CB_NORMALIZE_IMAGE Normalize the image gamma with equalizeHist before
  1036. applying fixed or adaptive thresholding.
  1037. - @ref CALIB_CB_FILTER_QUADS Use additional criteria (like contour area, perimeter,
  1038. square-like shape) to filter out false quads extracted at the contour retrieval stage.
  1039. - @ref CALIB_CB_FAST_CHECK Run a fast check on the image that looks for chessboard corners,
  1040. and shortcut the call if none is found. This can drastically speed up the call in the
  1041. degenerate condition when no chessboard is observed.
  1042. The function attempts to determine whether the input image is a view of the chessboard pattern and
  1043. locate the internal chessboard corners. The function returns a non-zero value if all of the corners
  1044. are found and they are placed in a certain order (row by row, left to right in every row).
  1045. Otherwise, if the function fails to find all the corners or reorder them, it returns 0. For example,
  1046. a regular chessboard has 8 x 8 squares and 7 x 7 internal corners, that is, points where the black
  1047. squares touch each other. The detected coordinates are approximate, and to determine their positions
  1048. more accurately, the function calls cornerSubPix. You also may use the function cornerSubPix with
  1049. different parameters if returned coordinates are not accurate enough.
  1050. Sample usage of detecting and drawing chessboard corners: :
  1051. @code
  1052. Size patternsize(8,6); //interior number of corners
  1053. Mat gray = ....; //source image
  1054. vector<Point2f> corners; //this will be filled by the detected corners
  1055. //CALIB_CB_FAST_CHECK saves a lot of time on images
  1056. //that do not contain any chessboard corners
  1057. bool patternfound = findChessboardCorners(gray, patternsize, corners,
  1058. CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE
  1059. + CALIB_CB_FAST_CHECK);
  1060. if(patternfound)
  1061. cornerSubPix(gray, corners, Size(11, 11), Size(-1, -1),
  1062. TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1));
  1063. drawChessboardCorners(img, patternsize, Mat(corners), patternfound);
  1064. @endcode
  1065. @note The function requires white space (like a square-thick border, the wider the better) around
  1066. the board to make the detection more robust in various environments. Otherwise, if there is no
  1067. border and the background is dark, the outer black squares cannot be segmented properly and so the
  1068. square grouping and ordering algorithm fails.
  1069. Use gen_pattern.py (@ref tutorial_camera_calibration_pattern) to create checkerboard.
  1070. */
  1071. CV_EXPORTS_W bool findChessboardCorners( InputArray image, Size patternSize, OutputArray corners,
  1072. int flags = CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE );
  1073. /*
  1074. Checks whether the image contains chessboard of the specific size or not.
  1075. If yes, nonzero value is returned.
  1076. */
  1077. CV_EXPORTS_W bool checkChessboard(InputArray img, Size size);
  1078. /** @brief Finds the positions of internal corners of the chessboard using a sector based approach.
  1079. @param image Source chessboard view. It must be an 8-bit grayscale or color image.
  1080. @param patternSize Number of inner corners per a chessboard row and column
  1081. ( patternSize = cv::Size(points_per_row,points_per_colum) = cv::Size(columns,rows) ).
  1082. @param corners Output array of detected corners.
  1083. @param flags Various operation flags that can be zero or a combination of the following values:
  1084. - @ref CALIB_CB_NORMALIZE_IMAGE Normalize the image gamma with equalizeHist before detection.
  1085. - @ref CALIB_CB_EXHAUSTIVE Run an exhaustive search to improve detection rate.
  1086. - @ref CALIB_CB_ACCURACY Up sample input image to improve sub-pixel accuracy due to aliasing effects.
  1087. - @ref CALIB_CB_LARGER The detected pattern is allowed to be larger than patternSize (see description).
  1088. - @ref CALIB_CB_MARKER The detected pattern must have a marker (see description).
  1089. This should be used if an accurate camera calibration is required.
  1090. @param meta Optional output arrray of detected corners (CV_8UC1 and size = cv::Size(columns,rows)).
  1091. Each entry stands for one corner of the pattern and can have one of the following values:
  1092. - 0 = no meta data attached
  1093. - 1 = left-top corner of a black cell
  1094. - 2 = left-top corner of a white cell
  1095. - 3 = left-top corner of a black cell with a white marker dot
  1096. - 4 = left-top corner of a white cell with a black marker dot (pattern origin in case of markers otherwise first corner)
  1097. The function is analog to #findChessboardCorners but uses a localized radon
  1098. transformation approximated by box filters being more robust to all sort of
  1099. noise, faster on larger images and is able to directly return the sub-pixel
  1100. position of the internal chessboard corners. The Method is based on the paper
  1101. @cite duda2018 "Accurate Detection and Localization of Checkerboard Corners for
  1102. Calibration" demonstrating that the returned sub-pixel positions are more
  1103. accurate than the one returned by cornerSubPix allowing a precise camera
  1104. calibration for demanding applications.
  1105. In the case, the flags @ref CALIB_CB_LARGER or @ref CALIB_CB_MARKER are given,
  1106. the result can be recovered from the optional meta array. Both flags are
  1107. helpful to use calibration patterns exceeding the field of view of the camera.
  1108. These oversized patterns allow more accurate calibrations as corners can be
  1109. utilized, which are as close as possible to the image borders. For a
  1110. consistent coordinate system across all images, the optional marker (see image
  1111. below) can be used to move the origin of the board to the location where the
  1112. black circle is located.
  1113. @note The function requires a white boarder with roughly the same width as one
  1114. of the checkerboard fields around the whole board to improve the detection in
  1115. various environments. In addition, because of the localized radon
  1116. transformation it is beneficial to use round corners for the field corners
  1117. which are located on the outside of the board. The following figure illustrates
  1118. a sample checkerboard optimized for the detection. However, any other checkerboard
  1119. can be used as well.
  1120. Use gen_pattern.py (@ref tutorial_camera_calibration_pattern) to create checkerboard.
  1121. ![Checkerboard](pics/checkerboard_radon.png)
  1122. */
  1123. CV_EXPORTS_AS(findChessboardCornersSBWithMeta)
  1124. bool findChessboardCornersSB(InputArray image,Size patternSize, OutputArray corners,
  1125. int flags,OutputArray meta);
  1126. /** @overload */
  1127. CV_EXPORTS_W inline
  1128. bool findChessboardCornersSB(InputArray image, Size patternSize, OutputArray corners,
  1129. int flags = 0)
  1130. {
  1131. return findChessboardCornersSB(image, patternSize, corners, flags, noArray());
  1132. }
  1133. /** @brief Estimates the sharpness of a detected chessboard.
  1134. Image sharpness, as well as brightness, are a critical parameter for accuracte
  1135. camera calibration. For accessing these parameters for filtering out
  1136. problematic calibraiton images, this method calculates edge profiles by traveling from
  1137. black to white chessboard cell centers. Based on this, the number of pixels is
  1138. calculated required to transit from black to white. This width of the
  1139. transition area is a good indication of how sharp the chessboard is imaged
  1140. and should be below ~3.0 pixels.
  1141. @param image Gray image used to find chessboard corners
  1142. @param patternSize Size of a found chessboard pattern
  1143. @param corners Corners found by #findChessboardCornersSB
  1144. @param rise_distance Rise distance 0.8 means 10% ... 90% of the final signal strength
  1145. @param vertical By default edge responses for horizontal lines are calculated
  1146. @param sharpness Optional output array with a sharpness value for calculated edge responses (see description)
  1147. The optional sharpness array is of type CV_32FC1 and has for each calculated
  1148. profile one row with the following five entries:
  1149. * 0 = x coordinate of the underlying edge in the image
  1150. * 1 = y coordinate of the underlying edge in the image
  1151. * 2 = width of the transition area (sharpness)
  1152. * 3 = signal strength in the black cell (min brightness)
  1153. * 4 = signal strength in the white cell (max brightness)
  1154. @return Scalar(average sharpness, average min brightness, average max brightness,0)
  1155. */
  1156. CV_EXPORTS_W Scalar estimateChessboardSharpness(InputArray image, Size patternSize, InputArray corners,
  1157. float rise_distance=0.8F,bool vertical=false,
  1158. OutputArray sharpness=noArray());
  1159. //! finds subpixel-accurate positions of the chessboard corners
  1160. CV_EXPORTS_W bool find4QuadCornerSubpix( InputArray img, InputOutputArray corners, Size region_size );
  1161. /** @brief Renders the detected chessboard corners.
  1162. @param image Destination image. It must be an 8-bit color image.
  1163. @param patternSize Number of inner corners per a chessboard row and column
  1164. (patternSize = cv::Size(points_per_row,points_per_column)).
  1165. @param corners Array of detected corners, the output of #findChessboardCorners.
  1166. @param patternWasFound Parameter indicating whether the complete board was found or not. The
  1167. return value of #findChessboardCorners should be passed here.
  1168. The function draws individual chessboard corners detected either as red circles if the board was not
  1169. found, or as colored corners connected with lines if the board was found.
  1170. */
  1171. CV_EXPORTS_W void drawChessboardCorners( InputOutputArray image, Size patternSize,
  1172. InputArray corners, bool patternWasFound );
  1173. /** @brief Draw axes of the world/object coordinate system from pose estimation. @sa solvePnP
  1174. @param image Input/output image. It must have 1 or 3 channels. The number of channels is not altered.
  1175. @param cameraMatrix Input 3x3 floating-point matrix of camera intrinsic parameters.
  1176. \f$\cameramatrix{A}\f$
  1177. @param distCoeffs Input vector of distortion coefficients
  1178. \f$\distcoeffs\f$. If the vector is empty, the zero distortion coefficients are assumed.
  1179. @param rvec Rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from
  1180. the model coordinate system to the camera coordinate system.
  1181. @param tvec Translation vector.
  1182. @param length Length of the painted axes in the same unit than tvec (usually in meters).
  1183. @param thickness Line thickness of the painted axes.
  1184. This function draws the axes of the world/object coordinate system w.r.t. to the camera frame.
  1185. OX is drawn in red, OY in green and OZ in blue.
  1186. */
  1187. CV_EXPORTS_W void drawFrameAxes(InputOutputArray image, InputArray cameraMatrix, InputArray distCoeffs,
  1188. InputArray rvec, InputArray tvec, float length, int thickness=3);
  1189. struct CV_EXPORTS_W_SIMPLE CirclesGridFinderParameters
  1190. {
  1191. CV_WRAP CirclesGridFinderParameters();
  1192. CV_PROP_RW cv::Size2f densityNeighborhoodSize;
  1193. CV_PROP_RW float minDensity;
  1194. CV_PROP_RW int kmeansAttempts;
  1195. CV_PROP_RW int minDistanceToAddKeypoint;
  1196. CV_PROP_RW int keypointScale;
  1197. CV_PROP_RW float minGraphConfidence;
  1198. CV_PROP_RW float vertexGain;
  1199. CV_PROP_RW float vertexPenalty;
  1200. CV_PROP_RW float existingVertexGain;
  1201. CV_PROP_RW float edgeGain;
  1202. CV_PROP_RW float edgePenalty;
  1203. CV_PROP_RW float convexHullFactor;
  1204. CV_PROP_RW float minRNGEdgeSwitchDist;
  1205. enum GridType
  1206. {
  1207. SYMMETRIC_GRID, ASYMMETRIC_GRID
  1208. };
  1209. GridType gridType;
  1210. CV_PROP_RW float squareSize; //!< Distance between two adjacent points. Used by CALIB_CB_CLUSTERING.
  1211. CV_PROP_RW float maxRectifiedDistance; //!< Max deviation from prediction. Used by CALIB_CB_CLUSTERING.
  1212. };
  1213. #ifndef DISABLE_OPENCV_3_COMPATIBILITY
  1214. typedef CirclesGridFinderParameters CirclesGridFinderParameters2;
  1215. #endif
  1216. /** @brief Finds centers in the grid of circles.
  1217. @param image grid view of input circles; it must be an 8-bit grayscale or color image.
  1218. @param patternSize number of circles per row and column
  1219. ( patternSize = Size(points_per_row, points_per_colum) ).
  1220. @param centers output array of detected centers.
  1221. @param flags various operation flags that can be one of the following values:
  1222. - @ref CALIB_CB_SYMMETRIC_GRID uses symmetric pattern of circles.
  1223. - @ref CALIB_CB_ASYMMETRIC_GRID uses asymmetric pattern of circles.
  1224. - @ref CALIB_CB_CLUSTERING uses a special algorithm for grid detection. It is more robust to
  1225. perspective distortions but much more sensitive to background clutter.
  1226. @param blobDetector feature detector that finds blobs like dark circles on light background.
  1227. If `blobDetector` is NULL then `image` represents Point2f array of candidates.
  1228. @param parameters struct for finding circles in a grid pattern.
  1229. The function attempts to determine whether the input image contains a grid of circles. If it is, the
  1230. function locates centers of the circles. The function returns a non-zero value if all of the centers
  1231. have been found and they have been placed in a certain order (row by row, left to right in every
  1232. row). Otherwise, if the function fails to find all the corners or reorder them, it returns 0.
  1233. Sample usage of detecting and drawing the centers of circles: :
  1234. @code
  1235. Size patternsize(7,7); //number of centers
  1236. Mat gray = ...; //source image
  1237. vector<Point2f> centers; //this will be filled by the detected centers
  1238. bool patternfound = findCirclesGrid(gray, patternsize, centers);
  1239. drawChessboardCorners(img, patternsize, Mat(centers), patternfound);
  1240. @endcode
  1241. @note The function requires white space (like a square-thick border, the wider the better) around
  1242. the board to make the detection more robust in various environments.
  1243. */
  1244. CV_EXPORTS_W bool findCirclesGrid( InputArray image, Size patternSize,
  1245. OutputArray centers, int flags,
  1246. const Ptr<FeatureDetector> &blobDetector,
  1247. const CirclesGridFinderParameters& parameters);
  1248. /** @overload */
  1249. CV_EXPORTS_W bool findCirclesGrid( InputArray image, Size patternSize,
  1250. OutputArray centers, int flags = CALIB_CB_SYMMETRIC_GRID,
  1251. const Ptr<FeatureDetector> &blobDetector = SimpleBlobDetector::create());
  1252. /** @brief Finds the camera intrinsic and extrinsic parameters from several views of a calibration
  1253. pattern.
  1254. @param objectPoints In the new interface it is a vector of vectors of calibration pattern points in
  1255. the calibration pattern coordinate space (e.g. std::vector<std::vector<cv::Vec3f>>). The outer
  1256. vector contains as many elements as the number of pattern views. If the same calibration pattern
  1257. is shown in each view and it is fully visible, all the vectors will be the same. Although, it is
  1258. possible to use partially occluded patterns or even different patterns in different views. Then,
  1259. the vectors will be different. Although the points are 3D, they all lie in the calibration pattern's
  1260. XY coordinate plane (thus 0 in the Z-coordinate), if the used calibration pattern is a planar rig.
  1261. In the old interface all the vectors of object points from different views are concatenated
  1262. together.
  1263. @param imagePoints In the new interface it is a vector of vectors of the projections of calibration
  1264. pattern points (e.g. std::vector<std::vector<cv::Vec2f>>). imagePoints.size() and
  1265. objectPoints.size(), and imagePoints[i].size() and objectPoints[i].size() for each i, must be equal,
  1266. respectively. In the old interface all the vectors of object points from different views are
  1267. concatenated together.
  1268. @param imageSize Size of the image used only to initialize the camera intrinsic matrix.
  1269. @param cameraMatrix Input/output 3x3 floating-point camera intrinsic matrix
  1270. \f$\cameramatrix{A}\f$ . If @ref CALIB_USE_INTRINSIC_GUESS
  1271. and/or @ref CALIB_FIX_ASPECT_RATIO, @ref CALIB_FIX_PRINCIPAL_POINT or @ref CALIB_FIX_FOCAL_LENGTH
  1272. are specified, some or all of fx, fy, cx, cy must be initialized before calling the function.
  1273. @param distCoeffs Input/output vector of distortion coefficients
  1274. \f$\distcoeffs\f$.
  1275. @param rvecs Output vector of rotation vectors (@ref Rodrigues ) estimated for each pattern view
  1276. (e.g. std::vector<cv::Mat>>). That is, each i-th rotation vector together with the corresponding
  1277. i-th translation vector (see the next output parameter description) brings the calibration pattern
  1278. from the object coordinate space (in which object points are specified) to the camera coordinate
  1279. space. In more technical terms, the tuple of the i-th rotation and translation vector performs
  1280. a change of basis from object coordinate space to camera coordinate space. Due to its duality, this
  1281. tuple is equivalent to the position of the calibration pattern with respect to the camera coordinate
  1282. space.
  1283. @param tvecs Output vector of translation vectors estimated for each pattern view, see parameter
  1284. describtion above.
  1285. @param stdDeviationsIntrinsics Output vector of standard deviations estimated for intrinsic
  1286. parameters. Order of deviations values:
  1287. \f$(f_x, f_y, c_x, c_y, k_1, k_2, p_1, p_2, k_3, k_4, k_5, k_6 , s_1, s_2, s_3,
  1288. s_4, \tau_x, \tau_y)\f$ If one of parameters is not estimated, it's deviation is equals to zero.
  1289. @param stdDeviationsExtrinsics Output vector of standard deviations estimated for extrinsic
  1290. parameters. Order of deviations values: \f$(R_0, T_0, \dotsc , R_{M - 1}, T_{M - 1})\f$ where M is
  1291. the number of pattern views. \f$R_i, T_i\f$ are concatenated 1x3 vectors.
  1292. @param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view.
  1293. @param flags Different flags that may be zero or a combination of the following values:
  1294. - @ref CALIB_USE_INTRINSIC_GUESS cameraMatrix contains valid initial values of
  1295. fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image
  1296. center ( imageSize is used), and focal distances are computed in a least-squares fashion.
  1297. Note, that if intrinsic parameters are known, there is no need to use this function just to
  1298. estimate extrinsic parameters. Use @ref solvePnP instead.
  1299. - @ref CALIB_FIX_PRINCIPAL_POINT The principal point is not changed during the global
  1300. optimization. It stays at the center or at a different location specified when
  1301. @ref CALIB_USE_INTRINSIC_GUESS is set too.
  1302. - @ref CALIB_FIX_ASPECT_RATIO The functions consider only fy as a free parameter. The
  1303. ratio fx/fy stays the same as in the input cameraMatrix . When
  1304. @ref CALIB_USE_INTRINSIC_GUESS is not set, the actual input values of fx and fy are
  1305. ignored, only their ratio is computed and used further.
  1306. - @ref CALIB_ZERO_TANGENT_DIST Tangential distortion coefficients \f$(p_1, p_2)\f$ are set
  1307. to zeros and stay zero.
  1308. - @ref CALIB_FIX_FOCAL_LENGTH The focal length is not changed during the global optimization if
  1309. @ref CALIB_USE_INTRINSIC_GUESS is set.
  1310. - @ref CALIB_FIX_K1,..., @ref CALIB_FIX_K6 The corresponding radial distortion
  1311. coefficient is not changed during the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is
  1312. set, the coefficient from the supplied distCoeffs matrix is used. Otherwise, it is set to 0.
  1313. - @ref CALIB_RATIONAL_MODEL Coefficients k4, k5, and k6 are enabled. To provide the
  1314. backward compatibility, this extra flag should be explicitly specified to make the
  1315. calibration function use the rational model and return 8 coefficients or more.
  1316. - @ref CALIB_THIN_PRISM_MODEL Coefficients s1, s2, s3 and s4 are enabled. To provide the
  1317. backward compatibility, this extra flag should be explicitly specified to make the
  1318. calibration function use the thin prism model and return 12 coefficients or more.
  1319. - @ref CALIB_FIX_S1_S2_S3_S4 The thin prism distortion coefficients are not changed during
  1320. the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the
  1321. supplied distCoeffs matrix is used. Otherwise, it is set to 0.
  1322. - @ref CALIB_TILTED_MODEL Coefficients tauX and tauY are enabled. To provide the
  1323. backward compatibility, this extra flag should be explicitly specified to make the
  1324. calibration function use the tilted sensor model and return 14 coefficients.
  1325. - @ref CALIB_FIX_TAUX_TAUY The coefficients of the tilted sensor model are not changed during
  1326. the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the
  1327. supplied distCoeffs matrix is used. Otherwise, it is set to 0.
  1328. @param criteria Termination criteria for the iterative optimization algorithm.
  1329. @return the overall RMS re-projection error.
  1330. The function estimates the intrinsic camera parameters and extrinsic parameters for each of the
  1331. views. The algorithm is based on @cite Zhang2000 and @cite BouguetMCT . The coordinates of 3D object
  1332. points and their corresponding 2D projections in each view must be specified. That may be achieved
  1333. by using an object with known geometry and easily detectable feature points. Such an object is
  1334. called a calibration rig or calibration pattern, and OpenCV has built-in support for a chessboard as
  1335. a calibration rig (see @ref findChessboardCorners). Currently, initialization of intrinsic
  1336. parameters (when @ref CALIB_USE_INTRINSIC_GUESS is not set) is only implemented for planar calibration
  1337. patterns (where Z-coordinates of the object points must be all zeros). 3D calibration rigs can also
  1338. be used as long as initial cameraMatrix is provided.
  1339. The algorithm performs the following steps:
  1340. - Compute the initial intrinsic parameters (the option only available for planar calibration
  1341. patterns) or read them from the input parameters. The distortion coefficients are all set to
  1342. zeros initially unless some of CALIB_FIX_K? are specified.
  1343. - Estimate the initial camera pose as if the intrinsic parameters have been already known. This is
  1344. done using @ref solvePnP .
  1345. - Run the global Levenberg-Marquardt optimization algorithm to minimize the reprojection error,
  1346. that is, the total sum of squared distances between the observed feature points imagePoints and
  1347. the projected (using the current estimates for camera parameters and the poses) object points
  1348. objectPoints. See @ref projectPoints for details.
  1349. @note
  1350. If you use a non-square (i.e. non-N-by-N) grid and @ref findChessboardCorners for calibration,
  1351. and @ref calibrateCamera returns bad values (zero distortion coefficients, \f$c_x\f$ and
  1352. \f$c_y\f$ very far from the image center, and/or large differences between \f$f_x\f$ and
  1353. \f$f_y\f$ (ratios of 10:1 or more)), then you are probably using patternSize=cvSize(rows,cols)
  1354. instead of using patternSize=cvSize(cols,rows) in @ref findChessboardCorners.
  1355. @sa
  1356. calibrateCameraRO, findChessboardCorners, solvePnP, initCameraMatrix2D, stereoCalibrate,
  1357. undistort
  1358. */
  1359. CV_EXPORTS_AS(calibrateCameraExtended) double calibrateCamera( InputArrayOfArrays objectPoints,
  1360. InputArrayOfArrays imagePoints, Size imageSize,
  1361. InputOutputArray cameraMatrix, InputOutputArray distCoeffs,
  1362. OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs,
  1363. OutputArray stdDeviationsIntrinsics,
  1364. OutputArray stdDeviationsExtrinsics,
  1365. OutputArray perViewErrors,
  1366. int flags = 0, TermCriteria criteria = TermCriteria(
  1367. TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) );
  1368. /** @overload */
  1369. CV_EXPORTS_W double calibrateCamera( InputArrayOfArrays objectPoints,
  1370. InputArrayOfArrays imagePoints, Size imageSize,
  1371. InputOutputArray cameraMatrix, InputOutputArray distCoeffs,
  1372. OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs,
  1373. int flags = 0, TermCriteria criteria = TermCriteria(
  1374. TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) );
  1375. /** @brief Finds the camera intrinsic and extrinsic parameters from several views of a calibration pattern.
  1376. This function is an extension of #calibrateCamera with the method of releasing object which was
  1377. proposed in @cite strobl2011iccv. In many common cases with inaccurate, unmeasured, roughly planar
  1378. targets (calibration plates), this method can dramatically improve the precision of the estimated
  1379. camera parameters. Both the object-releasing method and standard method are supported by this
  1380. function. Use the parameter **iFixedPoint** for method selection. In the internal implementation,
  1381. #calibrateCamera is a wrapper for this function.
  1382. @param objectPoints Vector of vectors of calibration pattern points in the calibration pattern
  1383. coordinate space. See #calibrateCamera for details. If the method of releasing object to be used,
  1384. the identical calibration board must be used in each view and it must be fully visible, and all
  1385. objectPoints[i] must be the same and all points should be roughly close to a plane. **The calibration
  1386. target has to be rigid, or at least static if the camera (rather than the calibration target) is
  1387. shifted for grabbing images.**
  1388. @param imagePoints Vector of vectors of the projections of calibration pattern points. See
  1389. #calibrateCamera for details.
  1390. @param imageSize Size of the image used only to initialize the intrinsic camera matrix.
  1391. @param iFixedPoint The index of the 3D object point in objectPoints[0] to be fixed. It also acts as
  1392. a switch for calibration method selection. If object-releasing method to be used, pass in the
  1393. parameter in the range of [1, objectPoints[0].size()-2], otherwise a value out of this range will
  1394. make standard calibration method selected. Usually the top-right corner point of the calibration
  1395. board grid is recommended to be fixed when object-releasing method being utilized. According to
  1396. \cite strobl2011iccv, two other points are also fixed. In this implementation, objectPoints[0].front
  1397. and objectPoints[0].back.z are used. With object-releasing method, accurate rvecs, tvecs and
  1398. newObjPoints are only possible if coordinates of these three fixed points are accurate enough.
  1399. @param cameraMatrix Output 3x3 floating-point camera matrix. See #calibrateCamera for details.
  1400. @param distCoeffs Output vector of distortion coefficients. See #calibrateCamera for details.
  1401. @param rvecs Output vector of rotation vectors estimated for each pattern view. See #calibrateCamera
  1402. for details.
  1403. @param tvecs Output vector of translation vectors estimated for each pattern view.
  1404. @param newObjPoints The updated output vector of calibration pattern points. The coordinates might
  1405. be scaled based on three fixed points. The returned coordinates are accurate only if the above
  1406. mentioned three fixed points are accurate. If not needed, noArray() can be passed in. This parameter
  1407. is ignored with standard calibration method.
  1408. @param stdDeviationsIntrinsics Output vector of standard deviations estimated for intrinsic parameters.
  1409. See #calibrateCamera for details.
  1410. @param stdDeviationsExtrinsics Output vector of standard deviations estimated for extrinsic parameters.
  1411. See #calibrateCamera for details.
  1412. @param stdDeviationsObjPoints Output vector of standard deviations estimated for refined coordinates
  1413. of calibration pattern points. It has the same size and order as objectPoints[0] vector. This
  1414. parameter is ignored with standard calibration method.
  1415. @param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view.
  1416. @param flags Different flags that may be zero or a combination of some predefined values. See
  1417. #calibrateCamera for details. If the method of releasing object is used, the calibration time may
  1418. be much longer. CALIB_USE_QR or CALIB_USE_LU could be used for faster calibration with potentially
  1419. less precise and less stable in some rare cases.
  1420. @param criteria Termination criteria for the iterative optimization algorithm.
  1421. @return the overall RMS re-projection error.
  1422. The function estimates the intrinsic camera parameters and extrinsic parameters for each of the
  1423. views. The algorithm is based on @cite Zhang2000, @cite BouguetMCT and @cite strobl2011iccv. See
  1424. #calibrateCamera for other detailed explanations.
  1425. @sa
  1426. calibrateCamera, findChessboardCorners, solvePnP, initCameraMatrix2D, stereoCalibrate, undistort
  1427. */
  1428. CV_EXPORTS_AS(calibrateCameraROExtended) double calibrateCameraRO( InputArrayOfArrays objectPoints,
  1429. InputArrayOfArrays imagePoints, Size imageSize, int iFixedPoint,
  1430. InputOutputArray cameraMatrix, InputOutputArray distCoeffs,
  1431. OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs,
  1432. OutputArray newObjPoints,
  1433. OutputArray stdDeviationsIntrinsics,
  1434. OutputArray stdDeviationsExtrinsics,
  1435. OutputArray stdDeviationsObjPoints,
  1436. OutputArray perViewErrors,
  1437. int flags = 0, TermCriteria criteria = TermCriteria(
  1438. TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) );
  1439. /** @overload */
  1440. CV_EXPORTS_W double calibrateCameraRO( InputArrayOfArrays objectPoints,
  1441. InputArrayOfArrays imagePoints, Size imageSize, int iFixedPoint,
  1442. InputOutputArray cameraMatrix, InputOutputArray distCoeffs,
  1443. OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs,
  1444. OutputArray newObjPoints,
  1445. int flags = 0, TermCriteria criteria = TermCriteria(
  1446. TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) );
  1447. /** @brief Computes useful camera characteristics from the camera intrinsic matrix.
  1448. @param cameraMatrix Input camera intrinsic matrix that can be estimated by #calibrateCamera or
  1449. #stereoCalibrate .
  1450. @param imageSize Input image size in pixels.
  1451. @param apertureWidth Physical width in mm of the sensor.
  1452. @param apertureHeight Physical height in mm of the sensor.
  1453. @param fovx Output field of view in degrees along the horizontal sensor axis.
  1454. @param fovy Output field of view in degrees along the vertical sensor axis.
  1455. @param focalLength Focal length of the lens in mm.
  1456. @param principalPoint Principal point in mm.
  1457. @param aspectRatio \f$f_y/f_x\f$
  1458. The function computes various useful camera characteristics from the previously estimated camera
  1459. matrix.
  1460. @note
  1461. Do keep in mind that the unity measure 'mm' stands for whatever unit of measure one chooses for
  1462. the chessboard pitch (it can thus be any value).
  1463. */
  1464. CV_EXPORTS_W void calibrationMatrixValues( InputArray cameraMatrix, Size imageSize,
  1465. double apertureWidth, double apertureHeight,
  1466. CV_OUT double& fovx, CV_OUT double& fovy,
  1467. CV_OUT double& focalLength, CV_OUT Point2d& principalPoint,
  1468. CV_OUT double& aspectRatio );
  1469. /** @brief Calibrates a stereo camera set up. This function finds the intrinsic parameters
  1470. for each of the two cameras and the extrinsic parameters between the two cameras.
  1471. @param objectPoints Vector of vectors of the calibration pattern points. The same structure as
  1472. in @ref calibrateCamera. For each pattern view, both cameras need to see the same object
  1473. points. Therefore, objectPoints.size(), imagePoints1.size(), and imagePoints2.size() need to be
  1474. equal as well as objectPoints[i].size(), imagePoints1[i].size(), and imagePoints2[i].size() need to
  1475. be equal for each i.
  1476. @param imagePoints1 Vector of vectors of the projections of the calibration pattern points,
  1477. observed by the first camera. The same structure as in @ref calibrateCamera.
  1478. @param imagePoints2 Vector of vectors of the projections of the calibration pattern points,
  1479. observed by the second camera. The same structure as in @ref calibrateCamera.
  1480. @param cameraMatrix1 Input/output camera intrinsic matrix for the first camera, the same as in
  1481. @ref calibrateCamera. Furthermore, for the stereo case, additional flags may be used, see below.
  1482. @param distCoeffs1 Input/output vector of distortion coefficients, the same as in
  1483. @ref calibrateCamera.
  1484. @param cameraMatrix2 Input/output second camera intrinsic matrix for the second camera. See description for
  1485. cameraMatrix1.
  1486. @param distCoeffs2 Input/output lens distortion coefficients for the second camera. See
  1487. description for distCoeffs1.
  1488. @param imageSize Size of the image used only to initialize the camera intrinsic matrices.
  1489. @param R Output rotation matrix. Together with the translation vector T, this matrix brings
  1490. points given in the first camera's coordinate system to points in the second camera's
  1491. coordinate system. In more technical terms, the tuple of R and T performs a change of basis
  1492. from the first camera's coordinate system to the second camera's coordinate system. Due to its
  1493. duality, this tuple is equivalent to the position of the first camera with respect to the
  1494. second camera coordinate system.
  1495. @param T Output translation vector, see description above.
  1496. @param E Output essential matrix.
  1497. @param F Output fundamental matrix.
  1498. @param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view.
  1499. @param flags Different flags that may be zero or a combination of the following values:
  1500. - @ref CALIB_FIX_INTRINSIC Fix cameraMatrix? and distCoeffs? so that only R, T, E, and F
  1501. matrices are estimated.
  1502. - @ref CALIB_USE_INTRINSIC_GUESS Optimize some or all of the intrinsic parameters
  1503. according to the specified flags. Initial values are provided by the user.
  1504. - @ref CALIB_USE_EXTRINSIC_GUESS R and T contain valid initial values that are optimized further.
  1505. Otherwise R and T are initialized to the median value of the pattern views (each dimension separately).
  1506. - @ref CALIB_FIX_PRINCIPAL_POINT Fix the principal points during the optimization.
  1507. - @ref CALIB_FIX_FOCAL_LENGTH Fix \f$f^{(j)}_x\f$ and \f$f^{(j)}_y\f$ .
  1508. - @ref CALIB_FIX_ASPECT_RATIO Optimize \f$f^{(j)}_y\f$ . Fix the ratio \f$f^{(j)}_x/f^{(j)}_y\f$
  1509. .
  1510. - @ref CALIB_SAME_FOCAL_LENGTH Enforce \f$f^{(0)}_x=f^{(1)}_x\f$ and \f$f^{(0)}_y=f^{(1)}_y\f$ .
  1511. - @ref CALIB_ZERO_TANGENT_DIST Set tangential distortion coefficients for each camera to
  1512. zeros and fix there.
  1513. - @ref CALIB_FIX_K1,..., @ref CALIB_FIX_K6 Do not change the corresponding radial
  1514. distortion coefficient during the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set,
  1515. the coefficient from the supplied distCoeffs matrix is used. Otherwise, it is set to 0.
  1516. - @ref CALIB_RATIONAL_MODEL Enable coefficients k4, k5, and k6. To provide the backward
  1517. compatibility, this extra flag should be explicitly specified to make the calibration
  1518. function use the rational model and return 8 coefficients. If the flag is not set, the
  1519. function computes and returns only 5 distortion coefficients.
  1520. - @ref CALIB_THIN_PRISM_MODEL Coefficients s1, s2, s3 and s4 are enabled. To provide the
  1521. backward compatibility, this extra flag should be explicitly specified to make the
  1522. calibration function use the thin prism model and return 12 coefficients. If the flag is not
  1523. set, the function computes and returns only 5 distortion coefficients.
  1524. - @ref CALIB_FIX_S1_S2_S3_S4 The thin prism distortion coefficients are not changed during
  1525. the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the
  1526. supplied distCoeffs matrix is used. Otherwise, it is set to 0.
  1527. - @ref CALIB_TILTED_MODEL Coefficients tauX and tauY are enabled. To provide the
  1528. backward compatibility, this extra flag should be explicitly specified to make the
  1529. calibration function use the tilted sensor model and return 14 coefficients. If the flag is not
  1530. set, the function computes and returns only 5 distortion coefficients.
  1531. - @ref CALIB_FIX_TAUX_TAUY The coefficients of the tilted sensor model are not changed during
  1532. the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the
  1533. supplied distCoeffs matrix is used. Otherwise, it is set to 0.
  1534. @param criteria Termination criteria for the iterative optimization algorithm.
  1535. The function estimates the transformation between two cameras making a stereo pair. If one computes
  1536. the poses of an object relative to the first camera and to the second camera,
  1537. ( \f$R_1\f$,\f$T_1\f$ ) and (\f$R_2\f$,\f$T_2\f$), respectively, for a stereo camera where the
  1538. relative position and orientation between the two cameras are fixed, then those poses definitely
  1539. relate to each other. This means, if the relative position and orientation (\f$R\f$,\f$T\f$) of the
  1540. two cameras is known, it is possible to compute (\f$R_2\f$,\f$T_2\f$) when (\f$R_1\f$,\f$T_1\f$) is
  1541. given. This is what the described function does. It computes (\f$R\f$,\f$T\f$) such that:
  1542. \f[R_2=R R_1\f]
  1543. \f[T_2=R T_1 + T.\f]
  1544. Therefore, one can compute the coordinate representation of a 3D point for the second camera's
  1545. coordinate system when given the point's coordinate representation in the first camera's coordinate
  1546. system:
  1547. \f[\begin{bmatrix}
  1548. X_2 \\
  1549. Y_2 \\
  1550. Z_2 \\
  1551. 1
  1552. \end{bmatrix} = \begin{bmatrix}
  1553. R & T \\
  1554. 0 & 1
  1555. \end{bmatrix} \begin{bmatrix}
  1556. X_1 \\
  1557. Y_1 \\
  1558. Z_1 \\
  1559. 1
  1560. \end{bmatrix}.\f]
  1561. Optionally, it computes the essential matrix E:
  1562. \f[E= \vecthreethree{0}{-T_2}{T_1}{T_2}{0}{-T_0}{-T_1}{T_0}{0} R\f]
  1563. where \f$T_i\f$ are components of the translation vector \f$T\f$ : \f$T=[T_0, T_1, T_2]^T\f$ .
  1564. And the function can also compute the fundamental matrix F:
  1565. \f[F = cameraMatrix2^{-T}\cdot E \cdot cameraMatrix1^{-1}\f]
  1566. Besides the stereo-related information, the function can also perform a full calibration of each of
  1567. the two cameras. However, due to the high dimensionality of the parameter space and noise in the
  1568. input data, the function can diverge from the correct solution. If the intrinsic parameters can be
  1569. estimated with high accuracy for each of the cameras individually (for example, using
  1570. #calibrateCamera ), you are recommended to do so and then pass @ref CALIB_FIX_INTRINSIC flag to the
  1571. function along with the computed intrinsic parameters. Otherwise, if all the parameters are
  1572. estimated at once, it makes sense to restrict some parameters, for example, pass
  1573. @ref CALIB_SAME_FOCAL_LENGTH and @ref CALIB_ZERO_TANGENT_DIST flags, which is usually a
  1574. reasonable assumption.
  1575. Similarly to #calibrateCamera, the function minimizes the total re-projection error for all the
  1576. points in all the available views from both cameras. The function returns the final value of the
  1577. re-projection error.
  1578. */
  1579. CV_EXPORTS_AS(stereoCalibrateExtended) double stereoCalibrate( InputArrayOfArrays objectPoints,
  1580. InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2,
  1581. InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1,
  1582. InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2,
  1583. Size imageSize, InputOutputArray R,InputOutputArray T, OutputArray E, OutputArray F,
  1584. OutputArray perViewErrors, int flags = CALIB_FIX_INTRINSIC,
  1585. TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6) );
  1586. /// @overload
  1587. CV_EXPORTS_W double stereoCalibrate( InputArrayOfArrays objectPoints,
  1588. InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2,
  1589. InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1,
  1590. InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2,
  1591. Size imageSize, OutputArray R,OutputArray T, OutputArray E, OutputArray F,
  1592. int flags = CALIB_FIX_INTRINSIC,
  1593. TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6) );
  1594. /** @brief Computes rectification transforms for each head of a calibrated stereo camera.
  1595. @param cameraMatrix1 First camera intrinsic matrix.
  1596. @param distCoeffs1 First camera distortion parameters.
  1597. @param cameraMatrix2 Second camera intrinsic matrix.
  1598. @param distCoeffs2 Second camera distortion parameters.
  1599. @param imageSize Size of the image used for stereo calibration.
  1600. @param R Rotation matrix from the coordinate system of the first camera to the second camera,
  1601. see @ref stereoCalibrate.
  1602. @param T Translation vector from the coordinate system of the first camera to the second camera,
  1603. see @ref stereoCalibrate.
  1604. @param R1 Output 3x3 rectification transform (rotation matrix) for the first camera. This matrix
  1605. brings points given in the unrectified first camera's coordinate system to points in the rectified
  1606. first camera's coordinate system. In more technical terms, it performs a change of basis from the
  1607. unrectified first camera's coordinate system to the rectified first camera's coordinate system.
  1608. @param R2 Output 3x3 rectification transform (rotation matrix) for the second camera. This matrix
  1609. brings points given in the unrectified second camera's coordinate system to points in the rectified
  1610. second camera's coordinate system. In more technical terms, it performs a change of basis from the
  1611. unrectified second camera's coordinate system to the rectified second camera's coordinate system.
  1612. @param P1 Output 3x4 projection matrix in the new (rectified) coordinate systems for the first
  1613. camera, i.e. it projects points given in the rectified first camera coordinate system into the
  1614. rectified first camera's image.
  1615. @param P2 Output 3x4 projection matrix in the new (rectified) coordinate systems for the second
  1616. camera, i.e. it projects points given in the rectified first camera coordinate system into the
  1617. rectified second camera's image.
  1618. @param Q Output \f$4 \times 4\f$ disparity-to-depth mapping matrix (see @ref reprojectImageTo3D).
  1619. @param flags Operation flags that may be zero or @ref CALIB_ZERO_DISPARITY . If the flag is set,
  1620. the function makes the principal points of each camera have the same pixel coordinates in the
  1621. rectified views. And if the flag is not set, the function may still shift the images in the
  1622. horizontal or vertical direction (depending on the orientation of epipolar lines) to maximize the
  1623. useful image area.
  1624. @param alpha Free scaling parameter. If it is -1 or absent, the function performs the default
  1625. scaling. Otherwise, the parameter should be between 0 and 1. alpha=0 means that the rectified
  1626. images are zoomed and shifted so that only valid pixels are visible (no black areas after
  1627. rectification). alpha=1 means that the rectified image is decimated and shifted so that all the
  1628. pixels from the original images from the cameras are retained in the rectified images (no source
  1629. image pixels are lost). Any intermediate value yields an intermediate result between
  1630. those two extreme cases.
  1631. @param newImageSize New image resolution after rectification. The same size should be passed to
  1632. #initUndistortRectifyMap (see the stereo_calib.cpp sample in OpenCV samples directory). When (0,0)
  1633. is passed (default), it is set to the original imageSize . Setting it to a larger value can help you
  1634. preserve details in the original image, especially when there is a big radial distortion.
  1635. @param validPixROI1 Optional output rectangles inside the rectified images where all the pixels
  1636. are valid. If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller
  1637. (see the picture below).
  1638. @param validPixROI2 Optional output rectangles inside the rectified images where all the pixels
  1639. are valid. If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller
  1640. (see the picture below).
  1641. The function computes the rotation matrices for each camera that (virtually) make both camera image
  1642. planes the same plane. Consequently, this makes all the epipolar lines parallel and thus simplifies
  1643. the dense stereo correspondence problem. The function takes the matrices computed by #stereoCalibrate
  1644. as input. As output, it provides two rotation matrices and also two projection matrices in the new
  1645. coordinates. The function distinguishes the following two cases:
  1646. - **Horizontal stereo**: the first and the second camera views are shifted relative to each other
  1647. mainly along the x-axis (with possible small vertical shift). In the rectified images, the
  1648. corresponding epipolar lines in the left and right cameras are horizontal and have the same
  1649. y-coordinate. P1 and P2 look like:
  1650. \f[\texttt{P1} = \begin{bmatrix}
  1651. f & 0 & cx_1 & 0 \\
  1652. 0 & f & cy & 0 \\
  1653. 0 & 0 & 1 & 0
  1654. \end{bmatrix}\f]
  1655. \f[\texttt{P2} = \begin{bmatrix}
  1656. f & 0 & cx_2 & T_x*f \\
  1657. 0 & f & cy & 0 \\
  1658. 0 & 0 & 1 & 0
  1659. \end{bmatrix} ,\f]
  1660. where \f$T_x\f$ is a horizontal shift between the cameras and \f$cx_1=cx_2\f$ if
  1661. @ref CALIB_ZERO_DISPARITY is set.
  1662. - **Vertical stereo**: the first and the second camera views are shifted relative to each other
  1663. mainly in the vertical direction (and probably a bit in the horizontal direction too). The epipolar
  1664. lines in the rectified images are vertical and have the same x-coordinate. P1 and P2 look like:
  1665. \f[\texttt{P1} = \begin{bmatrix}
  1666. f & 0 & cx & 0 \\
  1667. 0 & f & cy_1 & 0 \\
  1668. 0 & 0 & 1 & 0
  1669. \end{bmatrix}\f]
  1670. \f[\texttt{P2} = \begin{bmatrix}
  1671. f & 0 & cx & 0 \\
  1672. 0 & f & cy_2 & T_y*f \\
  1673. 0 & 0 & 1 & 0
  1674. \end{bmatrix},\f]
  1675. where \f$T_y\f$ is a vertical shift between the cameras and \f$cy_1=cy_2\f$ if
  1676. @ref CALIB_ZERO_DISPARITY is set.
  1677. As you can see, the first three columns of P1 and P2 will effectively be the new "rectified" camera
  1678. matrices. The matrices, together with R1 and R2 , can then be passed to #initUndistortRectifyMap to
  1679. initialize the rectification map for each camera.
  1680. See below the screenshot from the stereo_calib.cpp sample. Some red horizontal lines pass through
  1681. the corresponding image regions. This means that the images are well rectified, which is what most
  1682. stereo correspondence algorithms rely on. The green rectangles are roi1 and roi2 . You see that
  1683. their interiors are all valid pixels.
  1684. ![image](pics/stereo_undistort.jpg)
  1685. */
  1686. CV_EXPORTS_W void stereoRectify( InputArray cameraMatrix1, InputArray distCoeffs1,
  1687. InputArray cameraMatrix2, InputArray distCoeffs2,
  1688. Size imageSize, InputArray R, InputArray T,
  1689. OutputArray R1, OutputArray R2,
  1690. OutputArray P1, OutputArray P2,
  1691. OutputArray Q, int flags = CALIB_ZERO_DISPARITY,
  1692. double alpha = -1, Size newImageSize = Size(),
  1693. CV_OUT Rect* validPixROI1 = 0, CV_OUT Rect* validPixROI2 = 0 );
  1694. /** @brief Computes a rectification transform for an uncalibrated stereo camera.
  1695. @param points1 Array of feature points in the first image.
  1696. @param points2 The corresponding points in the second image. The same formats as in
  1697. #findFundamentalMat are supported.
  1698. @param F Input fundamental matrix. It can be computed from the same set of point pairs using
  1699. #findFundamentalMat .
  1700. @param imgSize Size of the image.
  1701. @param H1 Output rectification homography matrix for the first image.
  1702. @param H2 Output rectification homography matrix for the second image.
  1703. @param threshold Optional threshold used to filter out the outliers. If the parameter is greater
  1704. than zero, all the point pairs that do not comply with the epipolar geometry (that is, the points
  1705. for which \f$|\texttt{points2[i]}^T*\texttt{F}*\texttt{points1[i]}|>\texttt{threshold}\f$ ) are
  1706. rejected prior to computing the homographies. Otherwise, all the points are considered inliers.
  1707. The function computes the rectification transformations without knowing intrinsic parameters of the
  1708. cameras and their relative position in the space, which explains the suffix "uncalibrated". Another
  1709. related difference from #stereoRectify is that the function outputs not the rectification
  1710. transformations in the object (3D) space, but the planar perspective transformations encoded by the
  1711. homography matrices H1 and H2 . The function implements the algorithm @cite Hartley99 .
  1712. @note
  1713. While the algorithm does not need to know the intrinsic parameters of the cameras, it heavily
  1714. depends on the epipolar geometry. Therefore, if the camera lenses have a significant distortion,
  1715. it would be better to correct it before computing the fundamental matrix and calling this
  1716. function. For example, distortion coefficients can be estimated for each head of stereo camera
  1717. separately by using #calibrateCamera . Then, the images can be corrected using #undistort , or
  1718. just the point coordinates can be corrected with #undistortPoints .
  1719. */
  1720. CV_EXPORTS_W bool stereoRectifyUncalibrated( InputArray points1, InputArray points2,
  1721. InputArray F, Size imgSize,
  1722. OutputArray H1, OutputArray H2,
  1723. double threshold = 5 );
  1724. //! computes the rectification transformations for 3-head camera, where all the heads are on the same line.
  1725. CV_EXPORTS_W float rectify3Collinear( InputArray cameraMatrix1, InputArray distCoeffs1,
  1726. InputArray cameraMatrix2, InputArray distCoeffs2,
  1727. InputArray cameraMatrix3, InputArray distCoeffs3,
  1728. InputArrayOfArrays imgpt1, InputArrayOfArrays imgpt3,
  1729. Size imageSize, InputArray R12, InputArray T12,
  1730. InputArray R13, InputArray T13,
  1731. OutputArray R1, OutputArray R2, OutputArray R3,
  1732. OutputArray P1, OutputArray P2, OutputArray P3,
  1733. OutputArray Q, double alpha, Size newImgSize,
  1734. CV_OUT Rect* roi1, CV_OUT Rect* roi2, int flags );
  1735. /** @brief Returns the new camera intrinsic matrix based on the free scaling parameter.
  1736. @param cameraMatrix Input camera intrinsic matrix.
  1737. @param distCoeffs Input vector of distortion coefficients
  1738. \f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
  1739. assumed.
  1740. @param imageSize Original image size.
  1741. @param alpha Free scaling parameter between 0 (when all the pixels in the undistorted image are
  1742. valid) and 1 (when all the source image pixels are retained in the undistorted image). See
  1743. #stereoRectify for details.
  1744. @param newImgSize Image size after rectification. By default, it is set to imageSize .
  1745. @param validPixROI Optional output rectangle that outlines all-good-pixels region in the
  1746. undistorted image. See roi1, roi2 description in #stereoRectify .
  1747. @param centerPrincipalPoint Optional flag that indicates whether in the new camera intrinsic matrix the
  1748. principal point should be at the image center or not. By default, the principal point is chosen to
  1749. best fit a subset of the source image (determined by alpha) to the corrected image.
  1750. @return new_camera_matrix Output new camera intrinsic matrix.
  1751. The function computes and returns the optimal new camera intrinsic matrix based on the free scaling parameter.
  1752. By varying this parameter, you may retrieve only sensible pixels alpha=0 , keep all the original
  1753. image pixels if there is valuable information in the corners alpha=1 , or get something in between.
  1754. When alpha\>0 , the undistorted result is likely to have some black pixels corresponding to
  1755. "virtual" pixels outside of the captured distorted image. The original camera intrinsic matrix, distortion
  1756. coefficients, the computed new camera intrinsic matrix, and newImageSize should be passed to
  1757. #initUndistortRectifyMap to produce the maps for #remap .
  1758. */
  1759. CV_EXPORTS_W Mat getOptimalNewCameraMatrix( InputArray cameraMatrix, InputArray distCoeffs,
  1760. Size imageSize, double alpha, Size newImgSize = Size(),
  1761. CV_OUT Rect* validPixROI = 0,
  1762. bool centerPrincipalPoint = false);
  1763. /** @brief Computes Hand-Eye calibration: \f$_{}^{g}\textrm{T}_c\f$
  1764. @param[in] R_gripper2base Rotation part extracted from the homogeneous matrix that transforms a point
  1765. expressed in the gripper frame to the robot base frame (\f$_{}^{b}\textrm{T}_g\f$).
  1766. This is a vector (`vector<Mat>`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors,
  1767. for all the transformations from gripper frame to robot base frame.
  1768. @param[in] t_gripper2base Translation part extracted from the homogeneous matrix that transforms a point
  1769. expressed in the gripper frame to the robot base frame (\f$_{}^{b}\textrm{T}_g\f$).
  1770. This is a vector (`vector<Mat>`) that contains the `(3x1)` translation vectors for all the transformations
  1771. from gripper frame to robot base frame.
  1772. @param[in] R_target2cam Rotation part extracted from the homogeneous matrix that transforms a point
  1773. expressed in the target frame to the camera frame (\f$_{}^{c}\textrm{T}_t\f$).
  1774. This is a vector (`vector<Mat>`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors,
  1775. for all the transformations from calibration target frame to camera frame.
  1776. @param[in] t_target2cam Rotation part extracted from the homogeneous matrix that transforms a point
  1777. expressed in the target frame to the camera frame (\f$_{}^{c}\textrm{T}_t\f$).
  1778. This is a vector (`vector<Mat>`) that contains the `(3x1)` translation vectors for all the transformations
  1779. from calibration target frame to camera frame.
  1780. @param[out] R_cam2gripper Estimated `(3x3)` rotation part extracted from the homogeneous matrix that transforms a point
  1781. expressed in the camera frame to the gripper frame (\f$_{}^{g}\textrm{T}_c\f$).
  1782. @param[out] t_cam2gripper Estimated `(3x1)` translation part extracted from the homogeneous matrix that transforms a point
  1783. expressed in the camera frame to the gripper frame (\f$_{}^{g}\textrm{T}_c\f$).
  1784. @param[in] method One of the implemented Hand-Eye calibration method, see cv::HandEyeCalibrationMethod
  1785. The function performs the Hand-Eye calibration using various methods. One approach consists in estimating the
  1786. rotation then the translation (separable solutions) and the following methods are implemented:
  1787. - R. Tsai, R. Lenz A New Technique for Fully Autonomous and Efficient 3D Robotics Hand/EyeCalibration \cite Tsai89
  1788. - F. Park, B. Martin Robot Sensor Calibration: Solving AX = XB on the Euclidean Group \cite Park94
  1789. - R. Horaud, F. Dornaika Hand-Eye Calibration \cite Horaud95
  1790. Another approach consists in estimating simultaneously the rotation and the translation (simultaneous solutions),
  1791. with the following implemented methods:
  1792. - N. Andreff, R. Horaud, B. Espiau On-line Hand-Eye Calibration \cite Andreff99
  1793. - K. Daniilidis Hand-Eye Calibration Using Dual Quaternions \cite Daniilidis98
  1794. The following picture describes the Hand-Eye calibration problem where the transformation between a camera ("eye")
  1795. mounted on a robot gripper ("hand") has to be estimated. This configuration is called eye-in-hand.
  1796. The eye-to-hand configuration consists in a static camera observing a calibration pattern mounted on the robot
  1797. end-effector. The transformation from the camera to the robot base frame can then be estimated by inputting
  1798. the suitable transformations to the function, see below.
  1799. ![](pics/hand-eye_figure.png)
  1800. The calibration procedure is the following:
  1801. - a static calibration pattern is used to estimate the transformation between the target frame
  1802. and the camera frame
  1803. - the robot gripper is moved in order to acquire several poses
  1804. - for each pose, the homogeneous transformation between the gripper frame and the robot base frame is recorded using for
  1805. instance the robot kinematics
  1806. \f[
  1807. \begin{bmatrix}
  1808. X_b\\
  1809. Y_b\\
  1810. Z_b\\
  1811. 1
  1812. \end{bmatrix}
  1813. =
  1814. \begin{bmatrix}
  1815. _{}^{b}\textrm{R}_g & _{}^{b}\textrm{t}_g \\
  1816. 0_{1 \times 3} & 1
  1817. \end{bmatrix}
  1818. \begin{bmatrix}
  1819. X_g\\
  1820. Y_g\\
  1821. Z_g\\
  1822. 1
  1823. \end{bmatrix}
  1824. \f]
  1825. - for each pose, the homogeneous transformation between the calibration target frame and the camera frame is recorded using
  1826. for instance a pose estimation method (PnP) from 2D-3D point correspondences
  1827. \f[
  1828. \begin{bmatrix}
  1829. X_c\\
  1830. Y_c\\
  1831. Z_c\\
  1832. 1
  1833. \end{bmatrix}
  1834. =
  1835. \begin{bmatrix}
  1836. _{}^{c}\textrm{R}_t & _{}^{c}\textrm{t}_t \\
  1837. 0_{1 \times 3} & 1
  1838. \end{bmatrix}
  1839. \begin{bmatrix}
  1840. X_t\\
  1841. Y_t\\
  1842. Z_t\\
  1843. 1
  1844. \end{bmatrix}
  1845. \f]
  1846. The Hand-Eye calibration procedure returns the following homogeneous transformation
  1847. \f[
  1848. \begin{bmatrix}
  1849. X_g\\
  1850. Y_g\\
  1851. Z_g\\
  1852. 1
  1853. \end{bmatrix}
  1854. =
  1855. \begin{bmatrix}
  1856. _{}^{g}\textrm{R}_c & _{}^{g}\textrm{t}_c \\
  1857. 0_{1 \times 3} & 1
  1858. \end{bmatrix}
  1859. \begin{bmatrix}
  1860. X_c\\
  1861. Y_c\\
  1862. Z_c\\
  1863. 1
  1864. \end{bmatrix}
  1865. \f]
  1866. This problem is also known as solving the \f$\mathbf{A}\mathbf{X}=\mathbf{X}\mathbf{B}\f$ equation:
  1867. - for an eye-in-hand configuration
  1868. \f[
  1869. \begin{align*}
  1870. ^{b}{\textrm{T}_g}^{(1)} \hspace{0.2em} ^{g}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(1)} &=
  1871. \hspace{0.1em} ^{b}{\textrm{T}_g}^{(2)} \hspace{0.2em} ^{g}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} \\
  1872. (^{b}{\textrm{T}_g}^{(2)})^{-1} \hspace{0.2em} ^{b}{\textrm{T}_g}^{(1)} \hspace{0.2em} ^{g}\textrm{T}_c &=
  1873. \hspace{0.1em} ^{g}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} (^{c}{\textrm{T}_t}^{(1)})^{-1} \\
  1874. \textrm{A}_i \textrm{X} &= \textrm{X} \textrm{B}_i \\
  1875. \end{align*}
  1876. \f]
  1877. - for an eye-to-hand configuration
  1878. \f[
  1879. \begin{align*}
  1880. ^{g}{\textrm{T}_b}^{(1)} \hspace{0.2em} ^{b}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(1)} &=
  1881. \hspace{0.1em} ^{g}{\textrm{T}_b}^{(2)} \hspace{0.2em} ^{b}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} \\
  1882. (^{g}{\textrm{T}_b}^{(2)})^{-1} \hspace{0.2em} ^{g}{\textrm{T}_b}^{(1)} \hspace{0.2em} ^{b}\textrm{T}_c &=
  1883. \hspace{0.1em} ^{b}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} (^{c}{\textrm{T}_t}^{(1)})^{-1} \\
  1884. \textrm{A}_i \textrm{X} &= \textrm{X} \textrm{B}_i \\
  1885. \end{align*}
  1886. \f]
  1887. \note
  1888. Additional information can be found on this [website](http://campar.in.tum.de/Chair/HandEyeCalibration).
  1889. \note
  1890. A minimum of 2 motions with non parallel rotation axes are necessary to determine the hand-eye transformation.
  1891. So at least 3 different poses are required, but it is strongly recommended to use many more poses.
  1892. */
  1893. CV_EXPORTS_W void calibrateHandEye( InputArrayOfArrays R_gripper2base, InputArrayOfArrays t_gripper2base,
  1894. InputArrayOfArrays R_target2cam, InputArrayOfArrays t_target2cam,
  1895. OutputArray R_cam2gripper, OutputArray t_cam2gripper,
  1896. HandEyeCalibrationMethod method=CALIB_HAND_EYE_TSAI );
  1897. /** @brief Computes Robot-World/Hand-Eye calibration: \f$_{}^{w}\textrm{T}_b\f$ and \f$_{}^{c}\textrm{T}_g\f$
  1898. @param[in] R_world2cam Rotation part extracted from the homogeneous matrix that transforms a point
  1899. expressed in the world frame to the camera frame (\f$_{}^{c}\textrm{T}_w\f$).
  1900. This is a vector (`vector<Mat>`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors,
  1901. for all the transformations from world frame to the camera frame.
  1902. @param[in] t_world2cam Translation part extracted from the homogeneous matrix that transforms a point
  1903. expressed in the world frame to the camera frame (\f$_{}^{c}\textrm{T}_w\f$).
  1904. This is a vector (`vector<Mat>`) that contains the `(3x1)` translation vectors for all the transformations
  1905. from world frame to the camera frame.
  1906. @param[in] R_base2gripper Rotation part extracted from the homogeneous matrix that transforms a point
  1907. expressed in the robot base frame to the gripper frame (\f$_{}^{g}\textrm{T}_b\f$).
  1908. This is a vector (`vector<Mat>`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors,
  1909. for all the transformations from robot base frame to the gripper frame.
  1910. @param[in] t_base2gripper Rotation part extracted from the homogeneous matrix that transforms a point
  1911. expressed in the robot base frame to the gripper frame (\f$_{}^{g}\textrm{T}_b\f$).
  1912. This is a vector (`vector<Mat>`) that contains the `(3x1)` translation vectors for all the transformations
  1913. from robot base frame to the gripper frame.
  1914. @param[out] R_base2world Estimated `(3x3)` rotation part extracted from the homogeneous matrix that transforms a point
  1915. expressed in the robot base frame to the world frame (\f$_{}^{w}\textrm{T}_b\f$).
  1916. @param[out] t_base2world Estimated `(3x1)` translation part extracted from the homogeneous matrix that transforms a point
  1917. expressed in the robot base frame to the world frame (\f$_{}^{w}\textrm{T}_b\f$).
  1918. @param[out] R_gripper2cam Estimated `(3x3)` rotation part extracted from the homogeneous matrix that transforms a point
  1919. expressed in the gripper frame to the camera frame (\f$_{}^{c}\textrm{T}_g\f$).
  1920. @param[out] t_gripper2cam Estimated `(3x1)` translation part extracted from the homogeneous matrix that transforms a point
  1921. expressed in the gripper frame to the camera frame (\f$_{}^{c}\textrm{T}_g\f$).
  1922. @param[in] method One of the implemented Robot-World/Hand-Eye calibration method, see cv::RobotWorldHandEyeCalibrationMethod
  1923. The function performs the Robot-World/Hand-Eye calibration using various methods. One approach consists in estimating the
  1924. rotation then the translation (separable solutions):
  1925. - M. Shah, Solving the robot-world/hand-eye calibration problem using the kronecker product \cite Shah2013SolvingTR
  1926. Another approach consists in estimating simultaneously the rotation and the translation (simultaneous solutions),
  1927. with the following implemented method:
  1928. - A. Li, L. Wang, and D. Wu, Simultaneous robot-world and hand-eye calibration using dual-quaternions and kronecker product \cite Li2010SimultaneousRA
  1929. The following picture describes the Robot-World/Hand-Eye calibration problem where the transformations between a robot and a world frame
  1930. and between a robot gripper ("hand") and a camera ("eye") mounted at the robot end-effector have to be estimated.
  1931. ![](pics/robot-world_hand-eye_figure.png)
  1932. The calibration procedure is the following:
  1933. - a static calibration pattern is used to estimate the transformation between the target frame
  1934. and the camera frame
  1935. - the robot gripper is moved in order to acquire several poses
  1936. - for each pose, the homogeneous transformation between the gripper frame and the robot base frame is recorded using for
  1937. instance the robot kinematics
  1938. \f[
  1939. \begin{bmatrix}
  1940. X_g\\
  1941. Y_g\\
  1942. Z_g\\
  1943. 1
  1944. \end{bmatrix}
  1945. =
  1946. \begin{bmatrix}
  1947. _{}^{g}\textrm{R}_b & _{}^{g}\textrm{t}_b \\
  1948. 0_{1 \times 3} & 1
  1949. \end{bmatrix}
  1950. \begin{bmatrix}
  1951. X_b\\
  1952. Y_b\\
  1953. Z_b\\
  1954. 1
  1955. \end{bmatrix}
  1956. \f]
  1957. - for each pose, the homogeneous transformation between the calibration target frame (the world frame) and the camera frame is recorded using
  1958. for instance a pose estimation method (PnP) from 2D-3D point correspondences
  1959. \f[
  1960. \begin{bmatrix}
  1961. X_c\\
  1962. Y_c\\
  1963. Z_c\\
  1964. 1
  1965. \end{bmatrix}
  1966. =
  1967. \begin{bmatrix}
  1968. _{}^{c}\textrm{R}_w & _{}^{c}\textrm{t}_w \\
  1969. 0_{1 \times 3} & 1
  1970. \end{bmatrix}
  1971. \begin{bmatrix}
  1972. X_w\\
  1973. Y_w\\
  1974. Z_w\\
  1975. 1
  1976. \end{bmatrix}
  1977. \f]
  1978. The Robot-World/Hand-Eye calibration procedure returns the following homogeneous transformations
  1979. \f[
  1980. \begin{bmatrix}
  1981. X_w\\
  1982. Y_w\\
  1983. Z_w\\
  1984. 1
  1985. \end{bmatrix}
  1986. =
  1987. \begin{bmatrix}
  1988. _{}^{w}\textrm{R}_b & _{}^{w}\textrm{t}_b \\
  1989. 0_{1 \times 3} & 1
  1990. \end{bmatrix}
  1991. \begin{bmatrix}
  1992. X_b\\
  1993. Y_b\\
  1994. Z_b\\
  1995. 1
  1996. \end{bmatrix}
  1997. \f]
  1998. \f[
  1999. \begin{bmatrix}
  2000. X_c\\
  2001. Y_c\\
  2002. Z_c\\
  2003. 1
  2004. \end{bmatrix}
  2005. =
  2006. \begin{bmatrix}
  2007. _{}^{c}\textrm{R}_g & _{}^{c}\textrm{t}_g \\
  2008. 0_{1 \times 3} & 1
  2009. \end{bmatrix}
  2010. \begin{bmatrix}
  2011. X_g\\
  2012. Y_g\\
  2013. Z_g\\
  2014. 1
  2015. \end{bmatrix}
  2016. \f]
  2017. This problem is also known as solving the \f$\mathbf{A}\mathbf{X}=\mathbf{Z}\mathbf{B}\f$ equation, with:
  2018. - \f$\mathbf{A} \Leftrightarrow \hspace{0.1em} _{}^{c}\textrm{T}_w\f$
  2019. - \f$\mathbf{X} \Leftrightarrow \hspace{0.1em} _{}^{w}\textrm{T}_b\f$
  2020. - \f$\mathbf{Z} \Leftrightarrow \hspace{0.1em} _{}^{c}\textrm{T}_g\f$
  2021. - \f$\mathbf{B} \Leftrightarrow \hspace{0.1em} _{}^{g}\textrm{T}_b\f$
  2022. \note
  2023. At least 3 measurements are required (input vectors size must be greater or equal to 3).
  2024. */
  2025. CV_EXPORTS_W void calibrateRobotWorldHandEye( InputArrayOfArrays R_world2cam, InputArrayOfArrays t_world2cam,
  2026. InputArrayOfArrays R_base2gripper, InputArrayOfArrays t_base2gripper,
  2027. OutputArray R_base2world, OutputArray t_base2world,
  2028. OutputArray R_gripper2cam, OutputArray t_gripper2cam,
  2029. RobotWorldHandEyeCalibrationMethod method=CALIB_ROBOT_WORLD_HAND_EYE_SHAH );
  2030. /** @brief Converts points from Euclidean to homogeneous space.
  2031. @param src Input vector of N-dimensional points.
  2032. @param dst Output vector of N+1-dimensional points.
  2033. The function converts points from Euclidean to homogeneous space by appending 1's to the tuple of
  2034. point coordinates. That is, each point (x1, x2, ..., xn) is converted to (x1, x2, ..., xn, 1).
  2035. */
  2036. CV_EXPORTS_W void convertPointsToHomogeneous( InputArray src, OutputArray dst );
  2037. /** @brief Converts points from homogeneous to Euclidean space.
  2038. @param src Input vector of N-dimensional points.
  2039. @param dst Output vector of N-1-dimensional points.
  2040. The function converts points homogeneous to Euclidean space using perspective projection. That is,
  2041. each point (x1, x2, ... x(n-1), xn) is converted to (x1/xn, x2/xn, ..., x(n-1)/xn). When xn=0, the
  2042. output point coordinates will be (0,0,0,...).
  2043. */
  2044. CV_EXPORTS_W void convertPointsFromHomogeneous( InputArray src, OutputArray dst );
  2045. /** @brief Converts points to/from homogeneous coordinates.
  2046. @param src Input array or vector of 2D, 3D, or 4D points.
  2047. @param dst Output vector of 2D, 3D, or 4D points.
  2048. The function converts 2D or 3D points from/to homogeneous coordinates by calling either
  2049. #convertPointsToHomogeneous or #convertPointsFromHomogeneous.
  2050. @note The function is obsolete. Use one of the previous two functions instead.
  2051. */
  2052. CV_EXPORTS void convertPointsHomogeneous( InputArray src, OutputArray dst );
  2053. /** @brief Calculates a fundamental matrix from the corresponding points in two images.
  2054. @param points1 Array of N points from the first image. The point coordinates should be
  2055. floating-point (single or double precision).
  2056. @param points2 Array of the second image points of the same size and format as points1 .
  2057. @param method Method for computing a fundamental matrix.
  2058. - @ref FM_7POINT for a 7-point algorithm. \f$N = 7\f$
  2059. - @ref FM_8POINT for an 8-point algorithm. \f$N \ge 8\f$
  2060. - @ref FM_RANSAC for the RANSAC algorithm. \f$N \ge 8\f$
  2061. - @ref FM_LMEDS for the LMedS algorithm. \f$N \ge 8\f$
  2062. @param ransacReprojThreshold Parameter used only for RANSAC. It is the maximum distance from a point to an epipolar
  2063. line in pixels, beyond which the point is considered an outlier and is not used for computing the
  2064. final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the
  2065. point localization, image resolution, and the image noise.
  2066. @param confidence Parameter used for the RANSAC and LMedS methods only. It specifies a desirable level
  2067. of confidence (probability) that the estimated matrix is correct.
  2068. @param[out] mask optional output mask
  2069. @param maxIters The maximum number of robust method iterations.
  2070. The epipolar geometry is described by the following equation:
  2071. \f[[p_2; 1]^T F [p_1; 1] = 0\f]
  2072. where \f$F\f$ is a fundamental matrix, \f$p_1\f$ and \f$p_2\f$ are corresponding points in the first and the
  2073. second images, respectively.
  2074. The function calculates the fundamental matrix using one of four methods listed above and returns
  2075. the found fundamental matrix. Normally just one matrix is found. But in case of the 7-point
  2076. algorithm, the function may return up to 3 solutions ( \f$9 \times 3\f$ matrix that stores all 3
  2077. matrices sequentially).
  2078. The calculated fundamental matrix may be passed further to computeCorrespondEpilines that finds the
  2079. epipolar lines corresponding to the specified points. It can also be passed to
  2080. #stereoRectifyUncalibrated to compute the rectification transformation. :
  2081. @code
  2082. // Example. Estimation of fundamental matrix using the RANSAC algorithm
  2083. int point_count = 100;
  2084. vector<Point2f> points1(point_count);
  2085. vector<Point2f> points2(point_count);
  2086. // initialize the points here ...
  2087. for( int i = 0; i < point_count; i++ )
  2088. {
  2089. points1[i] = ...;
  2090. points2[i] = ...;
  2091. }
  2092. Mat fundamental_matrix =
  2093. findFundamentalMat(points1, points2, FM_RANSAC, 3, 0.99);
  2094. @endcode
  2095. */
  2096. CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2,
  2097. int method, double ransacReprojThreshold, double confidence,
  2098. int maxIters, OutputArray mask = noArray() );
  2099. /** @overload */
  2100. CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2,
  2101. int method = FM_RANSAC,
  2102. double ransacReprojThreshold = 3., double confidence = 0.99,
  2103. OutputArray mask = noArray() );
  2104. /** @overload */
  2105. CV_EXPORTS Mat findFundamentalMat( InputArray points1, InputArray points2,
  2106. OutputArray mask, int method = FM_RANSAC,
  2107. double ransacReprojThreshold = 3., double confidence = 0.99 );
  2108. CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2,
  2109. OutputArray mask, const UsacParams &params);
  2110. /** @brief Calculates an essential matrix from the corresponding points in two images.
  2111. @param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should
  2112. be floating-point (single or double precision).
  2113. @param points2 Array of the second image points of the same size and format as points1 .
  2114. @param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ .
  2115. Note that this function assumes that points1 and points2 are feature points from cameras with the
  2116. same camera intrinsic matrix. If this assumption does not hold for your use case, use
  2117. #undistortPoints with `P = cv::NoArray()` for both cameras to transform image points
  2118. to normalized image coordinates, which are valid for the identity camera intrinsic matrix. When
  2119. passing these coordinates, pass the identity matrix for this parameter.
  2120. @param method Method for computing an essential matrix.
  2121. - @ref RANSAC for the RANSAC algorithm.
  2122. - @ref LMEDS for the LMedS algorithm.
  2123. @param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of
  2124. confidence (probability) that the estimated matrix is correct.
  2125. @param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar
  2126. line in pixels, beyond which the point is considered an outlier and is not used for computing the
  2127. final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the
  2128. point localization, image resolution, and the image noise.
  2129. @param mask Output array of N elements, every element of which is set to 0 for outliers and to 1
  2130. for the other points. The array is computed only in the RANSAC and LMedS methods.
  2131. @param maxIters The maximum number of robust method iterations.
  2132. This function estimates essential matrix based on the five-point algorithm solver in @cite Nister03 .
  2133. @cite SteweniusCFS is also a related. The epipolar geometry is described by the following equation:
  2134. \f[[p_2; 1]^T K^{-T} E K^{-1} [p_1; 1] = 0\f]
  2135. where \f$E\f$ is an essential matrix, \f$p_1\f$ and \f$p_2\f$ are corresponding points in the first and the
  2136. second images, respectively. The result of this function may be passed further to
  2137. #decomposeEssentialMat or #recoverPose to recover the relative pose between cameras.
  2138. */
  2139. CV_EXPORTS_W
  2140. Mat findEssentialMat(
  2141. InputArray points1, InputArray points2,
  2142. InputArray cameraMatrix, int method = RANSAC,
  2143. double prob = 0.999, double threshold = 1.0,
  2144. int maxIters = 1000, OutputArray mask = noArray()
  2145. );
  2146. /** @overload */
  2147. CV_EXPORTS
  2148. Mat findEssentialMat(
  2149. InputArray points1, InputArray points2,
  2150. InputArray cameraMatrix, int method,
  2151. double prob, double threshold,
  2152. OutputArray mask
  2153. ); // TODO remove from OpenCV 5.0
  2154. /** @overload
  2155. @param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should
  2156. be floating-point (single or double precision).
  2157. @param points2 Array of the second image points of the same size and format as points1 .
  2158. @param focal focal length of the camera. Note that this function assumes that points1 and points2
  2159. are feature points from cameras with same focal length and principal point.
  2160. @param pp principal point of the camera.
  2161. @param method Method for computing a fundamental matrix.
  2162. - @ref RANSAC for the RANSAC algorithm.
  2163. - @ref LMEDS for the LMedS algorithm.
  2164. @param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar
  2165. line in pixels, beyond which the point is considered an outlier and is not used for computing the
  2166. final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the
  2167. point localization, image resolution, and the image noise.
  2168. @param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of
  2169. confidence (probability) that the estimated matrix is correct.
  2170. @param mask Output array of N elements, every element of which is set to 0 for outliers and to 1
  2171. for the other points. The array is computed only in the RANSAC and LMedS methods.
  2172. @param maxIters The maximum number of robust method iterations.
  2173. This function differs from the one above that it computes camera intrinsic matrix from focal length and
  2174. principal point:
  2175. \f[A =
  2176. \begin{bmatrix}
  2177. f & 0 & x_{pp} \\
  2178. 0 & f & y_{pp} \\
  2179. 0 & 0 & 1
  2180. \end{bmatrix}\f]
  2181. */
  2182. CV_EXPORTS_W
  2183. Mat findEssentialMat(
  2184. InputArray points1, InputArray points2,
  2185. double focal = 1.0, Point2d pp = Point2d(0, 0),
  2186. int method = RANSAC, double prob = 0.999,
  2187. double threshold = 1.0, int maxIters = 1000,
  2188. OutputArray mask = noArray()
  2189. );
  2190. /** @overload */
  2191. CV_EXPORTS
  2192. Mat findEssentialMat(
  2193. InputArray points1, InputArray points2,
  2194. double focal, Point2d pp,
  2195. int method, double prob,
  2196. double threshold, OutputArray mask
  2197. ); // TODO remove from OpenCV 5.0
  2198. /** @brief Calculates an essential matrix from the corresponding points in two images from potentially two different cameras.
  2199. @param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should
  2200. be floating-point (single or double precision).
  2201. @param points2 Array of the second image points of the same size and format as points1 .
  2202. @param cameraMatrix1 Camera matrix \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
  2203. Note that this function assumes that points1 and points2 are feature points from cameras with the
  2204. same camera matrix. If this assumption does not hold for your use case, use
  2205. #undistortPoints with `P = cv::NoArray()` for both cameras to transform image points
  2206. to normalized image coordinates, which are valid for the identity camera matrix. When
  2207. passing these coordinates, pass the identity matrix for this parameter.
  2208. @param cameraMatrix2 Camera matrix \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
  2209. Note that this function assumes that points1 and points2 are feature points from cameras with the
  2210. same camera matrix. If this assumption does not hold for your use case, use
  2211. #undistortPoints with `P = cv::NoArray()` for both cameras to transform image points
  2212. to normalized image coordinates, which are valid for the identity camera matrix. When
  2213. passing these coordinates, pass the identity matrix for this parameter.
  2214. @param distCoeffs1 Input vector of distortion coefficients
  2215. \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
  2216. of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
  2217. @param distCoeffs2 Input vector of distortion coefficients
  2218. \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
  2219. of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
  2220. @param method Method for computing an essential matrix.
  2221. - @ref RANSAC for the RANSAC algorithm.
  2222. - @ref LMEDS for the LMedS algorithm.
  2223. @param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of
  2224. confidence (probability) that the estimated matrix is correct.
  2225. @param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar
  2226. line in pixels, beyond which the point is considered an outlier and is not used for computing the
  2227. final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the
  2228. point localization, image resolution, and the image noise.
  2229. @param mask Output array of N elements, every element of which is set to 0 for outliers and to 1
  2230. for the other points. The array is computed only in the RANSAC and LMedS methods.
  2231. This function estimates essential matrix based on the five-point algorithm solver in @cite Nister03 .
  2232. @cite SteweniusCFS is also a related. The epipolar geometry is described by the following equation:
  2233. \f[[p_2; 1]^T K^{-T} E K^{-1} [p_1; 1] = 0\f]
  2234. where \f$E\f$ is an essential matrix, \f$p_1\f$ and \f$p_2\f$ are corresponding points in the first and the
  2235. second images, respectively. The result of this function may be passed further to
  2236. #decomposeEssentialMat or #recoverPose to recover the relative pose between cameras.
  2237. */
  2238. CV_EXPORTS_W Mat findEssentialMat( InputArray points1, InputArray points2,
  2239. InputArray cameraMatrix1, InputArray distCoeffs1,
  2240. InputArray cameraMatrix2, InputArray distCoeffs2,
  2241. int method = RANSAC,
  2242. double prob = 0.999, double threshold = 1.0,
  2243. OutputArray mask = noArray() );
  2244. CV_EXPORTS_W Mat findEssentialMat( InputArray points1, InputArray points2,
  2245. InputArray cameraMatrix1, InputArray cameraMatrix2,
  2246. InputArray dist_coeff1, InputArray dist_coeff2, OutputArray mask,
  2247. const UsacParams &params);
  2248. /** @brief Decompose an essential matrix to possible rotations and translation.
  2249. @param E The input essential matrix.
  2250. @param R1 One possible rotation matrix.
  2251. @param R2 Another possible rotation matrix.
  2252. @param t One possible translation.
  2253. This function decomposes the essential matrix E using svd decomposition @cite HartleyZ00. In
  2254. general, four possible poses exist for the decomposition of E. They are \f$[R_1, t]\f$,
  2255. \f$[R_1, -t]\f$, \f$[R_2, t]\f$, \f$[R_2, -t]\f$.
  2256. If E gives the epipolar constraint \f$[p_2; 1]^T A^{-T} E A^{-1} [p_1; 1] = 0\f$ between the image
  2257. points \f$p_1\f$ in the first image and \f$p_2\f$ in second image, then any of the tuples
  2258. \f$[R_1, t]\f$, \f$[R_1, -t]\f$, \f$[R_2, t]\f$, \f$[R_2, -t]\f$ is a change of basis from the first
  2259. camera's coordinate system to the second camera's coordinate system. However, by decomposing E, one
  2260. can only get the direction of the translation. For this reason, the translation t is returned with
  2261. unit length.
  2262. */
  2263. CV_EXPORTS_W void decomposeEssentialMat( InputArray E, OutputArray R1, OutputArray R2, OutputArray t );
  2264. /** @brief Recovers the relative camera rotation and the translation from corresponding points in two images from two different cameras, using cheirality check. Returns the number of
  2265. inliers that pass the check.
  2266. @param points1 Array of N 2D points from the first image. The point coordinates should be
  2267. floating-point (single or double precision).
  2268. @param points2 Array of the second image points of the same size and format as points1 .
  2269. @param cameraMatrix1 Input/output camera matrix for the first camera, the same as in
  2270. @ref calibrateCamera. Furthermore, for the stereo case, additional flags may be used, see below.
  2271. @param distCoeffs1 Input/output vector of distortion coefficients, the same as in
  2272. @ref calibrateCamera.
  2273. @param cameraMatrix2 Input/output camera matrix for the first camera, the same as in
  2274. @ref calibrateCamera. Furthermore, for the stereo case, additional flags may be used, see below.
  2275. @param distCoeffs2 Input/output vector of distortion coefficients, the same as in
  2276. @ref calibrateCamera.
  2277. @param E The output essential matrix.
  2278. @param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple
  2279. that performs a change of basis from the first camera's coordinate system to the second camera's
  2280. coordinate system. Note that, in general, t can not be used for this tuple, see the parameter
  2281. described below.
  2282. @param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and
  2283. therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit
  2284. length.
  2285. @param method Method for computing an essential matrix.
  2286. - @ref RANSAC for the RANSAC algorithm.
  2287. - @ref LMEDS for the LMedS algorithm.
  2288. @param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of
  2289. confidence (probability) that the estimated matrix is correct.
  2290. @param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar
  2291. line in pixels, beyond which the point is considered an outlier and is not used for computing the
  2292. final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the
  2293. point localization, image resolution, and the image noise.
  2294. @param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks
  2295. inliers in points1 and points2 for then given essential matrix E. Only these inliers will be used to
  2296. recover pose. In the output mask only inliers which pass the cheirality check.
  2297. This function decomposes an essential matrix using @ref decomposeEssentialMat and then verifies
  2298. possible pose hypotheses by doing cheirality check. The cheirality check means that the
  2299. triangulated 3D points should have positive depth. Some details can be found in @cite Nister03.
  2300. This function can be used to process the output E and mask from @ref findEssentialMat. In this
  2301. scenario, points1 and points2 are the same input for findEssentialMat.:
  2302. @code
  2303. // Example. Estimation of fundamental matrix using the RANSAC algorithm
  2304. int point_count = 100;
  2305. vector<Point2f> points1(point_count);
  2306. vector<Point2f> points2(point_count);
  2307. // initialize the points here ...
  2308. for( int i = 0; i < point_count; i++ )
  2309. {
  2310. points1[i] = ...;
  2311. points2[i] = ...;
  2312. }
  2313. // Input: camera calibration of both cameras, for example using intrinsic chessboard calibration.
  2314. Mat cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2;
  2315. // Output: Essential matrix, relative rotation and relative translation.
  2316. Mat E, R, t, mask;
  2317. recoverPose(points1, points2, cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, E, R, t, mask);
  2318. @endcode
  2319. */
  2320. CV_EXPORTS_W int recoverPose( InputArray points1, InputArray points2,
  2321. InputArray cameraMatrix1, InputArray distCoeffs1,
  2322. InputArray cameraMatrix2, InputArray distCoeffs2,
  2323. OutputArray E, OutputArray R, OutputArray t,
  2324. int method = cv::RANSAC, double prob = 0.999, double threshold = 1.0,
  2325. InputOutputArray mask = noArray());
  2326. /** @brief Recovers the relative camera rotation and the translation from an estimated essential
  2327. matrix and the corresponding points in two images, using cheirality check. Returns the number of
  2328. inliers that pass the check.
  2329. @param E The input essential matrix.
  2330. @param points1 Array of N 2D points from the first image. The point coordinates should be
  2331. floating-point (single or double precision).
  2332. @param points2 Array of the second image points of the same size and format as points1 .
  2333. @param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ .
  2334. Note that this function assumes that points1 and points2 are feature points from cameras with the
  2335. same camera intrinsic matrix.
  2336. @param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple
  2337. that performs a change of basis from the first camera's coordinate system to the second camera's
  2338. coordinate system. Note that, in general, t can not be used for this tuple, see the parameter
  2339. described below.
  2340. @param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and
  2341. therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit
  2342. length.
  2343. @param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks
  2344. inliers in points1 and points2 for then given essential matrix E. Only these inliers will be used to
  2345. recover pose. In the output mask only inliers which pass the cheirality check.
  2346. This function decomposes an essential matrix using @ref decomposeEssentialMat and then verifies
  2347. possible pose hypotheses by doing cheirality check. The cheirality check means that the
  2348. triangulated 3D points should have positive depth. Some details can be found in @cite Nister03.
  2349. This function can be used to process the output E and mask from @ref findEssentialMat. In this
  2350. scenario, points1 and points2 are the same input for #findEssentialMat :
  2351. @code
  2352. // Example. Estimation of fundamental matrix using the RANSAC algorithm
  2353. int point_count = 100;
  2354. vector<Point2f> points1(point_count);
  2355. vector<Point2f> points2(point_count);
  2356. // initialize the points here ...
  2357. for( int i = 0; i < point_count; i++ )
  2358. {
  2359. points1[i] = ...;
  2360. points2[i] = ...;
  2361. }
  2362. // cametra matrix with both focal lengths = 1, and principal point = (0, 0)
  2363. Mat cameraMatrix = Mat::eye(3, 3, CV_64F);
  2364. Mat E, R, t, mask;
  2365. E = findEssentialMat(points1, points2, cameraMatrix, RANSAC, 0.999, 1.0, mask);
  2366. recoverPose(E, points1, points2, cameraMatrix, R, t, mask);
  2367. @endcode
  2368. */
  2369. CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2,
  2370. InputArray cameraMatrix, OutputArray R, OutputArray t,
  2371. InputOutputArray mask = noArray() );
  2372. /** @overload
  2373. @param E The input essential matrix.
  2374. @param points1 Array of N 2D points from the first image. The point coordinates should be
  2375. floating-point (single or double precision).
  2376. @param points2 Array of the second image points of the same size and format as points1 .
  2377. @param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple
  2378. that performs a change of basis from the first camera's coordinate system to the second camera's
  2379. coordinate system. Note that, in general, t can not be used for this tuple, see the parameter
  2380. description below.
  2381. @param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and
  2382. therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit
  2383. length.
  2384. @param focal Focal length of the camera. Note that this function assumes that points1 and points2
  2385. are feature points from cameras with same focal length and principal point.
  2386. @param pp principal point of the camera.
  2387. @param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks
  2388. inliers in points1 and points2 for then given essential matrix E. Only these inliers will be used to
  2389. recover pose. In the output mask only inliers which pass the cheirality check.
  2390. This function differs from the one above that it computes camera intrinsic matrix from focal length and
  2391. principal point:
  2392. \f[A =
  2393. \begin{bmatrix}
  2394. f & 0 & x_{pp} \\
  2395. 0 & f & y_{pp} \\
  2396. 0 & 0 & 1
  2397. \end{bmatrix}\f]
  2398. */
  2399. CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2,
  2400. OutputArray R, OutputArray t,
  2401. double focal = 1.0, Point2d pp = Point2d(0, 0),
  2402. InputOutputArray mask = noArray() );
  2403. /** @overload
  2404. @param E The input essential matrix.
  2405. @param points1 Array of N 2D points from the first image. The point coordinates should be
  2406. floating-point (single or double precision).
  2407. @param points2 Array of the second image points of the same size and format as points1.
  2408. @param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ .
  2409. Note that this function assumes that points1 and points2 are feature points from cameras with the
  2410. same camera intrinsic matrix.
  2411. @param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple
  2412. that performs a change of basis from the first camera's coordinate system to the second camera's
  2413. coordinate system. Note that, in general, t can not be used for this tuple, see the parameter
  2414. description below.
  2415. @param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and
  2416. therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit
  2417. length.
  2418. @param distanceThresh threshold distance which is used to filter out far away points (i.e. infinite
  2419. points).
  2420. @param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks
  2421. inliers in points1 and points2 for then given essential matrix E. Only these inliers will be used to
  2422. recover pose. In the output mask only inliers which pass the cheirality check.
  2423. @param triangulatedPoints 3D points which were reconstructed by triangulation.
  2424. This function differs from the one above that it outputs the triangulated 3D point that are used for
  2425. the cheirality check.
  2426. */
  2427. CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2,
  2428. InputArray cameraMatrix, OutputArray R, OutputArray t, double distanceThresh, InputOutputArray mask = noArray(),
  2429. OutputArray triangulatedPoints = noArray());
  2430. /** @brief For points in an image of a stereo pair, computes the corresponding epilines in the other image.
  2431. @param points Input points. \f$N \times 1\f$ or \f$1 \times N\f$ matrix of type CV_32FC2 or
  2432. vector\<Point2f\> .
  2433. @param whichImage Index of the image (1 or 2) that contains the points .
  2434. @param F Fundamental matrix that can be estimated using #findFundamentalMat or #stereoRectify .
  2435. @param lines Output vector of the epipolar lines corresponding to the points in the other image.
  2436. Each line \f$ax + by + c=0\f$ is encoded by 3 numbers \f$(a, b, c)\f$ .
  2437. For every point in one of the two images of a stereo pair, the function finds the equation of the
  2438. corresponding epipolar line in the other image.
  2439. From the fundamental matrix definition (see #findFundamentalMat ), line \f$l^{(2)}_i\f$ in the second
  2440. image for the point \f$p^{(1)}_i\f$ in the first image (when whichImage=1 ) is computed as:
  2441. \f[l^{(2)}_i = F p^{(1)}_i\f]
  2442. And vice versa, when whichImage=2, \f$l^{(1)}_i\f$ is computed from \f$p^{(2)}_i\f$ as:
  2443. \f[l^{(1)}_i = F^T p^{(2)}_i\f]
  2444. Line coefficients are defined up to a scale. They are normalized so that \f$a_i^2+b_i^2=1\f$ .
  2445. */
  2446. CV_EXPORTS_W void computeCorrespondEpilines( InputArray points, int whichImage,
  2447. InputArray F, OutputArray lines );
  2448. /** @brief This function reconstructs 3-dimensional points (in homogeneous coordinates) by using
  2449. their observations with a stereo camera.
  2450. @param projMatr1 3x4 projection matrix of the first camera, i.e. this matrix projects 3D points
  2451. given in the world's coordinate system into the first image.
  2452. @param projMatr2 3x4 projection matrix of the second camera, i.e. this matrix projects 3D points
  2453. given in the world's coordinate system into the second image.
  2454. @param projPoints1 2xN array of feature points in the first image. In the case of the c++ version,
  2455. it can be also a vector of feature points or two-channel matrix of size 1xN or Nx1.
  2456. @param projPoints2 2xN array of corresponding points in the second image. In the case of the c++
  2457. version, it can be also a vector of feature points or two-channel matrix of size 1xN or Nx1.
  2458. @param points4D 4xN array of reconstructed points in homogeneous coordinates. These points are
  2459. returned in the world's coordinate system.
  2460. @note
  2461. Keep in mind that all input data should be of float type in order for this function to work.
  2462. @note
  2463. If the projection matrices from @ref stereoRectify are used, then the returned points are
  2464. represented in the first camera's rectified coordinate system.
  2465. @sa
  2466. reprojectImageTo3D
  2467. */
  2468. CV_EXPORTS_W void triangulatePoints( InputArray projMatr1, InputArray projMatr2,
  2469. InputArray projPoints1, InputArray projPoints2,
  2470. OutputArray points4D );
  2471. /** @brief Refines coordinates of corresponding points.
  2472. @param F 3x3 fundamental matrix.
  2473. @param points1 1xN array containing the first set of points.
  2474. @param points2 1xN array containing the second set of points.
  2475. @param newPoints1 The optimized points1.
  2476. @param newPoints2 The optimized points2.
  2477. The function implements the Optimal Triangulation Method (see Multiple View Geometry for details).
  2478. For each given point correspondence points1[i] \<-\> points2[i], and a fundamental matrix F, it
  2479. computes the corrected correspondences newPoints1[i] \<-\> newPoints2[i] that minimize the geometric
  2480. error \f$d(points1[i], newPoints1[i])^2 + d(points2[i],newPoints2[i])^2\f$ (where \f$d(a,b)\f$ is the
  2481. geometric distance between points \f$a\f$ and \f$b\f$ ) subject to the epipolar constraint
  2482. \f$newPoints2^T * F * newPoints1 = 0\f$ .
  2483. */
  2484. CV_EXPORTS_W void correctMatches( InputArray F, InputArray points1, InputArray points2,
  2485. OutputArray newPoints1, OutputArray newPoints2 );
  2486. /** @brief Filters off small noise blobs (speckles) in the disparity map
  2487. @param img The input 16-bit signed disparity image
  2488. @param newVal The disparity value used to paint-off the speckles
  2489. @param maxSpeckleSize The maximum speckle size to consider it a speckle. Larger blobs are not
  2490. affected by the algorithm
  2491. @param maxDiff Maximum difference between neighbor disparity pixels to put them into the same
  2492. blob. Note that since StereoBM, StereoSGBM and may be other algorithms return a fixed-point
  2493. disparity map, where disparity values are multiplied by 16, this scale factor should be taken into
  2494. account when specifying this parameter value.
  2495. @param buf The optional temporary buffer to avoid memory allocation within the function.
  2496. */
  2497. CV_EXPORTS_W void filterSpeckles( InputOutputArray img, double newVal,
  2498. int maxSpeckleSize, double maxDiff,
  2499. InputOutputArray buf = noArray() );
  2500. //! computes valid disparity ROI from the valid ROIs of the rectified images (that are returned by #stereoRectify)
  2501. CV_EXPORTS_W Rect getValidDisparityROI( Rect roi1, Rect roi2,
  2502. int minDisparity, int numberOfDisparities,
  2503. int blockSize );
  2504. //! validates disparity using the left-right check. The matrix "cost" should be computed by the stereo correspondence algorithm
  2505. CV_EXPORTS_W void validateDisparity( InputOutputArray disparity, InputArray cost,
  2506. int minDisparity, int numberOfDisparities,
  2507. int disp12MaxDisp = 1 );
  2508. /** @brief Reprojects a disparity image to 3D space.
  2509. @param disparity Input single-channel 8-bit unsigned, 16-bit signed, 32-bit signed or 32-bit
  2510. floating-point disparity image. The values of 8-bit / 16-bit signed formats are assumed to have no
  2511. fractional bits. If the disparity is 16-bit signed format, as computed by @ref StereoBM or
  2512. @ref StereoSGBM and maybe other algorithms, it should be divided by 16 (and scaled to float) before
  2513. being used here.
  2514. @param _3dImage Output 3-channel floating-point image of the same size as disparity. Each element of
  2515. _3dImage(x,y) contains 3D coordinates of the point (x,y) computed from the disparity map. If one
  2516. uses Q obtained by @ref stereoRectify, then the returned points are represented in the first
  2517. camera's rectified coordinate system.
  2518. @param Q \f$4 \times 4\f$ perspective transformation matrix that can be obtained with
  2519. @ref stereoRectify.
  2520. @param handleMissingValues Indicates, whether the function should handle missing values (i.e.
  2521. points where the disparity was not computed). If handleMissingValues=true, then pixels with the
  2522. minimal disparity that corresponds to the outliers (see StereoMatcher::compute ) are transformed
  2523. to 3D points with a very large Z value (currently set to 10000).
  2524. @param ddepth The optional output array depth. If it is -1, the output image will have CV_32F
  2525. depth. ddepth can also be set to CV_16S, CV_32S or CV_32F.
  2526. The function transforms a single-channel disparity map to a 3-channel image representing a 3D
  2527. surface. That is, for each pixel (x,y) and the corresponding disparity d=disparity(x,y) , it
  2528. computes:
  2529. \f[\begin{bmatrix}
  2530. X \\
  2531. Y \\
  2532. Z \\
  2533. W
  2534. \end{bmatrix} = Q \begin{bmatrix}
  2535. x \\
  2536. y \\
  2537. \texttt{disparity} (x,y) \\
  2538. z
  2539. \end{bmatrix}.\f]
  2540. @sa
  2541. To reproject a sparse set of points {(x,y,d),...} to 3D space, use perspectiveTransform.
  2542. */
  2543. CV_EXPORTS_W void reprojectImageTo3D( InputArray disparity,
  2544. OutputArray _3dImage, InputArray Q,
  2545. bool handleMissingValues = false,
  2546. int ddepth = -1 );
  2547. /** @brief Calculates the Sampson Distance between two points.
  2548. The function cv::sampsonDistance calculates and returns the first order approximation of the geometric error as:
  2549. \f[
  2550. sd( \texttt{pt1} , \texttt{pt2} )=
  2551. \frac{(\texttt{pt2}^t \cdot \texttt{F} \cdot \texttt{pt1})^2}
  2552. {((\texttt{F} \cdot \texttt{pt1})(0))^2 +
  2553. ((\texttt{F} \cdot \texttt{pt1})(1))^2 +
  2554. ((\texttt{F}^t \cdot \texttt{pt2})(0))^2 +
  2555. ((\texttt{F}^t \cdot \texttt{pt2})(1))^2}
  2556. \f]
  2557. The fundamental matrix may be calculated using the #findFundamentalMat function. See @cite HartleyZ00 11.4.3 for details.
  2558. @param pt1 first homogeneous 2d point
  2559. @param pt2 second homogeneous 2d point
  2560. @param F fundamental matrix
  2561. @return The computed Sampson distance.
  2562. */
  2563. CV_EXPORTS_W double sampsonDistance(InputArray pt1, InputArray pt2, InputArray F);
  2564. /** @brief Computes an optimal affine transformation between two 3D point sets.
  2565. It computes
  2566. \f[
  2567. \begin{bmatrix}
  2568. x\\
  2569. y\\
  2570. z\\
  2571. \end{bmatrix}
  2572. =
  2573. \begin{bmatrix}
  2574. a_{11} & a_{12} & a_{13}\\
  2575. a_{21} & a_{22} & a_{23}\\
  2576. a_{31} & a_{32} & a_{33}\\
  2577. \end{bmatrix}
  2578. \begin{bmatrix}
  2579. X\\
  2580. Y\\
  2581. Z\\
  2582. \end{bmatrix}
  2583. +
  2584. \begin{bmatrix}
  2585. b_1\\
  2586. b_2\\
  2587. b_3\\
  2588. \end{bmatrix}
  2589. \f]
  2590. @param src First input 3D point set containing \f$(X,Y,Z)\f$.
  2591. @param dst Second input 3D point set containing \f$(x,y,z)\f$.
  2592. @param out Output 3D affine transformation matrix \f$3 \times 4\f$ of the form
  2593. \f[
  2594. \begin{bmatrix}
  2595. a_{11} & a_{12} & a_{13} & b_1\\
  2596. a_{21} & a_{22} & a_{23} & b_2\\
  2597. a_{31} & a_{32} & a_{33} & b_3\\
  2598. \end{bmatrix}
  2599. \f]
  2600. @param inliers Output vector indicating which points are inliers (1-inlier, 0-outlier).
  2601. @param ransacThreshold Maximum reprojection error in the RANSAC algorithm to consider a point as
  2602. an inlier.
  2603. @param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything
  2604. between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation
  2605. significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation.
  2606. The function estimates an optimal 3D affine transformation between two 3D point sets using the
  2607. RANSAC algorithm.
  2608. */
  2609. CV_EXPORTS_W int estimateAffine3D(InputArray src, InputArray dst,
  2610. OutputArray out, OutputArray inliers,
  2611. double ransacThreshold = 3, double confidence = 0.99);
  2612. /** @brief Computes an optimal affine transformation between two 3D point sets.
  2613. It computes \f$R,s,t\f$ minimizing \f$\sum{i} dst_i - c \cdot R \cdot src_i \f$
  2614. where \f$R\f$ is a 3x3 rotation matrix, \f$t\f$ is a 3x1 translation vector and \f$s\f$ is a
  2615. scalar size value. This is an implementation of the algorithm by Umeyama \cite umeyama1991least .
  2616. The estimated affine transform has a homogeneous scale which is a subclass of affine
  2617. transformations with 7 degrees of freedom. The paired point sets need to comprise at least 3
  2618. points each.
  2619. @param src First input 3D point set.
  2620. @param dst Second input 3D point set.
  2621. @param scale If null is passed, the scale parameter c will be assumed to be 1.0.
  2622. Else the pointed-to variable will be set to the optimal scale.
  2623. @param force_rotation If true, the returned rotation will never be a reflection.
  2624. This might be unwanted, e.g. when optimizing a transform between a right- and a
  2625. left-handed coordinate system.
  2626. @return 3D affine transformation matrix \f$3 \times 4\f$ of the form
  2627. \f[T =
  2628. \begin{bmatrix}
  2629. R & t\\
  2630. \end{bmatrix}
  2631. \f]
  2632. */
  2633. CV_EXPORTS_W cv::Mat estimateAffine3D(InputArray src, InputArray dst,
  2634. CV_OUT double* scale = nullptr, bool force_rotation = true);
  2635. /** @brief Computes an optimal translation between two 3D point sets.
  2636. *
  2637. * It computes
  2638. * \f[
  2639. * \begin{bmatrix}
  2640. * x\\
  2641. * y\\
  2642. * z\\
  2643. * \end{bmatrix}
  2644. * =
  2645. * \begin{bmatrix}
  2646. * X\\
  2647. * Y\\
  2648. * Z\\
  2649. * \end{bmatrix}
  2650. * +
  2651. * \begin{bmatrix}
  2652. * b_1\\
  2653. * b_2\\
  2654. * b_3\\
  2655. * \end{bmatrix}
  2656. * \f]
  2657. *
  2658. * @param src First input 3D point set containing \f$(X,Y,Z)\f$.
  2659. * @param dst Second input 3D point set containing \f$(x,y,z)\f$.
  2660. * @param out Output 3D translation vector \f$3 \times 1\f$ of the form
  2661. * \f[
  2662. * \begin{bmatrix}
  2663. * b_1 \\
  2664. * b_2 \\
  2665. * b_3 \\
  2666. * \end{bmatrix}
  2667. * \f]
  2668. * @param inliers Output vector indicating which points are inliers (1-inlier, 0-outlier).
  2669. * @param ransacThreshold Maximum reprojection error in the RANSAC algorithm to consider a point as
  2670. * an inlier.
  2671. * @param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything
  2672. * between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation
  2673. * significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation.
  2674. *
  2675. * The function estimates an optimal 3D translation between two 3D point sets using the
  2676. * RANSAC algorithm.
  2677. * */
  2678. CV_EXPORTS_W int estimateTranslation3D(InputArray src, InputArray dst,
  2679. OutputArray out, OutputArray inliers,
  2680. double ransacThreshold = 3, double confidence = 0.99);
  2681. /** @brief Computes an optimal affine transformation between two 2D point sets.
  2682. It computes
  2683. \f[
  2684. \begin{bmatrix}
  2685. x\\
  2686. y\\
  2687. \end{bmatrix}
  2688. =
  2689. \begin{bmatrix}
  2690. a_{11} & a_{12}\\
  2691. a_{21} & a_{22}\\
  2692. \end{bmatrix}
  2693. \begin{bmatrix}
  2694. X\\
  2695. Y\\
  2696. \end{bmatrix}
  2697. +
  2698. \begin{bmatrix}
  2699. b_1\\
  2700. b_2\\
  2701. \end{bmatrix}
  2702. \f]
  2703. @param from First input 2D point set containing \f$(X,Y)\f$.
  2704. @param to Second input 2D point set containing \f$(x,y)\f$.
  2705. @param inliers Output vector indicating which points are inliers (1-inlier, 0-outlier).
  2706. @param method Robust method used to compute transformation. The following methods are possible:
  2707. - @ref RANSAC - RANSAC-based robust method
  2708. - @ref LMEDS - Least-Median robust method
  2709. RANSAC is the default method.
  2710. @param ransacReprojThreshold Maximum reprojection error in the RANSAC algorithm to consider
  2711. a point as an inlier. Applies only to RANSAC.
  2712. @param maxIters The maximum number of robust method iterations.
  2713. @param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything
  2714. between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation
  2715. significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation.
  2716. @param refineIters Maximum number of iterations of refining algorithm (Levenberg-Marquardt).
  2717. Passing 0 will disable refining, so the output matrix will be output of robust method.
  2718. @return Output 2D affine transformation matrix \f$2 \times 3\f$ or empty matrix if transformation
  2719. could not be estimated. The returned matrix has the following form:
  2720. \f[
  2721. \begin{bmatrix}
  2722. a_{11} & a_{12} & b_1\\
  2723. a_{21} & a_{22} & b_2\\
  2724. \end{bmatrix}
  2725. \f]
  2726. The function estimates an optimal 2D affine transformation between two 2D point sets using the
  2727. selected robust algorithm.
  2728. The computed transformation is then refined further (using only inliers) with the
  2729. Levenberg-Marquardt method to reduce the re-projection error even more.
  2730. @note
  2731. The RANSAC method can handle practically any ratio of outliers but needs a threshold to
  2732. distinguish inliers from outliers. The method LMeDS does not need any threshold but it works
  2733. correctly only when there are more than 50% of inliers.
  2734. @sa estimateAffinePartial2D, getAffineTransform
  2735. */
  2736. CV_EXPORTS_W cv::Mat estimateAffine2D(InputArray from, InputArray to, OutputArray inliers = noArray(),
  2737. int method = RANSAC, double ransacReprojThreshold = 3,
  2738. size_t maxIters = 2000, double confidence = 0.99,
  2739. size_t refineIters = 10);
  2740. CV_EXPORTS_W cv::Mat estimateAffine2D(InputArray pts1, InputArray pts2, OutputArray inliers,
  2741. const UsacParams &params);
  2742. /** @brief Computes an optimal limited affine transformation with 4 degrees of freedom between
  2743. two 2D point sets.
  2744. @param from First input 2D point set.
  2745. @param to Second input 2D point set.
  2746. @param inliers Output vector indicating which points are inliers.
  2747. @param method Robust method used to compute transformation. The following methods are possible:
  2748. - @ref RANSAC - RANSAC-based robust method
  2749. - @ref LMEDS - Least-Median robust method
  2750. RANSAC is the default method.
  2751. @param ransacReprojThreshold Maximum reprojection error in the RANSAC algorithm to consider
  2752. a point as an inlier. Applies only to RANSAC.
  2753. @param maxIters The maximum number of robust method iterations.
  2754. @param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything
  2755. between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation
  2756. significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation.
  2757. @param refineIters Maximum number of iterations of refining algorithm (Levenberg-Marquardt).
  2758. Passing 0 will disable refining, so the output matrix will be output of robust method.
  2759. @return Output 2D affine transformation (4 degrees of freedom) matrix \f$2 \times 3\f$ or
  2760. empty matrix if transformation could not be estimated.
  2761. The function estimates an optimal 2D affine transformation with 4 degrees of freedom limited to
  2762. combinations of translation, rotation, and uniform scaling. Uses the selected algorithm for robust
  2763. estimation.
  2764. The computed transformation is then refined further (using only inliers) with the
  2765. Levenberg-Marquardt method to reduce the re-projection error even more.
  2766. Estimated transformation matrix is:
  2767. \f[ \begin{bmatrix} \cos(\theta) \cdot s & -\sin(\theta) \cdot s & t_x \\
  2768. \sin(\theta) \cdot s & \cos(\theta) \cdot s & t_y
  2769. \end{bmatrix} \f]
  2770. Where \f$ \theta \f$ is the rotation angle, \f$ s \f$ the scaling factor and \f$ t_x, t_y \f$ are
  2771. translations in \f$ x, y \f$ axes respectively.
  2772. @note
  2773. The RANSAC method can handle practically any ratio of outliers but need a threshold to
  2774. distinguish inliers from outliers. The method LMeDS does not need any threshold but it works
  2775. correctly only when there are more than 50% of inliers.
  2776. @sa estimateAffine2D, getAffineTransform
  2777. */
  2778. CV_EXPORTS_W cv::Mat estimateAffinePartial2D(InputArray from, InputArray to, OutputArray inliers = noArray(),
  2779. int method = RANSAC, double ransacReprojThreshold = 3,
  2780. size_t maxIters = 2000, double confidence = 0.99,
  2781. size_t refineIters = 10);
  2782. /** @example samples/cpp/tutorial_code/features2D/Homography/decompose_homography.cpp
  2783. An example program with homography decomposition.
  2784. Check @ref tutorial_homography "the corresponding tutorial" for more details.
  2785. */
  2786. /** @brief Decompose a homography matrix to rotation(s), translation(s) and plane normal(s).
  2787. @param H The input homography matrix between two images.
  2788. @param K The input camera intrinsic matrix.
  2789. @param rotations Array of rotation matrices.
  2790. @param translations Array of translation matrices.
  2791. @param normals Array of plane normal matrices.
  2792. This function extracts relative camera motion between two views of a planar object and returns up to
  2793. four mathematical solution tuples of rotation, translation, and plane normal. The decomposition of
  2794. the homography matrix H is described in detail in @cite Malis.
  2795. If the homography H, induced by the plane, gives the constraint
  2796. \f[s_i \vecthree{x'_i}{y'_i}{1} \sim H \vecthree{x_i}{y_i}{1}\f] on the source image points
  2797. \f$p_i\f$ and the destination image points \f$p'_i\f$, then the tuple of rotations[k] and
  2798. translations[k] is a change of basis from the source camera's coordinate system to the destination
  2799. camera's coordinate system. However, by decomposing H, one can only get the translation normalized
  2800. by the (typically unknown) depth of the scene, i.e. its direction but with normalized length.
  2801. If point correspondences are available, at least two solutions may further be invalidated, by
  2802. applying positive depth constraint, i.e. all points must be in front of the camera.
  2803. */
  2804. CV_EXPORTS_W int decomposeHomographyMat(InputArray H,
  2805. InputArray K,
  2806. OutputArrayOfArrays rotations,
  2807. OutputArrayOfArrays translations,
  2808. OutputArrayOfArrays normals);
  2809. /** @brief Filters homography decompositions based on additional information.
  2810. @param rotations Vector of rotation matrices.
  2811. @param normals Vector of plane normal matrices.
  2812. @param beforePoints Vector of (rectified) visible reference points before the homography is applied
  2813. @param afterPoints Vector of (rectified) visible reference points after the homography is applied
  2814. @param possibleSolutions Vector of int indices representing the viable solution set after filtering
  2815. @param pointsMask optional Mat/Vector of 8u type representing the mask for the inliers as given by the #findHomography function
  2816. This function is intended to filter the output of the #decomposeHomographyMat based on additional
  2817. information as described in @cite Malis . The summary of the method: the #decomposeHomographyMat function
  2818. returns 2 unique solutions and their "opposites" for a total of 4 solutions. If we have access to the
  2819. sets of points visible in the camera frame before and after the homography transformation is applied,
  2820. we can determine which are the true potential solutions and which are the opposites by verifying which
  2821. homographies are consistent with all visible reference points being in front of the camera. The inputs
  2822. are left unchanged; the filtered solution set is returned as indices into the existing one.
  2823. */
  2824. CV_EXPORTS_W void filterHomographyDecompByVisibleRefpoints(InputArrayOfArrays rotations,
  2825. InputArrayOfArrays normals,
  2826. InputArray beforePoints,
  2827. InputArray afterPoints,
  2828. OutputArray possibleSolutions,
  2829. InputArray pointsMask = noArray());
  2830. /** @brief The base class for stereo correspondence algorithms.
  2831. */
  2832. class CV_EXPORTS_W StereoMatcher : public Algorithm
  2833. {
  2834. public:
  2835. enum { DISP_SHIFT = 4,
  2836. DISP_SCALE = (1 << DISP_SHIFT)
  2837. };
  2838. /** @brief Computes disparity map for the specified stereo pair
  2839. @param left Left 8-bit single-channel image.
  2840. @param right Right image of the same size and the same type as the left one.
  2841. @param disparity Output disparity map. It has the same size as the input images. Some algorithms,
  2842. like StereoBM or StereoSGBM compute 16-bit fixed-point disparity map (where each disparity value
  2843. has 4 fractional bits), whereas other algorithms output 32-bit floating-point disparity map.
  2844. */
  2845. CV_WRAP virtual void compute( InputArray left, InputArray right,
  2846. OutputArray disparity ) = 0;
  2847. CV_WRAP virtual int getMinDisparity() const = 0;
  2848. CV_WRAP virtual void setMinDisparity(int minDisparity) = 0;
  2849. CV_WRAP virtual int getNumDisparities() const = 0;
  2850. CV_WRAP virtual void setNumDisparities(int numDisparities) = 0;
  2851. CV_WRAP virtual int getBlockSize() const = 0;
  2852. CV_WRAP virtual void setBlockSize(int blockSize) = 0;
  2853. CV_WRAP virtual int getSpeckleWindowSize() const = 0;
  2854. CV_WRAP virtual void setSpeckleWindowSize(int speckleWindowSize) = 0;
  2855. CV_WRAP virtual int getSpeckleRange() const = 0;
  2856. CV_WRAP virtual void setSpeckleRange(int speckleRange) = 0;
  2857. CV_WRAP virtual int getDisp12MaxDiff() const = 0;
  2858. CV_WRAP virtual void setDisp12MaxDiff(int disp12MaxDiff) = 0;
  2859. };
  2860. /** @brief Class for computing stereo correspondence using the block matching algorithm, introduced and
  2861. contributed to OpenCV by K. Konolige.
  2862. */
  2863. class CV_EXPORTS_W StereoBM : public StereoMatcher
  2864. {
  2865. public:
  2866. enum { PREFILTER_NORMALIZED_RESPONSE = 0,
  2867. PREFILTER_XSOBEL = 1
  2868. };
  2869. CV_WRAP virtual int getPreFilterType() const = 0;
  2870. CV_WRAP virtual void setPreFilterType(int preFilterType) = 0;
  2871. CV_WRAP virtual int getPreFilterSize() const = 0;
  2872. CV_WRAP virtual void setPreFilterSize(int preFilterSize) = 0;
  2873. CV_WRAP virtual int getPreFilterCap() const = 0;
  2874. CV_WRAP virtual void setPreFilterCap(int preFilterCap) = 0;
  2875. CV_WRAP virtual int getTextureThreshold() const = 0;
  2876. CV_WRAP virtual void setTextureThreshold(int textureThreshold) = 0;
  2877. CV_WRAP virtual int getUniquenessRatio() const = 0;
  2878. CV_WRAP virtual void setUniquenessRatio(int uniquenessRatio) = 0;
  2879. CV_WRAP virtual int getSmallerBlockSize() const = 0;
  2880. CV_WRAP virtual void setSmallerBlockSize(int blockSize) = 0;
  2881. CV_WRAP virtual Rect getROI1() const = 0;
  2882. CV_WRAP virtual void setROI1(Rect roi1) = 0;
  2883. CV_WRAP virtual Rect getROI2() const = 0;
  2884. CV_WRAP virtual void setROI2(Rect roi2) = 0;
  2885. /** @brief Creates StereoBM object
  2886. @param numDisparities the disparity search range. For each pixel algorithm will find the best
  2887. disparity from 0 (default minimum disparity) to numDisparities. The search range can then be
  2888. shifted by changing the minimum disparity.
  2889. @param blockSize the linear size of the blocks compared by the algorithm. The size should be odd
  2890. (as the block is centered at the current pixel). Larger block size implies smoother, though less
  2891. accurate disparity map. Smaller block size gives more detailed disparity map, but there is higher
  2892. chance for algorithm to find a wrong correspondence.
  2893. The function create StereoBM object. You can then call StereoBM::compute() to compute disparity for
  2894. a specific stereo pair.
  2895. */
  2896. CV_WRAP static Ptr<StereoBM> create(int numDisparities = 0, int blockSize = 21);
  2897. };
  2898. /** @brief The class implements the modified H. Hirschmuller algorithm @cite HH08 that differs from the original
  2899. one as follows:
  2900. - By default, the algorithm is single-pass, which means that you consider only 5 directions
  2901. instead of 8. Set mode=StereoSGBM::MODE_HH in createStereoSGBM to run the full variant of the
  2902. algorithm but beware that it may consume a lot of memory.
  2903. - The algorithm matches blocks, not individual pixels. Though, setting blockSize=1 reduces the
  2904. blocks to single pixels.
  2905. - Mutual information cost function is not implemented. Instead, a simpler Birchfield-Tomasi
  2906. sub-pixel metric from @cite BT98 is used. Though, the color images are supported as well.
  2907. - Some pre- and post- processing steps from K. Konolige algorithm StereoBM are included, for
  2908. example: pre-filtering (StereoBM::PREFILTER_XSOBEL type) and post-filtering (uniqueness
  2909. check, quadratic interpolation and speckle filtering).
  2910. @note
  2911. - (Python) An example illustrating the use of the StereoSGBM matching algorithm can be found
  2912. at opencv_source_code/samples/python/stereo_match.py
  2913. */
  2914. class CV_EXPORTS_W StereoSGBM : public StereoMatcher
  2915. {
  2916. public:
  2917. enum
  2918. {
  2919. MODE_SGBM = 0,
  2920. MODE_HH = 1,
  2921. MODE_SGBM_3WAY = 2,
  2922. MODE_HH4 = 3
  2923. };
  2924. CV_WRAP virtual int getPreFilterCap() const = 0;
  2925. CV_WRAP virtual void setPreFilterCap(int preFilterCap) = 0;
  2926. CV_WRAP virtual int getUniquenessRatio() const = 0;
  2927. CV_WRAP virtual void setUniquenessRatio(int uniquenessRatio) = 0;
  2928. CV_WRAP virtual int getP1() const = 0;
  2929. CV_WRAP virtual void setP1(int P1) = 0;
  2930. CV_WRAP virtual int getP2() const = 0;
  2931. CV_WRAP virtual void setP2(int P2) = 0;
  2932. CV_WRAP virtual int getMode() const = 0;
  2933. CV_WRAP virtual void setMode(int mode) = 0;
  2934. /** @brief Creates StereoSGBM object
  2935. @param minDisparity Minimum possible disparity value. Normally, it is zero but sometimes
  2936. rectification algorithms can shift images, so this parameter needs to be adjusted accordingly.
  2937. @param numDisparities Maximum disparity minus minimum disparity. The value is always greater than
  2938. zero. In the current implementation, this parameter must be divisible by 16.
  2939. @param blockSize Matched block size. It must be an odd number \>=1 . Normally, it should be
  2940. somewhere in the 3..11 range.
  2941. @param P1 The first parameter controlling the disparity smoothness. See below.
  2942. @param P2 The second parameter controlling the disparity smoothness. The larger the values are,
  2943. the smoother the disparity is. P1 is the penalty on the disparity change by plus or minus 1
  2944. between neighbor pixels. P2 is the penalty on the disparity change by more than 1 between neighbor
  2945. pixels. The algorithm requires P2 \> P1 . See stereo_match.cpp sample where some reasonably good
  2946. P1 and P2 values are shown (like 8\*number_of_image_channels\*blockSize\*blockSize and
  2947. 32\*number_of_image_channels\*blockSize\*blockSize , respectively).
  2948. @param disp12MaxDiff Maximum allowed difference (in integer pixel units) in the left-right
  2949. disparity check. Set it to a non-positive value to disable the check.
  2950. @param preFilterCap Truncation value for the prefiltered image pixels. The algorithm first
  2951. computes x-derivative at each pixel and clips its value by [-preFilterCap, preFilterCap] interval.
  2952. The result values are passed to the Birchfield-Tomasi pixel cost function.
  2953. @param uniquenessRatio Margin in percentage by which the best (minimum) computed cost function
  2954. value should "win" the second best value to consider the found match correct. Normally, a value
  2955. within the 5-15 range is good enough.
  2956. @param speckleWindowSize Maximum size of smooth disparity regions to consider their noise speckles
  2957. and invalidate. Set it to 0 to disable speckle filtering. Otherwise, set it somewhere in the
  2958. 50-200 range.
  2959. @param speckleRange Maximum disparity variation within each connected component. If you do speckle
  2960. filtering, set the parameter to a positive value, it will be implicitly multiplied by 16.
  2961. Normally, 1 or 2 is good enough.
  2962. @param mode Set it to StereoSGBM::MODE_HH to run the full-scale two-pass dynamic programming
  2963. algorithm. It will consume O(W\*H\*numDisparities) bytes, which is large for 640x480 stereo and
  2964. huge for HD-size pictures. By default, it is set to false .
  2965. The first constructor initializes StereoSGBM with all the default parameters. So, you only have to
  2966. set StereoSGBM::numDisparities at minimum. The second constructor enables you to set each parameter
  2967. to a custom value.
  2968. */
  2969. CV_WRAP static Ptr<StereoSGBM> create(int minDisparity = 0, int numDisparities = 16, int blockSize = 3,
  2970. int P1 = 0, int P2 = 0, int disp12MaxDiff = 0,
  2971. int preFilterCap = 0, int uniquenessRatio = 0,
  2972. int speckleWindowSize = 0, int speckleRange = 0,
  2973. int mode = StereoSGBM::MODE_SGBM);
  2974. };
  2975. //! cv::undistort mode
  2976. enum UndistortTypes
  2977. {
  2978. PROJ_SPHERICAL_ORTHO = 0,
  2979. PROJ_SPHERICAL_EQRECT = 1
  2980. };
  2981. /** @brief Transforms an image to compensate for lens distortion.
  2982. The function transforms an image to compensate radial and tangential lens distortion.
  2983. The function is simply a combination of #initUndistortRectifyMap (with unity R ) and #remap
  2984. (with bilinear interpolation). See the former function for details of the transformation being
  2985. performed.
  2986. Those pixels in the destination image, for which there is no correspondent pixels in the source
  2987. image, are filled with zeros (black color).
  2988. A particular subset of the source image that will be visible in the corrected image can be regulated
  2989. by newCameraMatrix. You can use #getOptimalNewCameraMatrix to compute the appropriate
  2990. newCameraMatrix depending on your requirements.
  2991. The camera matrix and the distortion parameters can be determined using #calibrateCamera. If
  2992. the resolution of images is different from the resolution used at the calibration stage, \f$f_x,
  2993. f_y, c_x\f$ and \f$c_y\f$ need to be scaled accordingly, while the distortion coefficients remain
  2994. the same.
  2995. @param src Input (distorted) image.
  2996. @param dst Output (corrected) image that has the same size and type as src .
  2997. @param cameraMatrix Input camera matrix \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
  2998. @param distCoeffs Input vector of distortion coefficients
  2999. \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
  3000. of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
  3001. @param newCameraMatrix Camera matrix of the distorted image. By default, it is the same as
  3002. cameraMatrix but you may additionally scale and shift the result by using a different matrix.
  3003. */
  3004. CV_EXPORTS_W void undistort( InputArray src, OutputArray dst,
  3005. InputArray cameraMatrix,
  3006. InputArray distCoeffs,
  3007. InputArray newCameraMatrix = noArray() );
  3008. /** @brief Computes the undistortion and rectification transformation map.
  3009. The function computes the joint undistortion and rectification transformation and represents the
  3010. result in the form of maps for #remap. The undistorted image looks like original, as if it is
  3011. captured with a camera using the camera matrix =newCameraMatrix and zero distortion. In case of a
  3012. monocular camera, newCameraMatrix is usually equal to cameraMatrix, or it can be computed by
  3013. #getOptimalNewCameraMatrix for a better control over scaling. In case of a stereo camera,
  3014. newCameraMatrix is normally set to P1 or P2 computed by #stereoRectify .
  3015. Also, this new camera is oriented differently in the coordinate space, according to R. That, for
  3016. example, helps to align two heads of a stereo camera so that the epipolar lines on both images
  3017. become horizontal and have the same y- coordinate (in case of a horizontally aligned stereo camera).
  3018. The function actually builds the maps for the inverse mapping algorithm that is used by #remap. That
  3019. is, for each pixel \f$(u, v)\f$ in the destination (corrected and rectified) image, the function
  3020. computes the corresponding coordinates in the source image (that is, in the original image from
  3021. camera). The following process is applied:
  3022. \f[
  3023. \begin{array}{l}
  3024. x \leftarrow (u - {c'}_x)/{f'}_x \\
  3025. y \leftarrow (v - {c'}_y)/{f'}_y \\
  3026. {[X\,Y\,W]} ^T \leftarrow R^{-1}*[x \, y \, 1]^T \\
  3027. x' \leftarrow X/W \\
  3028. y' \leftarrow Y/W \\
  3029. r^2 \leftarrow x'^2 + y'^2 \\
  3030. x'' \leftarrow x' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6}
  3031. + 2p_1 x' y' + p_2(r^2 + 2 x'^2) + s_1 r^2 + s_2 r^4\\
  3032. y'' \leftarrow y' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6}
  3033. + p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' + s_3 r^2 + s_4 r^4 \\
  3034. s\vecthree{x'''}{y'''}{1} =
  3035. \vecthreethree{R_{33}(\tau_x, \tau_y)}{0}{-R_{13}((\tau_x, \tau_y)}
  3036. {0}{R_{33}(\tau_x, \tau_y)}{-R_{23}(\tau_x, \tau_y)}
  3037. {0}{0}{1} R(\tau_x, \tau_y) \vecthree{x''}{y''}{1}\\
  3038. map_x(u,v) \leftarrow x''' f_x + c_x \\
  3039. map_y(u,v) \leftarrow y''' f_y + c_y
  3040. \end{array}
  3041. \f]
  3042. where \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
  3043. are the distortion coefficients.
  3044. In case of a stereo camera, this function is called twice: once for each camera head, after
  3045. #stereoRectify, which in its turn is called after #stereoCalibrate. But if the stereo camera
  3046. was not calibrated, it is still possible to compute the rectification transformations directly from
  3047. the fundamental matrix using #stereoRectifyUncalibrated. For each camera, the function computes
  3048. homography H as the rectification transformation in a pixel domain, not a rotation matrix R in 3D
  3049. space. R can be computed from H as
  3050. \f[\texttt{R} = \texttt{cameraMatrix} ^{-1} \cdot \texttt{H} \cdot \texttt{cameraMatrix}\f]
  3051. where cameraMatrix can be chosen arbitrarily.
  3052. @param cameraMatrix Input camera matrix \f$A=\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
  3053. @param distCoeffs Input vector of distortion coefficients
  3054. \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
  3055. of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
  3056. @param R Optional rectification transformation in the object space (3x3 matrix). R1 or R2 ,
  3057. computed by #stereoRectify can be passed here. If the matrix is empty, the identity transformation
  3058. is assumed. In cvInitUndistortMap R assumed to be an identity matrix.
  3059. @param newCameraMatrix New camera matrix \f$A'=\vecthreethree{f_x'}{0}{c_x'}{0}{f_y'}{c_y'}{0}{0}{1}\f$.
  3060. @param size Undistorted image size.
  3061. @param m1type Type of the first output map that can be CV_32FC1, CV_32FC2 or CV_16SC2, see #convertMaps
  3062. @param map1 The first output map.
  3063. @param map2 The second output map.
  3064. */
  3065. CV_EXPORTS_W
  3066. void initUndistortRectifyMap(InputArray cameraMatrix, InputArray distCoeffs,
  3067. InputArray R, InputArray newCameraMatrix,
  3068. Size size, int m1type, OutputArray map1, OutputArray map2);
  3069. /** @brief Computes the projection and inverse-rectification transformation map. In essense, this is the inverse of
  3070. #initUndistortRectifyMap to accomodate stereo-rectification of projectors ('inverse-cameras') in projector-camera pairs.
  3071. The function computes the joint projection and inverse rectification transformation and represents the
  3072. result in the form of maps for #remap. The projected image looks like a distorted version of the original which,
  3073. once projected by a projector, should visually match the original. In case of a monocular camera, newCameraMatrix
  3074. is usually equal to cameraMatrix, or it can be computed by
  3075. #getOptimalNewCameraMatrix for a better control over scaling. In case of a projector-camera pair,
  3076. newCameraMatrix is normally set to P1 or P2 computed by #stereoRectify .
  3077. The projector is oriented differently in the coordinate space, according to R. In case of projector-camera pairs,
  3078. this helps align the projector (in the same manner as #initUndistortRectifyMap for the camera) to create a stereo-rectified pair. This
  3079. allows epipolar lines on both images to become horizontal and have the same y-coordinate (in case of a horizontally aligned projector-camera pair).
  3080. The function builds the maps for the inverse mapping algorithm that is used by #remap. That
  3081. is, for each pixel \f$(u, v)\f$ in the destination (projected and inverse-rectified) image, the function
  3082. computes the corresponding coordinates in the source image (that is, in the original digital image). The following process is applied:
  3083. \f[
  3084. \begin{array}{l}
  3085. \text{newCameraMatrix}\\
  3086. x \leftarrow (u - {c'}_x)/{f'}_x \\
  3087. y \leftarrow (v - {c'}_y)/{f'}_y \\
  3088. \\\text{Undistortion}
  3089. \\\scriptsize{\textit{though equation shown is for radial undistortion, function implements cv::undistortPoints()}}\\
  3090. r^2 \leftarrow x^2 + y^2 \\
  3091. \theta \leftarrow \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6}\\
  3092. x' \leftarrow \frac{x}{\theta} \\
  3093. y' \leftarrow \frac{y}{\theta} \\
  3094. \\\text{Rectification}\\
  3095. {[X\,Y\,W]} ^T \leftarrow R*[x' \, y' \, 1]^T \\
  3096. x'' \leftarrow X/W \\
  3097. y'' \leftarrow Y/W \\
  3098. \\\text{cameraMatrix}\\
  3099. map_x(u,v) \leftarrow x'' f_x + c_x \\
  3100. map_y(u,v) \leftarrow y'' f_y + c_y
  3101. \end{array}
  3102. \f]
  3103. where \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
  3104. are the distortion coefficients vector distCoeffs.
  3105. In case of a stereo-rectified projector-camera pair, this function is called for the projector while #initUndistortRectifyMap is called for the camera head.
  3106. This is done after #stereoRectify, which in turn is called after #stereoCalibrate. If the projector-camera pair
  3107. is not calibrated, it is still possible to compute the rectification transformations directly from
  3108. the fundamental matrix using #stereoRectifyUncalibrated. For the projector and camera, the function computes
  3109. homography H as the rectification transformation in a pixel domain, not a rotation matrix R in 3D
  3110. space. R can be computed from H as
  3111. \f[\texttt{R} = \texttt{cameraMatrix} ^{-1} \cdot \texttt{H} \cdot \texttt{cameraMatrix}\f]
  3112. where cameraMatrix can be chosen arbitrarily.
  3113. @param cameraMatrix Input camera matrix \f$A=\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
  3114. @param distCoeffs Input vector of distortion coefficients
  3115. \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
  3116. of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
  3117. @param R Optional rectification transformation in the object space (3x3 matrix). R1 or R2,
  3118. computed by #stereoRectify can be passed here. If the matrix is empty, the identity transformation
  3119. is assumed.
  3120. @param newCameraMatrix New camera matrix \f$A'=\vecthreethree{f_x'}{0}{c_x'}{0}{f_y'}{c_y'}{0}{0}{1}\f$.
  3121. @param size Distorted image size.
  3122. @param m1type Type of the first output map. Can be CV_32FC1, CV_32FC2 or CV_16SC2, see #convertMaps
  3123. @param map1 The first output map for #remap.
  3124. @param map2 The second output map for #remap.
  3125. */
  3126. CV_EXPORTS_W
  3127. void initInverseRectificationMap( InputArray cameraMatrix, InputArray distCoeffs,
  3128. InputArray R, InputArray newCameraMatrix,
  3129. const Size& size, int m1type, OutputArray map1, OutputArray map2 );
  3130. //! initializes maps for #remap for wide-angle
  3131. CV_EXPORTS
  3132. float initWideAngleProjMap(InputArray cameraMatrix, InputArray distCoeffs,
  3133. Size imageSize, int destImageWidth,
  3134. int m1type, OutputArray map1, OutputArray map2,
  3135. enum UndistortTypes projType = PROJ_SPHERICAL_EQRECT, double alpha = 0);
  3136. static inline
  3137. float initWideAngleProjMap(InputArray cameraMatrix, InputArray distCoeffs,
  3138. Size imageSize, int destImageWidth,
  3139. int m1type, OutputArray map1, OutputArray map2,
  3140. int projType, double alpha = 0)
  3141. {
  3142. return initWideAngleProjMap(cameraMatrix, distCoeffs, imageSize, destImageWidth,
  3143. m1type, map1, map2, (UndistortTypes)projType, alpha);
  3144. }
  3145. /** @brief Returns the default new camera matrix.
  3146. The function returns the camera matrix that is either an exact copy of the input cameraMatrix (when
  3147. centerPrinicipalPoint=false ), or the modified one (when centerPrincipalPoint=true).
  3148. In the latter case, the new camera matrix will be:
  3149. \f[\begin{bmatrix} f_x && 0 && ( \texttt{imgSize.width} -1)*0.5 \\ 0 && f_y && ( \texttt{imgSize.height} -1)*0.5 \\ 0 && 0 && 1 \end{bmatrix} ,\f]
  3150. where \f$f_x\f$ and \f$f_y\f$ are \f$(0,0)\f$ and \f$(1,1)\f$ elements of cameraMatrix, respectively.
  3151. By default, the undistortion functions in OpenCV (see #initUndistortRectifyMap, #undistort) do not
  3152. move the principal point. However, when you work with stereo, it is important to move the principal
  3153. points in both views to the same y-coordinate (which is required by most of stereo correspondence
  3154. algorithms), and may be to the same x-coordinate too. So, you can form the new camera matrix for
  3155. each view where the principal points are located at the center.
  3156. @param cameraMatrix Input camera matrix.
  3157. @param imgsize Camera view image size in pixels.
  3158. @param centerPrincipalPoint Location of the principal point in the new camera matrix. The
  3159. parameter indicates whether this location should be at the image center or not.
  3160. */
  3161. CV_EXPORTS_W
  3162. Mat getDefaultNewCameraMatrix(InputArray cameraMatrix, Size imgsize = Size(),
  3163. bool centerPrincipalPoint = false);
  3164. /** @brief Computes the ideal point coordinates from the observed point coordinates.
  3165. The function is similar to #undistort and #initUndistortRectifyMap but it operates on a
  3166. sparse set of points instead of a raster image. Also the function performs a reverse transformation
  3167. to #projectPoints. In case of a 3D object, it does not reconstruct its 3D coordinates, but for a
  3168. planar object, it does, up to a translation vector, if the proper R is specified.
  3169. For each observed point coordinate \f$(u, v)\f$ the function computes:
  3170. \f[
  3171. \begin{array}{l}
  3172. x^{"} \leftarrow (u - c_x)/f_x \\
  3173. y^{"} \leftarrow (v - c_y)/f_y \\
  3174. (x',y') = undistort(x^{"},y^{"}, \texttt{distCoeffs}) \\
  3175. {[X\,Y\,W]} ^T \leftarrow R*[x' \, y' \, 1]^T \\
  3176. x \leftarrow X/W \\
  3177. y \leftarrow Y/W \\
  3178. \text{only performed if P is specified:} \\
  3179. u' \leftarrow x {f'}_x + {c'}_x \\
  3180. v' \leftarrow y {f'}_y + {c'}_y
  3181. \end{array}
  3182. \f]
  3183. where *undistort* is an approximate iterative algorithm that estimates the normalized original
  3184. point coordinates out of the normalized distorted point coordinates ("normalized" means that the
  3185. coordinates do not depend on the camera matrix).
  3186. The function can be used for both a stereo camera head or a monocular camera (when R is empty).
  3187. @param src Observed point coordinates, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel (CV_32FC2 or CV_64FC2) (or
  3188. vector\<Point2f\> ).
  3189. @param dst Output ideal point coordinates (1xN/Nx1 2-channel or vector\<Point2f\> ) after undistortion and reverse perspective
  3190. transformation. If matrix P is identity or omitted, dst will contain normalized point coordinates.
  3191. @param cameraMatrix Camera matrix \f$\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
  3192. @param distCoeffs Input vector of distortion coefficients
  3193. \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$
  3194. of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
  3195. @param R Rectification transformation in the object space (3x3 matrix). R1 or R2 computed by
  3196. #stereoRectify can be passed here. If the matrix is empty, the identity transformation is used.
  3197. @param P New camera matrix (3x3) or new projection matrix (3x4) \f$\begin{bmatrix} {f'}_x & 0 & {c'}_x & t_x \\ 0 & {f'}_y & {c'}_y & t_y \\ 0 & 0 & 1 & t_z \end{bmatrix}\f$. P1 or P2 computed by
  3198. #stereoRectify can be passed here. If the matrix is empty, the identity new camera matrix is used.
  3199. */
  3200. CV_EXPORTS_W
  3201. void undistortPoints(InputArray src, OutputArray dst,
  3202. InputArray cameraMatrix, InputArray distCoeffs,
  3203. InputArray R = noArray(), InputArray P = noArray());
  3204. /** @overload
  3205. @note Default version of #undistortPoints does 5 iterations to compute undistorted points.
  3206. */
  3207. CV_EXPORTS_AS(undistortPointsIter)
  3208. void undistortPoints(InputArray src, OutputArray dst,
  3209. InputArray cameraMatrix, InputArray distCoeffs,
  3210. InputArray R, InputArray P, TermCriteria criteria);
  3211. /**
  3212. * @brief Compute undistorted image points position
  3213. *
  3214. * @param src Observed points position, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel (CV_32FC2 or
  3215. CV_64FC2) (or vector\<Point2f\> ).
  3216. * @param dst Output undistorted points position (1xN/Nx1 2-channel or vector\<Point2f\> ).
  3217. * @param cameraMatrix Camera matrix \f$\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
  3218. * @param distCoeffs Distortion coefficients
  3219. */
  3220. CV_EXPORTS_W
  3221. void undistortImagePoints(InputArray src, OutputArray dst, InputArray cameraMatrix,
  3222. InputArray distCoeffs,
  3223. TermCriteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5,
  3224. 0.01));
  3225. //! @} calib3d
  3226. /** @brief The methods in this namespace use a so-called fisheye camera model.
  3227. @ingroup calib3d_fisheye
  3228. */
  3229. namespace fisheye
  3230. {
  3231. //! @addtogroup calib3d_fisheye
  3232. //! @{
  3233. enum{
  3234. CALIB_USE_INTRINSIC_GUESS = 1 << 0,
  3235. CALIB_RECOMPUTE_EXTRINSIC = 1 << 1,
  3236. CALIB_CHECK_COND = 1 << 2,
  3237. CALIB_FIX_SKEW = 1 << 3,
  3238. CALIB_FIX_K1 = 1 << 4,
  3239. CALIB_FIX_K2 = 1 << 5,
  3240. CALIB_FIX_K3 = 1 << 6,
  3241. CALIB_FIX_K4 = 1 << 7,
  3242. CALIB_FIX_INTRINSIC = 1 << 8,
  3243. CALIB_FIX_PRINCIPAL_POINT = 1 << 9,
  3244. CALIB_ZERO_DISPARITY = 1 << 10,
  3245. CALIB_FIX_FOCAL_LENGTH = 1 << 11
  3246. };
  3247. /** @brief Projects points using fisheye model
  3248. @param objectPoints Array of object points, 1xN/Nx1 3-channel (or vector\<Point3f\> ), where N is
  3249. the number of points in the view.
  3250. @param imagePoints Output array of image points, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel, or
  3251. vector\<Point2f\>.
  3252. @param affine
  3253. @param K Camera intrinsic matrix \f$cameramatrix{K}\f$.
  3254. @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
  3255. @param alpha The skew coefficient.
  3256. @param jacobian Optional output 2Nx15 jacobian matrix of derivatives of image points with respect
  3257. to components of the focal lengths, coordinates of the principal point, distortion coefficients,
  3258. rotation vector, translation vector, and the skew. In the old interface different components of
  3259. the jacobian are returned via different output parameters.
  3260. The function computes projections of 3D points to the image plane given intrinsic and extrinsic
  3261. camera parameters. Optionally, the function computes Jacobians - matrices of partial derivatives of
  3262. image points coordinates (as functions of all the input parameters) with respect to the particular
  3263. parameters, intrinsic and/or extrinsic.
  3264. */
  3265. CV_EXPORTS void projectPoints(InputArray objectPoints, OutputArray imagePoints, const Affine3d& affine,
  3266. InputArray K, InputArray D, double alpha = 0, OutputArray jacobian = noArray());
  3267. /** @overload */
  3268. CV_EXPORTS_W void projectPoints(InputArray objectPoints, OutputArray imagePoints, InputArray rvec, InputArray tvec,
  3269. InputArray K, InputArray D, double alpha = 0, OutputArray jacobian = noArray());
  3270. /** @brief Distorts 2D points using fisheye model.
  3271. @param undistorted Array of object points, 1xN/Nx1 2-channel (or vector\<Point2f\> ), where N is
  3272. the number of points in the view.
  3273. @param K Camera intrinsic matrix \f$cameramatrix{K}\f$.
  3274. @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
  3275. @param alpha The skew coefficient.
  3276. @param distorted Output array of image points, 1xN/Nx1 2-channel, or vector\<Point2f\> .
  3277. Note that the function assumes the camera intrinsic matrix of the undistorted points to be identity.
  3278. This means if you want to distort image points you have to multiply them with \f$K^{-1}\f$.
  3279. */
  3280. CV_EXPORTS_W void distortPoints(InputArray undistorted, OutputArray distorted, InputArray K, InputArray D, double alpha = 0);
  3281. /** @brief Undistorts 2D points using fisheye model
  3282. @param distorted Array of object points, 1xN/Nx1 2-channel (or vector\<Point2f\> ), where N is the
  3283. number of points in the view.
  3284. @param K Camera intrinsic matrix \f$cameramatrix{K}\f$.
  3285. @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
  3286. @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3
  3287. 1-channel or 1x1 3-channel
  3288. @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4)
  3289. @param criteria Termination criteria
  3290. @param undistorted Output array of image points, 1xN/Nx1 2-channel, or vector\<Point2f\> .
  3291. */
  3292. CV_EXPORTS_W void undistortPoints(InputArray distorted, OutputArray undistorted,
  3293. InputArray K, InputArray D, InputArray R = noArray(), InputArray P = noArray(),
  3294. TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 10, 1e-8));
  3295. /** @brief Computes undistortion and rectification maps for image transform by #remap. If D is empty zero
  3296. distortion is used, if R or P is empty identity matrixes are used.
  3297. @param K Camera intrinsic matrix \f$cameramatrix{K}\f$.
  3298. @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
  3299. @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3
  3300. 1-channel or 1x1 3-channel
  3301. @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4)
  3302. @param size Undistorted image size.
  3303. @param m1type Type of the first output map that can be CV_32FC1 or CV_16SC2 . See #convertMaps
  3304. for details.
  3305. @param map1 The first output map.
  3306. @param map2 The second output map.
  3307. */
  3308. CV_EXPORTS_W void initUndistortRectifyMap(InputArray K, InputArray D, InputArray R, InputArray P,
  3309. const cv::Size& size, int m1type, OutputArray map1, OutputArray map2);
  3310. /** @brief Transforms an image to compensate for fisheye lens distortion.
  3311. @param distorted image with fisheye lens distortion.
  3312. @param undistorted Output image with compensated fisheye lens distortion.
  3313. @param K Camera intrinsic matrix \f$cameramatrix{K}\f$.
  3314. @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
  3315. @param Knew Camera intrinsic matrix of the distorted image. By default, it is the identity matrix but you
  3316. may additionally scale and shift the result by using a different matrix.
  3317. @param new_size the new size
  3318. The function transforms an image to compensate radial and tangential lens distortion.
  3319. The function is simply a combination of #fisheye::initUndistortRectifyMap (with unity R ) and #remap
  3320. (with bilinear interpolation). See the former function for details of the transformation being
  3321. performed.
  3322. See below the results of undistortImage.
  3323. - a\) result of undistort of perspective camera model (all possible coefficients (k_1, k_2, k_3,
  3324. k_4, k_5, k_6) of distortion were optimized under calibration)
  3325. - b\) result of #fisheye::undistortImage of fisheye camera model (all possible coefficients (k_1, k_2,
  3326. k_3, k_4) of fisheye distortion were optimized under calibration)
  3327. - c\) original image was captured with fisheye lens
  3328. Pictures a) and b) almost the same. But if we consider points of image located far from the center
  3329. of image, we can notice that on image a) these points are distorted.
  3330. ![image](pics/fisheye_undistorted.jpg)
  3331. */
  3332. CV_EXPORTS_W void undistortImage(InputArray distorted, OutputArray undistorted,
  3333. InputArray K, InputArray D, InputArray Knew = cv::noArray(), const Size& new_size = Size());
  3334. /** @brief Estimates new camera intrinsic matrix for undistortion or rectification.
  3335. @param K Camera intrinsic matrix \f$cameramatrix{K}\f$.
  3336. @param image_size Size of the image
  3337. @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
  3338. @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3
  3339. 1-channel or 1x1 3-channel
  3340. @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4)
  3341. @param balance Sets the new focal length in range between the min focal length and the max focal
  3342. length. Balance is in range of [0, 1].
  3343. @param new_size the new size
  3344. @param fov_scale Divisor for new focal length.
  3345. */
  3346. CV_EXPORTS_W void estimateNewCameraMatrixForUndistortRectify(InputArray K, InputArray D, const Size &image_size, InputArray R,
  3347. OutputArray P, double balance = 0.0, const Size& new_size = Size(), double fov_scale = 1.0);
  3348. /** @brief Performs camera calibration
  3349. @param objectPoints vector of vectors of calibration pattern points in the calibration pattern
  3350. coordinate space.
  3351. @param imagePoints vector of vectors of the projections of calibration pattern points.
  3352. imagePoints.size() and objectPoints.size() and imagePoints[i].size() must be equal to
  3353. objectPoints[i].size() for each i.
  3354. @param image_size Size of the image used only to initialize the camera intrinsic matrix.
  3355. @param K Output 3x3 floating-point camera intrinsic matrix
  3356. \f$\cameramatrix{A}\f$ . If
  3357. @ref fisheye::CALIB_USE_INTRINSIC_GUESS is specified, some or all of fx, fy, cx, cy must be
  3358. initialized before calling the function.
  3359. @param D Output vector of distortion coefficients \f$\distcoeffsfisheye\f$.
  3360. @param rvecs Output vector of rotation vectors (see Rodrigues ) estimated for each pattern view.
  3361. That is, each k-th rotation vector together with the corresponding k-th translation vector (see
  3362. the next output parameter description) brings the calibration pattern from the model coordinate
  3363. space (in which object points are specified) to the world coordinate space, that is, a real
  3364. position of the calibration pattern in the k-th pattern view (k=0.. *M* -1).
  3365. @param tvecs Output vector of translation vectors estimated for each pattern view.
  3366. @param flags Different flags that may be zero or a combination of the following values:
  3367. - @ref fisheye::CALIB_USE_INTRINSIC_GUESS cameraMatrix contains valid initial values of
  3368. fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image
  3369. center ( imageSize is used), and focal distances are computed in a least-squares fashion.
  3370. - @ref fisheye::CALIB_RECOMPUTE_EXTRINSIC Extrinsic will be recomputed after each iteration
  3371. of intrinsic optimization.
  3372. - @ref fisheye::CALIB_CHECK_COND The functions will check validity of condition number.
  3373. - @ref fisheye::CALIB_FIX_SKEW Skew coefficient (alpha) is set to zero and stay zero.
  3374. - @ref fisheye::CALIB_FIX_K1,..., @ref fisheye::CALIB_FIX_K4 Selected distortion coefficients
  3375. are set to zeros and stay zero.
  3376. - @ref fisheye::CALIB_FIX_PRINCIPAL_POINT The principal point is not changed during the global
  3377. optimization. It stays at the center or at a different location specified when @ref fisheye::CALIB_USE_INTRINSIC_GUESS is set too.
  3378. - @ref fisheye::CALIB_FIX_FOCAL_LENGTH The focal length is not changed during the global
  3379. optimization. It is the \f$max(width,height)/\pi\f$ or the provided \f$f_x\f$, \f$f_y\f$ when @ref fisheye::CALIB_USE_INTRINSIC_GUESS is set too.
  3380. @param criteria Termination criteria for the iterative optimization algorithm.
  3381. */
  3382. CV_EXPORTS_W double calibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, const Size& image_size,
  3383. InputOutputArray K, InputOutputArray D, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, int flags = 0,
  3384. TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON));
  3385. /** @brief Stereo rectification for fisheye camera model
  3386. @param K1 First camera intrinsic matrix.
  3387. @param D1 First camera distortion parameters.
  3388. @param K2 Second camera intrinsic matrix.
  3389. @param D2 Second camera distortion parameters.
  3390. @param imageSize Size of the image used for stereo calibration.
  3391. @param R Rotation matrix between the coordinate systems of the first and the second
  3392. cameras.
  3393. @param tvec Translation vector between coordinate systems of the cameras.
  3394. @param R1 Output 3x3 rectification transform (rotation matrix) for the first camera.
  3395. @param R2 Output 3x3 rectification transform (rotation matrix) for the second camera.
  3396. @param P1 Output 3x4 projection matrix in the new (rectified) coordinate systems for the first
  3397. camera.
  3398. @param P2 Output 3x4 projection matrix in the new (rectified) coordinate systems for the second
  3399. camera.
  3400. @param Q Output \f$4 \times 4\f$ disparity-to-depth mapping matrix (see reprojectImageTo3D ).
  3401. @param flags Operation flags that may be zero or @ref fisheye::CALIB_ZERO_DISPARITY . If the flag is set,
  3402. the function makes the principal points of each camera have the same pixel coordinates in the
  3403. rectified views. And if the flag is not set, the function may still shift the images in the
  3404. horizontal or vertical direction (depending on the orientation of epipolar lines) to maximize the
  3405. useful image area.
  3406. @param newImageSize New image resolution after rectification. The same size should be passed to
  3407. #initUndistortRectifyMap (see the stereo_calib.cpp sample in OpenCV samples directory). When (0,0)
  3408. is passed (default), it is set to the original imageSize . Setting it to larger value can help you
  3409. preserve details in the original image, especially when there is a big radial distortion.
  3410. @param balance Sets the new focal length in range between the min focal length and the max focal
  3411. length. Balance is in range of [0, 1].
  3412. @param fov_scale Divisor for new focal length.
  3413. */
  3414. CV_EXPORTS_W void stereoRectify(InputArray K1, InputArray D1, InputArray K2, InputArray D2, const Size &imageSize, InputArray R, InputArray tvec,
  3415. OutputArray R1, OutputArray R2, OutputArray P1, OutputArray P2, OutputArray Q, int flags, const Size &newImageSize = Size(),
  3416. double balance = 0.0, double fov_scale = 1.0);
  3417. /** @brief Performs stereo calibration
  3418. @param objectPoints Vector of vectors of the calibration pattern points.
  3419. @param imagePoints1 Vector of vectors of the projections of the calibration pattern points,
  3420. observed by the first camera.
  3421. @param imagePoints2 Vector of vectors of the projections of the calibration pattern points,
  3422. observed by the second camera.
  3423. @param K1 Input/output first camera intrinsic matrix:
  3424. \f$\vecthreethree{f_x^{(j)}}{0}{c_x^{(j)}}{0}{f_y^{(j)}}{c_y^{(j)}}{0}{0}{1}\f$ , \f$j = 0,\, 1\f$ . If
  3425. any of @ref fisheye::CALIB_USE_INTRINSIC_GUESS , @ref fisheye::CALIB_FIX_INTRINSIC are specified,
  3426. some or all of the matrix components must be initialized.
  3427. @param D1 Input/output vector of distortion coefficients \f$\distcoeffsfisheye\f$ of 4 elements.
  3428. @param K2 Input/output second camera intrinsic matrix. The parameter is similar to K1 .
  3429. @param D2 Input/output lens distortion coefficients for the second camera. The parameter is
  3430. similar to D1 .
  3431. @param imageSize Size of the image used only to initialize camera intrinsic matrix.
  3432. @param R Output rotation matrix between the 1st and the 2nd camera coordinate systems.
  3433. @param T Output translation vector between the coordinate systems of the cameras.
  3434. @param flags Different flags that may be zero or a combination of the following values:
  3435. - @ref fisheye::CALIB_FIX_INTRINSIC Fix K1, K2? and D1, D2? so that only R, T matrices
  3436. are estimated.
  3437. - @ref fisheye::CALIB_USE_INTRINSIC_GUESS K1, K2 contains valid initial values of
  3438. fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image
  3439. center (imageSize is used), and focal distances are computed in a least-squares fashion.
  3440. - @ref fisheye::CALIB_RECOMPUTE_EXTRINSIC Extrinsic will be recomputed after each iteration
  3441. of intrinsic optimization.
  3442. - @ref fisheye::CALIB_CHECK_COND The functions will check validity of condition number.
  3443. - @ref fisheye::CALIB_FIX_SKEW Skew coefficient (alpha) is set to zero and stay zero.
  3444. - @ref fisheye::CALIB_FIX_K1,..., @ref fisheye::CALIB_FIX_K4 Selected distortion coefficients are set to zeros and stay
  3445. zero.
  3446. @param criteria Termination criteria for the iterative optimization algorithm.
  3447. */
  3448. CV_EXPORTS_W double stereoCalibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2,
  3449. InputOutputArray K1, InputOutputArray D1, InputOutputArray K2, InputOutputArray D2, Size imageSize,
  3450. OutputArray R, OutputArray T, int flags = fisheye::CALIB_FIX_INTRINSIC,
  3451. TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON));
  3452. //! @} calib3d_fisheye
  3453. } // end namespace fisheye
  3454. } //end namespace cv
  3455. #if 0 //def __cplusplus
  3456. //////////////////////////////////////////////////////////////////////////////////////////
  3457. class CV_EXPORTS CvLevMarq
  3458. {
  3459. public:
  3460. CvLevMarq();
  3461. CvLevMarq( int nparams, int nerrs, CvTermCriteria criteria=
  3462. cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON),
  3463. bool completeSymmFlag=false );
  3464. ~CvLevMarq();
  3465. void init( int nparams, int nerrs, CvTermCriteria criteria=
  3466. cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON),
  3467. bool completeSymmFlag=false );
  3468. bool update( const CvMat*& param, CvMat*& J, CvMat*& err );
  3469. bool updateAlt( const CvMat*& param, CvMat*& JtJ, CvMat*& JtErr, double*& errNorm );
  3470. void clear();
  3471. void step();
  3472. enum { DONE=0, STARTED=1, CALC_J=2, CHECK_ERR=3 };
  3473. cv::Ptr<CvMat> mask;
  3474. cv::Ptr<CvMat> prevParam;
  3475. cv::Ptr<CvMat> param;
  3476. cv::Ptr<CvMat> J;
  3477. cv::Ptr<CvMat> err;
  3478. cv::Ptr<CvMat> JtJ;
  3479. cv::Ptr<CvMat> JtJN;
  3480. cv::Ptr<CvMat> JtErr;
  3481. cv::Ptr<CvMat> JtJV;
  3482. cv::Ptr<CvMat> JtJW;
  3483. double prevErrNorm, errNorm;
  3484. int lambdaLg10;
  3485. CvTermCriteria criteria;
  3486. int state;
  3487. int iters;
  3488. bool completeSymmFlag;
  3489. int solveMethod;
  3490. };
  3491. #endif
  3492. #endif