calib3d.hpp 195 KB

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