calib3d.hpp 212 KB

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