calib3d.hpp 164 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058
  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. Summary:
  354. Generic camera model @cite Kannala2006 with perspective projection and without distortion correction
  355. @defgroup calib3d_c C API
  356. @}
  357. */
  358. namespace cv
  359. {
  360. //! @addtogroup calib3d
  361. //! @{
  362. //! type of the robust estimation algorithm
  363. enum { LMEDS = 4, //!< least-median of squares algorithm
  364. RANSAC = 8, //!< RANSAC algorithm
  365. RHO = 16 //!< RHO algorithm
  366. };
  367. enum SolvePnPMethod {
  368. SOLVEPNP_ITERATIVE = 0, //!< Pose refinement using non-linear Levenberg-Marquardt minimization scheme @cite Madsen04 @cite Eade13 \n
  369. //!< Initial solution for non-planar "objectPoints" needs at least 6 points and uses the DLT algorithm. \n
  370. //!< Initial solution for planar "objectPoints" needs at least 4 points and uses pose from homography decomposition.
  371. SOLVEPNP_EPNP = 1, //!< EPnP: Efficient Perspective-n-Point Camera Pose Estimation @cite lepetit2009epnp
  372. SOLVEPNP_P3P = 2, //!< Complete Solution Classification for the Perspective-Three-Point Problem @cite gao2003complete
  373. SOLVEPNP_DLS = 3, //!< **Broken implementation. Using this flag will fallback to EPnP.** \n
  374. //!< A Direct Least-Squares (DLS) Method for PnP @cite hesch2011direct
  375. SOLVEPNP_UPNP = 4, //!< **Broken implementation. Using this flag will fallback to EPnP.** \n
  376. //!< Exhaustive Linearization for Robust Camera Pose and Focal Length Estimation @cite penate2013exhaustive
  377. SOLVEPNP_AP3P = 5, //!< An Efficient Algebraic Solution to the Perspective-Three-Point Problem @cite Ke17
  378. SOLVEPNP_IPPE = 6, //!< Infinitesimal Plane-Based Pose Estimation @cite Collins14 \n
  379. //!< Object points must be coplanar.
  380. SOLVEPNP_IPPE_SQUARE = 7, //!< Infinitesimal Plane-Based Pose Estimation @cite Collins14 \n
  381. //!< This is a special case suitable for marker pose estimation.\n
  382. //!< 4 coplanar object points must be defined in the following order:
  383. //!< - point 0: [-squareLength / 2, squareLength / 2, 0]
  384. //!< - point 1: [ squareLength / 2, squareLength / 2, 0]
  385. //!< - point 2: [ squareLength / 2, -squareLength / 2, 0]
  386. //!< - point 3: [-squareLength / 2, -squareLength / 2, 0]
  387. SOLVEPNP_SQPNP = 8, //!< SQPnP: A Consistently Fast and Globally OptimalSolution to the Perspective-n-Point Problem @cite Terzakis2020SQPnP
  388. #ifndef CV_DOXYGEN
  389. SOLVEPNP_MAX_COUNT //!< Used for count
  390. #endif
  391. };
  392. enum { CALIB_CB_ADAPTIVE_THRESH = 1,
  393. CALIB_CB_NORMALIZE_IMAGE = 2,
  394. CALIB_CB_FILTER_QUADS = 4,
  395. CALIB_CB_FAST_CHECK = 8
  396. };
  397. enum { CALIB_CB_SYMMETRIC_GRID = 1,
  398. CALIB_CB_ASYMMETRIC_GRID = 2,
  399. CALIB_CB_CLUSTERING = 4
  400. };
  401. enum { CALIB_USE_INTRINSIC_GUESS = 0x00001,
  402. CALIB_FIX_ASPECT_RATIO = 0x00002,
  403. CALIB_FIX_PRINCIPAL_POINT = 0x00004,
  404. CALIB_ZERO_TANGENT_DIST = 0x00008,
  405. CALIB_FIX_FOCAL_LENGTH = 0x00010,
  406. CALIB_FIX_K1 = 0x00020,
  407. CALIB_FIX_K2 = 0x00040,
  408. CALIB_FIX_K3 = 0x00080,
  409. CALIB_FIX_K4 = 0x00800,
  410. CALIB_FIX_K5 = 0x01000,
  411. CALIB_FIX_K6 = 0x02000,
  412. CALIB_RATIONAL_MODEL = 0x04000,
  413. CALIB_THIN_PRISM_MODEL = 0x08000,
  414. CALIB_FIX_S1_S2_S3_S4 = 0x10000,
  415. CALIB_TILTED_MODEL = 0x40000,
  416. CALIB_FIX_TAUX_TAUY = 0x80000,
  417. CALIB_USE_QR = 0x100000, //!< use QR instead of SVD decomposition for solving. Faster but potentially less precise
  418. CALIB_FIX_TANGENT_DIST = 0x200000,
  419. // only for stereo
  420. CALIB_FIX_INTRINSIC = 0x00100,
  421. CALIB_SAME_FOCAL_LENGTH = 0x00200,
  422. // for stereo rectification
  423. CALIB_ZERO_DISPARITY = 0x00400,
  424. CALIB_USE_LU = (1 << 17), //!< use LU instead of SVD decomposition for solving. much faster but potentially less precise
  425. CALIB_USE_EXTRINSIC_GUESS = (1 << 22) //!< for stereoCalibrate
  426. };
  427. //! the algorithm for finding fundamental matrix
  428. enum { FM_7POINT = 1, //!< 7-point algorithm
  429. FM_8POINT = 2, //!< 8-point algorithm
  430. FM_LMEDS = 4, //!< least-median algorithm. 7-point algorithm is used.
  431. FM_RANSAC = 8 //!< RANSAC algorithm. It needs at least 15 points. 7-point algorithm is used.
  432. };
  433. enum HandEyeCalibrationMethod
  434. {
  435. CALIB_HAND_EYE_TSAI = 0, //!< A New Technique for Fully Autonomous and Efficient 3D Robotics Hand/Eye Calibration @cite Tsai89
  436. CALIB_HAND_EYE_PARK = 1, //!< Robot Sensor Calibration: Solving AX = XB on the Euclidean Group @cite Park94
  437. CALIB_HAND_EYE_HORAUD = 2, //!< Hand-eye Calibration @cite Horaud95
  438. CALIB_HAND_EYE_ANDREFF = 3, //!< On-line Hand-Eye Calibration @cite Andreff99
  439. CALIB_HAND_EYE_DANIILIDIS = 4 //!< Hand-Eye Calibration Using Dual Quaternions @cite Daniilidis98
  440. };
  441. /** @brief Converts a rotation matrix to a rotation vector or vice versa.
  442. @param src Input rotation vector (3x1 or 1x3) or rotation matrix (3x3).
  443. @param dst Output rotation matrix (3x3) or rotation vector (3x1 or 1x3), respectively.
  444. @param jacobian Optional output Jacobian matrix, 3x9 or 9x3, which is a matrix of partial
  445. derivatives of the output array components with respect to the input array components.
  446. \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]
  447. Inverse transformation can be also done easily, since
  448. \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]
  449. A rotation vector is a convenient and most compact representation of a rotation matrix (since any
  450. rotation matrix has just 3 degrees of freedom). The representation is used in the global 3D geometry
  451. optimization procedures like @ref calibrateCamera, @ref stereoCalibrate, or @ref solvePnP .
  452. @note More information about the computation of the derivative of a 3D rotation matrix with respect to its exponential coordinate
  453. can be found in:
  454. - A Compact Formula for the Derivative of a 3-D Rotation in Exponential Coordinates, Guillermo Gallego, Anthony J. Yezzi @cite Gallego2014ACF
  455. @note Useful information on SE(3) and Lie Groups can be found in:
  456. - A tutorial on SE(3) transformation parameterizations and on-manifold optimization, Jose-Luis Blanco @cite blanco2010tutorial
  457. - Lie Groups for 2D and 3D Transformation, Ethan Eade @cite Eade17
  458. - A micro Lie theory for state estimation in robotics, Joan Solà, Jérémie Deray, Dinesh Atchuthan @cite Sol2018AML
  459. */
  460. CV_EXPORTS_W void Rodrigues( InputArray src, OutputArray dst, OutputArray jacobian = noArray() );
  461. /** @example samples/cpp/tutorial_code/features2D/Homography/pose_from_homography.cpp
  462. An example program about pose estimation from coplanar points
  463. Check @ref tutorial_homography "the corresponding tutorial" for more details
  464. */
  465. /** @brief Finds a perspective transformation between two planes.
  466. @param srcPoints Coordinates of the points in the original plane, a matrix of the type CV_32FC2
  467. or vector\<Point2f\> .
  468. @param dstPoints Coordinates of the points in the target plane, a matrix of the type CV_32FC2 or
  469. a vector\<Point2f\> .
  470. @param method Method used to compute a homography matrix. The following methods are possible:
  471. - **0** - a regular method using all the points, i.e., the least squares method
  472. - @ref RANSAC - RANSAC-based robust method
  473. - @ref LMEDS - Least-Median robust method
  474. - @ref RHO - PROSAC-based robust method
  475. @param ransacReprojThreshold Maximum allowed reprojection error to treat a point pair as an inlier
  476. (used in the RANSAC and RHO methods only). That is, if
  477. \f[\| \texttt{dstPoints} _i - \texttt{convertPointsHomogeneous} ( \texttt{H} \cdot \texttt{srcPoints} _i) \|_2 > \texttt{ransacReprojThreshold}\f]
  478. then the point \f$i\f$ is considered as an outlier. If srcPoints and dstPoints are measured in pixels,
  479. it usually makes sense to set this parameter somewhere in the range of 1 to 10.
  480. @param mask Optional output mask set by a robust method ( RANSAC or LMeDS ). Note that the input
  481. mask values are ignored.
  482. @param maxIters The maximum number of RANSAC iterations.
  483. @param confidence Confidence level, between 0 and 1.
  484. The function finds and returns the perspective transformation \f$H\f$ between the source and the
  485. destination planes:
  486. \f[s_i \vecthree{x'_i}{y'_i}{1} \sim H \vecthree{x_i}{y_i}{1}\f]
  487. so that the back-projection error
  488. \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]
  489. is minimized. If the parameter method is set to the default value 0, the function uses all the point
  490. pairs to compute an initial homography estimate with a simple least-squares scheme.
  491. However, if not all of the point pairs ( \f$srcPoints_i\f$, \f$dstPoints_i\f$ ) fit the rigid perspective
  492. transformation (that is, there are some outliers), this initial estimate will be poor. In this case,
  493. you can use one of the three robust methods. The methods RANSAC, LMeDS and RHO try many different
  494. random subsets of the corresponding point pairs (of four pairs each, collinear pairs are discarded), estimate the homography matrix
  495. using this subset and a simple least-squares algorithm, and then compute the quality/goodness of the
  496. computed homography (which is the number of inliers for RANSAC or the least median re-projection error for
  497. LMeDS). The best subset is then used to produce the initial estimate of the homography matrix and
  498. the mask of inliers/outliers.
  499. Regardless of the method, robust or not, the computed homography matrix is refined further (using
  500. inliers only in case of a robust method) with the Levenberg-Marquardt method to reduce the
  501. re-projection error even more.
  502. The methods RANSAC and RHO can handle practically any ratio of outliers but need a threshold to
  503. distinguish inliers from outliers. The method LMeDS does not need any threshold but it works
  504. correctly only when there are more than 50% of inliers. Finally, if there are no outliers and the
  505. noise is rather small, use the default method (method=0).
  506. The function is used to find initial intrinsic and extrinsic matrices. Homography matrix is
  507. determined up to a scale. Thus, it is normalized so that \f$h_{33}=1\f$. Note that whenever an \f$H\f$ matrix
  508. cannot be estimated, an empty one will be returned.
  509. @sa
  510. getAffineTransform, estimateAffine2D, estimateAffinePartial2D, getPerspectiveTransform, warpPerspective,
  511. perspectiveTransform
  512. */
  513. CV_EXPORTS_W Mat findHomography( InputArray srcPoints, InputArray dstPoints,
  514. int method = 0, double ransacReprojThreshold = 3,
  515. OutputArray mask=noArray(), const int maxIters = 2000,
  516. const double confidence = 0.995);
  517. /** @overload */
  518. CV_EXPORTS Mat findHomography( InputArray srcPoints, InputArray dstPoints,
  519. OutputArray mask, int method = 0, double ransacReprojThreshold = 3 );
  520. /** @brief Computes an RQ decomposition of 3x3 matrices.
  521. @param src 3x3 input matrix.
  522. @param mtxR Output 3x3 upper-triangular matrix.
  523. @param mtxQ Output 3x3 orthogonal matrix.
  524. @param Qx Optional output 3x3 rotation matrix around x-axis.
  525. @param Qy Optional output 3x3 rotation matrix around y-axis.
  526. @param Qz Optional output 3x3 rotation matrix around z-axis.
  527. The function computes a RQ decomposition using the given rotations. This function is used in
  528. #decomposeProjectionMatrix to decompose the left 3x3 submatrix of a projection matrix into a camera
  529. and a rotation matrix.
  530. It optionally returns three rotation matrices, one for each axis, and the three Euler angles in
  531. degrees (as the return value) that could be used in OpenGL. Note, there is always more than one
  532. sequence of rotations about the three principal axes that results in the same orientation of an
  533. object, e.g. see @cite Slabaugh . Returned tree rotation matrices and corresponding three Euler angles
  534. are only one of the possible solutions.
  535. */
  536. CV_EXPORTS_W Vec3d RQDecomp3x3( InputArray src, OutputArray mtxR, OutputArray mtxQ,
  537. OutputArray Qx = noArray(),
  538. OutputArray Qy = noArray(),
  539. OutputArray Qz = noArray());
  540. /** @brief Decomposes a projection matrix into a rotation matrix and a camera intrinsic matrix.
  541. @param projMatrix 3x4 input projection matrix P.
  542. @param cameraMatrix Output 3x3 camera intrinsic matrix \f$\cameramatrix{A}\f$.
  543. @param rotMatrix Output 3x3 external rotation matrix R.
  544. @param transVect Output 4x1 translation vector T.
  545. @param rotMatrixX Optional 3x3 rotation matrix around x-axis.
  546. @param rotMatrixY Optional 3x3 rotation matrix around y-axis.
  547. @param rotMatrixZ Optional 3x3 rotation matrix around z-axis.
  548. @param eulerAngles Optional three-element vector containing three Euler angles of rotation in
  549. degrees.
  550. The function computes a decomposition of a projection matrix into a calibration and a rotation
  551. matrix and the position of a camera.
  552. It optionally returns three rotation matrices, one for each axis, and three Euler angles that could
  553. be used in OpenGL. Note, there is always more than one sequence of rotations about the three
  554. principal axes that results in the same orientation of an object, e.g. see @cite Slabaugh . Returned
  555. tree rotation matrices and corresponding three Euler angles are only one of the possible solutions.
  556. The function is based on #RQDecomp3x3 .
  557. */
  558. CV_EXPORTS_W void decomposeProjectionMatrix( InputArray projMatrix, OutputArray cameraMatrix,
  559. OutputArray rotMatrix, OutputArray transVect,
  560. OutputArray rotMatrixX = noArray(),
  561. OutputArray rotMatrixY = noArray(),
  562. OutputArray rotMatrixZ = noArray(),
  563. OutputArray eulerAngles =noArray() );
  564. /** @brief Computes partial derivatives of the matrix product for each multiplied matrix.
  565. @param A First multiplied matrix.
  566. @param B Second multiplied matrix.
  567. @param dABdA First output derivative matrix d(A\*B)/dA of size
  568. \f$\texttt{A.rows*B.cols} \times {A.rows*A.cols}\f$ .
  569. @param dABdB Second output derivative matrix d(A\*B)/dB of size
  570. \f$\texttt{A.rows*B.cols} \times {B.rows*B.cols}\f$ .
  571. The function computes partial derivatives of the elements of the matrix product \f$A*B\f$ with regard to
  572. the elements of each of the two input matrices. The function is used to compute the Jacobian
  573. matrices in #stereoCalibrate but can also be used in any other similar optimization function.
  574. */
  575. CV_EXPORTS_W void matMulDeriv( InputArray A, InputArray B, OutputArray dABdA, OutputArray dABdB );
  576. /** @brief Combines two rotation-and-shift transformations.
  577. @param rvec1 First rotation vector.
  578. @param tvec1 First translation vector.
  579. @param rvec2 Second rotation vector.
  580. @param tvec2 Second translation vector.
  581. @param rvec3 Output rotation vector of the superposition.
  582. @param tvec3 Output translation vector of the superposition.
  583. @param dr3dr1 Optional output derivative of rvec3 with regard to rvec1
  584. @param dr3dt1 Optional output derivative of rvec3 with regard to tvec1
  585. @param dr3dr2 Optional output derivative of rvec3 with regard to rvec2
  586. @param dr3dt2 Optional output derivative of rvec3 with regard to tvec2
  587. @param dt3dr1 Optional output derivative of tvec3 with regard to rvec1
  588. @param dt3dt1 Optional output derivative of tvec3 with regard to tvec1
  589. @param dt3dr2 Optional output derivative of tvec3 with regard to rvec2
  590. @param dt3dt2 Optional output derivative of tvec3 with regard to tvec2
  591. The functions compute:
  592. \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]
  593. where \f$\mathrm{rodrigues}\f$ denotes a rotation vector to a rotation matrix transformation, and
  594. \f$\mathrm{rodrigues}^{-1}\f$ denotes the inverse transformation. See #Rodrigues for details.
  595. Also, the functions can compute the derivatives of the output vectors with regards to the input
  596. vectors (see #matMulDeriv ). The functions are used inside #stereoCalibrate but can also be used in
  597. your own code where Levenberg-Marquardt or another gradient-based solver is used to optimize a
  598. function that contains a matrix multiplication.
  599. */
  600. CV_EXPORTS_W void composeRT( InputArray rvec1, InputArray tvec1,
  601. InputArray rvec2, InputArray tvec2,
  602. OutputArray rvec3, OutputArray tvec3,
  603. OutputArray dr3dr1 = noArray(), OutputArray dr3dt1 = noArray(),
  604. OutputArray dr3dr2 = noArray(), OutputArray dr3dt2 = noArray(),
  605. OutputArray dt3dr1 = noArray(), OutputArray dt3dt1 = noArray(),
  606. OutputArray dt3dr2 = noArray(), OutputArray dt3dt2 = noArray() );
  607. /** @brief Projects 3D points to an image plane.
  608. @param objectPoints Array of object points expressed wrt. the world coordinate frame. A 3xN/Nx3
  609. 1-channel or 1xN/Nx1 3-channel (or vector\<Point3f\> ), where N is the number of points in the view.
  610. @param rvec The rotation vector (@ref Rodrigues) that, together with tvec, performs a change of
  611. basis from world to camera coordinate system, see @ref calibrateCamera for details.
  612. @param tvec The translation vector, see parameter description above.
  613. @param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ .
  614. @param distCoeffs Input vector of distortion coefficients
  615. \f$\distcoeffs\f$ . If the vector is empty, the zero distortion coefficients are assumed.
  616. @param imagePoints Output array of image points, 1xN/Nx1 2-channel, or
  617. vector\<Point2f\> .
  618. @param jacobian Optional output 2Nx(10+\<numDistCoeffs\>) jacobian matrix of derivatives of image
  619. points with respect to components of the rotation vector, translation vector, focal lengths,
  620. coordinates of the principal point and the distortion coefficients. In the old interface different
  621. components of the jacobian are returned via different output parameters.
  622. @param aspectRatio Optional "fixed aspect ratio" parameter. If the parameter is not 0, the
  623. function assumes that the aspect ratio (\f$f_x / f_y\f$) is fixed and correspondingly adjusts the
  624. jacobian matrix.
  625. The function computes the 2D projections of 3D points to the image plane, given intrinsic and
  626. extrinsic camera parameters. Optionally, the function computes Jacobians -matrices of partial
  627. derivatives of image points coordinates (as functions of all the input parameters) with respect to
  628. the particular parameters, intrinsic and/or extrinsic. The Jacobians are used during the global
  629. optimization in @ref calibrateCamera, @ref solvePnP, and @ref stereoCalibrate. The function itself
  630. can also be used to compute a re-projection error, given the current intrinsic and extrinsic
  631. parameters.
  632. @note By setting rvec = tvec = \f$[0, 0, 0]\f$, or by setting cameraMatrix to a 3x3 identity matrix,
  633. or by passing zero distortion coefficients, one can get various useful partial cases of the
  634. function. This means, one can compute the distorted coordinates for a sparse set of points or apply
  635. a perspective transformation (and also compute the derivatives) in the ideal zero-distortion setup.
  636. */
  637. CV_EXPORTS_W void projectPoints( InputArray objectPoints,
  638. InputArray rvec, InputArray tvec,
  639. InputArray cameraMatrix, InputArray distCoeffs,
  640. OutputArray imagePoints,
  641. OutputArray jacobian = noArray(),
  642. double aspectRatio = 0 );
  643. /** @example samples/cpp/tutorial_code/features2D/Homography/homography_from_camera_displacement.cpp
  644. An example program about homography from the camera displacement
  645. Check @ref tutorial_homography "the corresponding tutorial" for more details
  646. */
  647. /** @brief Finds an object pose from 3D-2D point correspondences.
  648. @see @ref calib3d_solvePnP
  649. This function returns the rotation and the translation vectors that transform a 3D point expressed in the object
  650. coordinate frame to the camera coordinate frame, using different methods:
  651. - P3P methods (@ref SOLVEPNP_P3P, @ref SOLVEPNP_AP3P): need 4 input points to return a unique solution.
  652. - @ref SOLVEPNP_IPPE Input points must be >= 4 and object points must be coplanar.
  653. - @ref SOLVEPNP_IPPE_SQUARE Special case suitable for marker pose estimation.
  654. Number of input points must be 4. Object points must be defined in the following order:
  655. - point 0: [-squareLength / 2, squareLength / 2, 0]
  656. - point 1: [ squareLength / 2, squareLength / 2, 0]
  657. - point 2: [ squareLength / 2, -squareLength / 2, 0]
  658. - point 3: [-squareLength / 2, -squareLength / 2, 0]
  659. - for all the other flags, number of input points must be >= 4 and object points can be in any configuration.
  660. @param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or
  661. 1xN/Nx1 3-channel, where N is the number of points. vector\<Point3d\> can be also passed here.
  662. @param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel,
  663. where N is the number of points. vector\<Point2d\> can be also passed here.
  664. @param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
  665. @param distCoeffs Input vector of distortion coefficients
  666. \f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
  667. assumed.
  668. @param rvec Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from
  669. the model coordinate system to the camera coordinate system.
  670. @param tvec Output translation vector.
  671. @param useExtrinsicGuess Parameter used for #SOLVEPNP_ITERATIVE. If true (1), the function uses
  672. the provided rvec and tvec values as initial approximations of the rotation and translation
  673. vectors, respectively, and further optimizes them.
  674. @param flags Method for solving a PnP problem: see @ref calib3d_solvePnP_flags
  675. More information about Perspective-n-Points is described in @ref calib3d_solvePnP
  676. @note
  677. - An example of how to use solvePnP for planar augmented reality can be found at
  678. opencv_source_code/samples/python/plane_ar.py
  679. - If you are using Python:
  680. - Numpy array slices won't work as input because solvePnP requires contiguous
  681. arrays (enforced by the assertion using cv::Mat::checkVector() around line 55 of
  682. modules/calib3d/src/solvepnp.cpp version 2.4.9)
  683. - The P3P algorithm requires image points to be in an array of shape (N,1,2) due
  684. to its calling of cv::undistortPoints (around line 75 of modules/calib3d/src/solvepnp.cpp version 2.4.9)
  685. which requires 2-channel information.
  686. - Thus, given some data D = np.array(...) where D.shape = (N,M), in order to use a subset of
  687. it as, e.g., imagePoints, one must effectively copy it into a new array: imagePoints =
  688. np.ascontiguousarray(D[:,:2]).reshape((N,1,2))
  689. - The methods @ref SOLVEPNP_DLS and @ref SOLVEPNP_UPNP cannot be used as the current implementations are
  690. unstable and sometimes give completely wrong results. If you pass one of these two
  691. flags, @ref SOLVEPNP_EPNP method will be used instead.
  692. - The minimum number of points is 4 in the general case. In the case of @ref SOLVEPNP_P3P and @ref SOLVEPNP_AP3P
  693. methods, it is required to use exactly 4 points (the first 3 points are used to estimate all the solutions
  694. of the P3P problem, the last one is used to retain the best solution that minimizes the reprojection error).
  695. - With @ref SOLVEPNP_ITERATIVE method and `useExtrinsicGuess=true`, the minimum number of points is 3 (3 points
  696. are sufficient to compute a pose but there are up to 4 solutions). The initial solution should be close to the
  697. global solution to converge.
  698. - With @ref SOLVEPNP_IPPE input points must be >= 4 and object points must be coplanar.
  699. - With @ref SOLVEPNP_IPPE_SQUARE this is a special case suitable for marker pose estimation.
  700. Number of input points must be 4. Object points must be defined in the following order:
  701. - point 0: [-squareLength / 2, squareLength / 2, 0]
  702. - point 1: [ squareLength / 2, squareLength / 2, 0]
  703. - point 2: [ squareLength / 2, -squareLength / 2, 0]
  704. - point 3: [-squareLength / 2, -squareLength / 2, 0]
  705. - With @ref SOLVEPNP_SQPNP input points must be >= 3
  706. */
  707. CV_EXPORTS_W bool solvePnP( InputArray objectPoints, InputArray imagePoints,
  708. InputArray cameraMatrix, InputArray distCoeffs,
  709. OutputArray rvec, OutputArray tvec,
  710. bool useExtrinsicGuess = false, int flags = SOLVEPNP_ITERATIVE );
  711. /** @brief Finds an object pose from 3D-2D point correspondences using the RANSAC scheme.
  712. @see @ref calib3d_solvePnP
  713. @param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or
  714. 1xN/Nx1 3-channel, where N is the number of points. vector\<Point3d\> can be also passed here.
  715. @param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel,
  716. where N is the number of points. vector\<Point2d\> can be also passed here.
  717. @param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
  718. @param distCoeffs Input vector of distortion coefficients
  719. \f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
  720. assumed.
  721. @param rvec Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from
  722. the model coordinate system to the camera coordinate system.
  723. @param tvec Output translation vector.
  724. @param useExtrinsicGuess Parameter used for @ref SOLVEPNP_ITERATIVE. If true (1), the function uses
  725. the provided rvec and tvec values as initial approximations of the rotation and translation
  726. vectors, respectively, and further optimizes them.
  727. @param iterationsCount Number of iterations.
  728. @param reprojectionError Inlier threshold value used by the RANSAC procedure. The parameter value
  729. is the maximum allowed distance between the observed and computed point projections to consider it
  730. an inlier.
  731. @param confidence The probability that the algorithm produces a useful result.
  732. @param inliers Output vector that contains indices of inliers in objectPoints and imagePoints .
  733. @param flags Method for solving a PnP problem (see @ref solvePnP ).
  734. The function estimates an object pose given a set of object points, their corresponding image
  735. projections, as well as the camera intrinsic matrix and the distortion coefficients. This function finds such
  736. a pose that minimizes reprojection error, that is, the sum of squared distances between the observed
  737. projections imagePoints and the projected (using @ref projectPoints ) objectPoints. The use of RANSAC
  738. makes the function resistant to outliers.
  739. @note
  740. - An example of how to use solvePNPRansac for object detection can be found at
  741. opencv_source_code/samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/
  742. - The default method used to estimate the camera pose for the Minimal Sample Sets step
  743. is #SOLVEPNP_EPNP. Exceptions are:
  744. - if you choose #SOLVEPNP_P3P or #SOLVEPNP_AP3P, these methods will be used.
  745. - if the number of input points is equal to 4, #SOLVEPNP_P3P is used.
  746. - The method used to estimate the camera pose using all the inliers is defined by the
  747. flags parameters unless it is equal to #SOLVEPNP_P3P or #SOLVEPNP_AP3P. In this case,
  748. the method #SOLVEPNP_EPNP will be used instead.
  749. */
  750. CV_EXPORTS_W bool solvePnPRansac( InputArray objectPoints, InputArray imagePoints,
  751. InputArray cameraMatrix, InputArray distCoeffs,
  752. OutputArray rvec, OutputArray tvec,
  753. bool useExtrinsicGuess = false, int iterationsCount = 100,
  754. float reprojectionError = 8.0, double confidence = 0.99,
  755. OutputArray inliers = noArray(), int flags = SOLVEPNP_ITERATIVE );
  756. /** @brief Finds an object pose from 3 3D-2D point correspondences.
  757. @see @ref calib3d_solvePnP
  758. @param objectPoints Array of object points in the object coordinate space, 3x3 1-channel or
  759. 1x3/3x1 3-channel. vector\<Point3f\> can be also passed here.
  760. @param imagePoints Array of corresponding image points, 3x2 1-channel or 1x3/3x1 2-channel.
  761. vector\<Point2f\> can be also passed here.
  762. @param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
  763. @param distCoeffs Input vector of distortion coefficients
  764. \f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
  765. assumed.
  766. @param rvecs Output rotation vectors (see @ref Rodrigues ) that, together with tvecs, brings points from
  767. the model coordinate system to the camera coordinate system. A P3P problem has up to 4 solutions.
  768. @param tvecs Output translation vectors.
  769. @param flags Method for solving a P3P problem:
  770. - @ref SOLVEPNP_P3P Method is based on the paper of X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang
  771. "Complete Solution Classification for the Perspective-Three-Point Problem" (@cite gao2003complete).
  772. - @ref SOLVEPNP_AP3P Method is based on the paper of T. Ke and S. Roumeliotis.
  773. "An Efficient Algebraic Solution to the Perspective-Three-Point Problem" (@cite Ke17).
  774. The function estimates the object pose given 3 object points, their corresponding image
  775. projections, as well as the camera intrinsic matrix and the distortion coefficients.
  776. @note
  777. The solutions are sorted by reprojection errors (lowest to highest).
  778. */
  779. CV_EXPORTS_W int solveP3P( InputArray objectPoints, InputArray imagePoints,
  780. InputArray cameraMatrix, InputArray distCoeffs,
  781. OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs,
  782. int flags );
  783. /** @brief Refine a pose (the translation and the rotation that transform a 3D point expressed in the object coordinate frame
  784. to the camera coordinate frame) from a 3D-2D point correspondences and starting from an initial solution.
  785. @see @ref calib3d_solvePnP
  786. @param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or 1xN/Nx1 3-channel,
  787. where N is the number of points. vector\<Point3d\> can also be passed here.
  788. @param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel,
  789. where N is the number of points. vector\<Point2d\> can also be passed here.
  790. @param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
  791. @param distCoeffs Input vector of distortion coefficients
  792. \f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
  793. assumed.
  794. @param rvec Input/Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from
  795. the model coordinate system to the camera coordinate system. Input values are used as an initial solution.
  796. @param tvec Input/Output translation vector. Input values are used as an initial solution.
  797. @param criteria Criteria when to stop the Levenberg-Marquard iterative algorithm.
  798. The function refines the object pose given at least 3 object points, their corresponding image
  799. projections, an initial solution for the rotation and translation vector,
  800. as well as the camera intrinsic matrix and the distortion coefficients.
  801. The function minimizes the projection error with respect to the rotation and the translation vectors, according
  802. to a Levenberg-Marquardt iterative minimization @cite Madsen04 @cite Eade13 process.
  803. */
  804. CV_EXPORTS_W void solvePnPRefineLM( InputArray objectPoints, InputArray imagePoints,
  805. InputArray cameraMatrix, InputArray distCoeffs,
  806. InputOutputArray rvec, InputOutputArray tvec,
  807. TermCriteria criteria = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 20, FLT_EPSILON));
  808. /** @brief Refine a pose (the translation and the rotation that transform a 3D point expressed in the object coordinate frame
  809. to the camera coordinate frame) from a 3D-2D point correspondences and starting from an initial solution.
  810. @see @ref calib3d_solvePnP
  811. @param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or 1xN/Nx1 3-channel,
  812. where N is the number of points. vector\<Point3d\> can also be passed here.
  813. @param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel,
  814. where N is the number of points. vector\<Point2d\> can also be passed here.
  815. @param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
  816. @param distCoeffs Input vector of distortion coefficients
  817. \f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
  818. assumed.
  819. @param rvec Input/Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from
  820. the model coordinate system to the camera coordinate system. Input values are used as an initial solution.
  821. @param tvec Input/Output translation vector. Input values are used as an initial solution.
  822. @param criteria Criteria when to stop the Levenberg-Marquard iterative algorithm.
  823. @param VVSlambda Gain for the virtual visual servoing control law, equivalent to the \f$\alpha\f$
  824. gain in the Damped Gauss-Newton formulation.
  825. The function refines the object pose given at least 3 object points, their corresponding image
  826. projections, an initial solution for the rotation and translation vector,
  827. as well as the camera intrinsic matrix and the distortion coefficients.
  828. The function minimizes the projection error with respect to the rotation and the translation vectors, using a
  829. virtual visual servoing (VVS) @cite Chaumette06 @cite Marchand16 scheme.
  830. */
  831. CV_EXPORTS_W void solvePnPRefineVVS( InputArray objectPoints, InputArray imagePoints,
  832. InputArray cameraMatrix, InputArray distCoeffs,
  833. InputOutputArray rvec, InputOutputArray tvec,
  834. TermCriteria criteria = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 20, FLT_EPSILON),
  835. double VVSlambda = 1);
  836. /** @brief Finds an object pose from 3D-2D point correspondences.
  837. @see @ref calib3d_solvePnP
  838. This function returns a list of all the possible solutions (a solution is a <rotation vector, translation vector>
  839. couple), depending on the number of input points and the chosen method:
  840. - 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.
  841. - @ref SOLVEPNP_IPPE Input points must be >= 4 and object points must be coplanar. Returns 2 solutions.
  842. - @ref SOLVEPNP_IPPE_SQUARE Special case suitable for marker pose estimation.
  843. Number of input points must be 4 and 2 solutions are returned. Object points must be defined in the following order:
  844. - point 0: [-squareLength / 2, squareLength / 2, 0]
  845. - point 1: [ squareLength / 2, squareLength / 2, 0]
  846. - point 2: [ squareLength / 2, -squareLength / 2, 0]
  847. - point 3: [-squareLength / 2, -squareLength / 2, 0]
  848. - for all the other flags, number of input points must be >= 4 and object points can be in any configuration.
  849. Only 1 solution is returned.
  850. @param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or
  851. 1xN/Nx1 3-channel, where N is the number of points. vector\<Point3d\> can be also passed here.
  852. @param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel,
  853. where N is the number of points. vector\<Point2d\> can be also passed here.
  854. @param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ .
  855. @param distCoeffs Input vector of distortion coefficients
  856. \f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
  857. assumed.
  858. @param rvecs Vector of output rotation vectors (see @ref Rodrigues ) that, together with tvecs, brings points from
  859. the model coordinate system to the camera coordinate system.
  860. @param tvecs Vector of output translation vectors.
  861. @param useExtrinsicGuess Parameter used for #SOLVEPNP_ITERATIVE. If true (1), the function uses
  862. the provided rvec and tvec values as initial approximations of the rotation and translation
  863. vectors, respectively, and further optimizes them.
  864. @param flags Method for solving a PnP problem: see @ref calib3d_solvePnP_flags
  865. @param rvec Rotation vector used to initialize an iterative PnP refinement algorithm, when flag is @ref SOLVEPNP_ITERATIVE
  866. and useExtrinsicGuess is set to true.
  867. @param tvec Translation vector used to initialize an iterative PnP refinement algorithm, when flag is @ref SOLVEPNP_ITERATIVE
  868. and useExtrinsicGuess is set to true.
  869. @param reprojectionError Optional vector of reprojection error, that is the RMS error
  870. (\f$ \text{RMSE} = \sqrt{\frac{\sum_{i}^{N} \left ( \hat{y_i} - y_i \right )^2}{N}} \f$) between the input image points
  871. and the 3D object points projected with the estimated pose.
  872. More information is described in @ref calib3d_solvePnP
  873. @note
  874. - An example of how to use solvePnP for planar augmented reality can be found at
  875. opencv_source_code/samples/python/plane_ar.py
  876. - If you are using Python:
  877. - Numpy array slices won't work as input because solvePnP requires contiguous
  878. arrays (enforced by the assertion using cv::Mat::checkVector() around line 55 of
  879. modules/calib3d/src/solvepnp.cpp version 2.4.9)
  880. - The P3P algorithm requires image points to be in an array of shape (N,1,2) due
  881. to its calling of cv::undistortPoints (around line 75 of modules/calib3d/src/solvepnp.cpp version 2.4.9)
  882. which requires 2-channel information.
  883. - Thus, given some data D = np.array(...) where D.shape = (N,M), in order to use a subset of
  884. it as, e.g., imagePoints, one must effectively copy it into a new array: imagePoints =
  885. np.ascontiguousarray(D[:,:2]).reshape((N,1,2))
  886. - The methods @ref SOLVEPNP_DLS and @ref SOLVEPNP_UPNP cannot be used as the current implementations are
  887. unstable and sometimes give completely wrong results. If you pass one of these two
  888. flags, @ref SOLVEPNP_EPNP method will be used instead.
  889. - The minimum number of points is 4 in the general case. In the case of @ref SOLVEPNP_P3P and @ref SOLVEPNP_AP3P
  890. methods, it is required to use exactly 4 points (the first 3 points are used to estimate all the solutions
  891. of the P3P problem, the last one is used to retain the best solution that minimizes the reprojection error).
  892. - With @ref SOLVEPNP_ITERATIVE method and `useExtrinsicGuess=true`, the minimum number of points is 3 (3 points
  893. are sufficient to compute a pose but there are up to 4 solutions). The initial solution should be close to the
  894. global solution to converge.
  895. - With @ref SOLVEPNP_IPPE input points must be >= 4 and object points must be coplanar.
  896. - With @ref SOLVEPNP_IPPE_SQUARE this is a special case suitable for marker pose estimation.
  897. Number of input points must be 4. Object points must be defined in the following order:
  898. - point 0: [-squareLength / 2, squareLength / 2, 0]
  899. - point 1: [ squareLength / 2, squareLength / 2, 0]
  900. - point 2: [ squareLength / 2, -squareLength / 2, 0]
  901. - point 3: [-squareLength / 2, -squareLength / 2, 0]
  902. */
  903. CV_EXPORTS_W int solvePnPGeneric( InputArray objectPoints, InputArray imagePoints,
  904. InputArray cameraMatrix, InputArray distCoeffs,
  905. OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs,
  906. bool useExtrinsicGuess = false, SolvePnPMethod flags = SOLVEPNP_ITERATIVE,
  907. InputArray rvec = noArray(), InputArray tvec = noArray(),
  908. OutputArray reprojectionError = noArray() );
  909. /** @brief Finds an initial camera intrinsic matrix from 3D-2D point correspondences.
  910. @param objectPoints Vector of vectors of the calibration pattern points in the calibration pattern
  911. coordinate space. In the old interface all the per-view vectors are concatenated. See
  912. calibrateCamera for details.
  913. @param imagePoints Vector of vectors of the projections of the calibration pattern points. In the
  914. old interface all the per-view vectors are concatenated.
  915. @param imageSize Image size in pixels used to initialize the principal point.
  916. @param aspectRatio If it is zero or negative, both \f$f_x\f$ and \f$f_y\f$ are estimated independently.
  917. Otherwise, \f$f_x = f_y \cdot \texttt{aspectRatio}\f$ .
  918. The function estimates and returns an initial camera intrinsic matrix for the camera calibration process.
  919. Currently, the function only supports planar calibration patterns, which are patterns where each
  920. object point has z-coordinate =0.
  921. */
  922. CV_EXPORTS_W Mat initCameraMatrix2D( InputArrayOfArrays objectPoints,
  923. InputArrayOfArrays imagePoints,
  924. Size imageSize, double aspectRatio = 1.0 );
  925. /** @brief Finds the positions of internal corners of the chessboard.
  926. @param image Source chessboard view. It must be an 8-bit grayscale or color image.
  927. @param patternSize Number of inner corners per a chessboard row and column
  928. ( patternSize = cv::Size(points_per_row,points_per_colum) = cv::Size(columns,rows) ).
  929. @param corners Output array of detected corners.
  930. @param flags Various operation flags that can be zero or a combination of the following values:
  931. - @ref CALIB_CB_ADAPTIVE_THRESH Use adaptive thresholding to convert the image to black
  932. and white, rather than a fixed threshold level (computed from the average image brightness).
  933. - @ref CALIB_CB_NORMALIZE_IMAGE Normalize the image gamma with #equalizeHist before
  934. applying fixed or adaptive thresholding.
  935. - @ref CALIB_CB_FILTER_QUADS Use additional criteria (like contour area, perimeter,
  936. square-like shape) to filter out false quads extracted at the contour retrieval stage.
  937. - @ref CALIB_CB_FAST_CHECK Run a fast check on the image that looks for chessboard corners,
  938. and shortcut the call if none is found. This can drastically speed up the call in the
  939. degenerate condition when no chessboard is observed.
  940. The function attempts to determine whether the input image is a view of the chessboard pattern and
  941. locate the internal chessboard corners. The function returns a non-zero value if all of the corners
  942. are found and they are placed in a certain order (row by row, left to right in every row).
  943. Otherwise, if the function fails to find all the corners or reorder them, it returns 0. For example,
  944. a regular chessboard has 8 x 8 squares and 7 x 7 internal corners, that is, points where the black
  945. squares touch each other. The detected coordinates are approximate, and to determine their positions
  946. more accurately, the function calls #cornerSubPix. You also may use the function #cornerSubPix with
  947. different parameters if returned coordinates are not accurate enough.
  948. Sample usage of detecting and drawing chessboard corners: :
  949. @code
  950. Size patternsize(8,6); //interior number of corners
  951. Mat gray = ....; //source image
  952. vector<Point2f> corners; //this will be filled by the detected corners
  953. //CALIB_CB_FAST_CHECK saves a lot of time on images
  954. //that do not contain any chessboard corners
  955. bool patternfound = findChessboardCorners(gray, patternsize, corners,
  956. CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE
  957. + CALIB_CB_FAST_CHECK);
  958. if(patternfound)
  959. cornerSubPix(gray, corners, Size(11, 11), Size(-1, -1),
  960. TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1));
  961. drawChessboardCorners(img, patternsize, Mat(corners), patternfound);
  962. @endcode
  963. @note The function requires white space (like a square-thick border, the wider the better) around
  964. the board to make the detection more robust in various environments. Otherwise, if there is no
  965. border and the background is dark, the outer black squares cannot be segmented properly and so the
  966. square grouping and ordering algorithm fails.
  967. */
  968. CV_EXPORTS_W bool findChessboardCorners( InputArray image, Size patternSize, OutputArray corners,
  969. int flags = CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE );
  970. //! finds subpixel-accurate positions of the chessboard corners
  971. CV_EXPORTS_W bool find4QuadCornerSubpix( InputArray img, InputOutputArray corners, Size region_size );
  972. /** @brief Renders the detected chessboard corners.
  973. @param image Destination image. It must be an 8-bit color image.
  974. @param patternSize Number of inner corners per a chessboard row and column
  975. (patternSize = cv::Size(points_per_row,points_per_column)).
  976. @param corners Array of detected corners, the output of #findChessboardCorners.
  977. @param patternWasFound Parameter indicating whether the complete board was found or not. The
  978. return value of #findChessboardCorners should be passed here.
  979. The function draws individual chessboard corners detected either as red circles if the board was not
  980. found, or as colored corners connected with lines if the board was found.
  981. */
  982. CV_EXPORTS_W void drawChessboardCorners( InputOutputArray image, Size patternSize,
  983. InputArray corners, bool patternWasFound );
  984. /** @brief Draw axes of the world/object coordinate system from pose estimation. @sa solvePnP
  985. @param image Input/output image. It must have 1 or 3 channels. The number of channels is not altered.
  986. @param cameraMatrix Input 3x3 floating-point matrix of camera intrinsic parameters.
  987. \f$\cameramatrix{A}\f$
  988. @param distCoeffs Input vector of distortion coefficients
  989. \f$\distcoeffs\f$. If the vector is empty, the zero distortion coefficients are assumed.
  990. @param rvec Rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from
  991. the model coordinate system to the camera coordinate system.
  992. @param tvec Translation vector.
  993. @param length Length of the painted axes in the same unit than tvec (usually in meters).
  994. @param thickness Line thickness of the painted axes.
  995. This function draws the axes of the world/object coordinate system w.r.t. to the camera frame.
  996. OX is drawn in red, OY in green and OZ in blue.
  997. */
  998. CV_EXPORTS_W void drawFrameAxes(InputOutputArray image, InputArray cameraMatrix, InputArray distCoeffs,
  999. InputArray rvec, InputArray tvec, float length, int thickness=3);
  1000. struct CV_EXPORTS_W_SIMPLE CirclesGridFinderParameters
  1001. {
  1002. CV_WRAP CirclesGridFinderParameters();
  1003. CV_PROP_RW cv::Size2f densityNeighborhoodSize;
  1004. CV_PROP_RW float minDensity;
  1005. CV_PROP_RW int kmeansAttempts;
  1006. CV_PROP_RW int minDistanceToAddKeypoint;
  1007. CV_PROP_RW int keypointScale;
  1008. CV_PROP_RW float minGraphConfidence;
  1009. CV_PROP_RW float vertexGain;
  1010. CV_PROP_RW float vertexPenalty;
  1011. CV_PROP_RW float existingVertexGain;
  1012. CV_PROP_RW float edgeGain;
  1013. CV_PROP_RW float edgePenalty;
  1014. CV_PROP_RW float convexHullFactor;
  1015. CV_PROP_RW float minRNGEdgeSwitchDist;
  1016. enum GridType
  1017. {
  1018. SYMMETRIC_GRID, ASYMMETRIC_GRID
  1019. };
  1020. GridType gridType;
  1021. };
  1022. struct CV_EXPORTS_W_SIMPLE CirclesGridFinderParameters2 : public CirclesGridFinderParameters
  1023. {
  1024. CV_WRAP CirclesGridFinderParameters2();
  1025. CV_PROP_RW float squareSize; //!< Distance between two adjacent points. Used by CALIB_CB_CLUSTERING.
  1026. CV_PROP_RW float maxRectifiedDistance; //!< Max deviation from prediction. Used by CALIB_CB_CLUSTERING.
  1027. };
  1028. /** @brief Finds centers in the grid of circles.
  1029. @param image grid view of input circles; it must be an 8-bit grayscale or color image.
  1030. @param patternSize number of circles per row and column
  1031. ( patternSize = Size(points_per_row, points_per_colum) ).
  1032. @param centers output array of detected centers.
  1033. @param flags various operation flags that can be one of the following values:
  1034. - @ref CALIB_CB_SYMMETRIC_GRID uses symmetric pattern of circles.
  1035. - @ref CALIB_CB_ASYMMETRIC_GRID uses asymmetric pattern of circles.
  1036. - @ref CALIB_CB_CLUSTERING uses a special algorithm for grid detection. It is more robust to
  1037. perspective distortions but much more sensitive to background clutter.
  1038. @param blobDetector feature detector that finds blobs like dark circles on light background.
  1039. If `blobDetector` is NULL then `image` represents Point2f array of candidates.
  1040. @param parameters struct for finding circles in a grid pattern.
  1041. The function attempts to determine whether the input image contains a grid of circles. If it is, the
  1042. function locates centers of the circles. The function returns a non-zero value if all of the centers
  1043. have been found and they have been placed in a certain order (row by row, left to right in every
  1044. row). Otherwise, if the function fails to find all the corners or reorder them, it returns 0.
  1045. Sample usage of detecting and drawing the centers of circles: :
  1046. @code
  1047. Size patternsize(7,7); //number of centers
  1048. Mat gray = ...; //source image
  1049. vector<Point2f> centers; //this will be filled by the detected centers
  1050. bool patternfound = findCirclesGrid(gray, patternsize, centers);
  1051. drawChessboardCorners(img, patternsize, Mat(centers), patternfound);
  1052. @endcode
  1053. @note The function requires white space (like a square-thick border, the wider the better) around
  1054. the board to make the detection more robust in various environments.
  1055. */
  1056. CV_EXPORTS_W bool findCirclesGrid( InputArray image, Size patternSize,
  1057. OutputArray centers, int flags,
  1058. const Ptr<FeatureDetector> &blobDetector,
  1059. CirclesGridFinderParameters parameters);
  1060. /** @overload */
  1061. CV_EXPORTS_W bool findCirclesGrid2( InputArray image, Size patternSize,
  1062. OutputArray centers, int flags,
  1063. const Ptr<FeatureDetector> &blobDetector,
  1064. CirclesGridFinderParameters2 parameters);
  1065. /** @overload */
  1066. CV_EXPORTS_W bool findCirclesGrid( InputArray image, Size patternSize,
  1067. OutputArray centers, int flags = CALIB_CB_SYMMETRIC_GRID,
  1068. const Ptr<FeatureDetector> &blobDetector = SimpleBlobDetector::create());
  1069. /** @brief Finds the camera intrinsic and extrinsic parameters from several views of a calibration
  1070. pattern.
  1071. @param objectPoints In the new interface it is a vector of vectors of calibration pattern points in
  1072. the calibration pattern coordinate space (e.g. std::vector<std::vector<cv::Vec3f>>). The outer
  1073. vector contains as many elements as the number of pattern views. If the same calibration pattern
  1074. is shown in each view and it is fully visible, all the vectors will be the same. Although, it is
  1075. possible to use partially occluded patterns or even different patterns in different views. Then,
  1076. the vectors will be different. Although the points are 3D, they all lie in the calibration pattern's
  1077. XY coordinate plane (thus 0 in the Z-coordinate), if the used calibration pattern is a planar rig.
  1078. In the old interface all the vectors of object points from different views are concatenated
  1079. together.
  1080. @param imagePoints In the new interface it is a vector of vectors of the projections of calibration
  1081. pattern points (e.g. std::vector<std::vector<cv::Vec2f>>). imagePoints.size() and
  1082. objectPoints.size(), and imagePoints[i].size() and objectPoints[i].size() for each i, must be equal,
  1083. respectively. In the old interface all the vectors of object points from different views are
  1084. concatenated together.
  1085. @param imageSize Size of the image used only to initialize the camera intrinsic matrix.
  1086. @param cameraMatrix Input/output 3x3 floating-point camera intrinsic matrix
  1087. \f$\cameramatrix{A}\f$ . If @ref CALIB_USE_INTRINSIC_GUESS
  1088. and/or @ref CALIB_FIX_ASPECT_RATIO, @ref CALIB_FIX_PRINCIPAL_POINT or @ref CALIB_FIX_FOCAL_LENGTH
  1089. are specified, some or all of fx, fy, cx, cy must be initialized before calling the function.
  1090. @param distCoeffs Input/output vector of distortion coefficients
  1091. \f$\distcoeffs\f$.
  1092. @param rvecs Output vector of rotation vectors (@ref Rodrigues ) estimated for each pattern view
  1093. (e.g. std::vector<cv::Mat>>). That is, each i-th rotation vector together with the corresponding
  1094. i-th translation vector (see the next output parameter description) brings the calibration pattern
  1095. from the object coordinate space (in which object points are specified) to the camera coordinate
  1096. space. In more technical terms, the tuple of the i-th rotation and translation vector performs
  1097. a change of basis from object coordinate space to camera coordinate space. Due to its duality, this
  1098. tuple is equivalent to the position of the calibration pattern with respect to the camera coordinate
  1099. space.
  1100. @param tvecs Output vector of translation vectors estimated for each pattern view, see parameter
  1101. describtion above.
  1102. @param stdDeviationsIntrinsics Output vector of standard deviations estimated for intrinsic
  1103. parameters. Order of deviations values:
  1104. \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,
  1105. s_4, \tau_x, \tau_y)\f$ If one of parameters is not estimated, it's deviation is equals to zero.
  1106. @param stdDeviationsExtrinsics Output vector of standard deviations estimated for extrinsic
  1107. parameters. Order of deviations values: \f$(R_0, T_0, \dotsc , R_{M - 1}, T_{M - 1})\f$ where M is
  1108. the number of pattern views. \f$R_i, T_i\f$ are concatenated 1x3 vectors.
  1109. @param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view.
  1110. @param flags Different flags that may be zero or a combination of the following values:
  1111. - @ref CALIB_USE_INTRINSIC_GUESS cameraMatrix contains valid initial values of
  1112. fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image
  1113. center ( imageSize is used), and focal distances are computed in a least-squares fashion.
  1114. Note, that if intrinsic parameters are known, there is no need to use this function just to
  1115. estimate extrinsic parameters. Use @ref solvePnP instead.
  1116. - @ref CALIB_FIX_PRINCIPAL_POINT The principal point is not changed during the global
  1117. optimization. It stays at the center or at a different location specified when
  1118. @ref CALIB_USE_INTRINSIC_GUESS is set too.
  1119. - @ref CALIB_FIX_ASPECT_RATIO The functions consider only fy as a free parameter. The
  1120. ratio fx/fy stays the same as in the input cameraMatrix . When
  1121. @ref CALIB_USE_INTRINSIC_GUESS is not set, the actual input values of fx and fy are
  1122. ignored, only their ratio is computed and used further.
  1123. - @ref CALIB_ZERO_TANGENT_DIST Tangential distortion coefficients \f$(p_1, p_2)\f$ are set
  1124. to zeros and stay zero.
  1125. - @ref CALIB_FIX_FOCAL_LENGTH The focal length is not changed during the global optimization if
  1126. @ref CALIB_USE_INTRINSIC_GUESS is set.
  1127. - @ref CALIB_FIX_K1,..., @ref CALIB_FIX_K6 The corresponding radial distortion
  1128. coefficient is not changed during the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is
  1129. set, the coefficient from the supplied distCoeffs matrix is used. Otherwise, it is set to 0.
  1130. - @ref CALIB_RATIONAL_MODEL Coefficients k4, k5, and k6 are enabled. To provide the
  1131. backward compatibility, this extra flag should be explicitly specified to make the
  1132. calibration function use the rational model and return 8 coefficients or more.
  1133. - @ref CALIB_THIN_PRISM_MODEL Coefficients s1, s2, s3 and s4 are enabled. To provide the
  1134. backward compatibility, this extra flag should be explicitly specified to make the
  1135. calibration function use the thin prism model and return 12 coefficients or more.
  1136. - @ref CALIB_FIX_S1_S2_S3_S4 The thin prism distortion coefficients are not changed during
  1137. the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the
  1138. supplied distCoeffs matrix is used. Otherwise, it is set to 0.
  1139. - @ref CALIB_TILTED_MODEL Coefficients tauX and tauY are enabled. To provide the
  1140. backward compatibility, this extra flag should be explicitly specified to make the
  1141. calibration function use the tilted sensor model and return 14 coefficients.
  1142. - @ref CALIB_FIX_TAUX_TAUY The coefficients of the tilted sensor model are not changed during
  1143. the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the
  1144. supplied distCoeffs matrix is used. Otherwise, it is set to 0.
  1145. @param criteria Termination criteria for the iterative optimization algorithm.
  1146. @return the overall RMS re-projection error.
  1147. The function estimates the intrinsic camera parameters and extrinsic parameters for each of the
  1148. views. The algorithm is based on @cite Zhang2000 and @cite BouguetMCT . The coordinates of 3D object
  1149. points and their corresponding 2D projections in each view must be specified. That may be achieved
  1150. by using an object with known geometry and easily detectable feature points. Such an object is
  1151. called a calibration rig or calibration pattern, and OpenCV has built-in support for a chessboard as
  1152. a calibration rig (see @ref findChessboardCorners). Currently, initialization of intrinsic
  1153. parameters (when @ref CALIB_USE_INTRINSIC_GUESS is not set) is only implemented for planar calibration
  1154. patterns (where Z-coordinates of the object points must be all zeros). 3D calibration rigs can also
  1155. be used as long as initial cameraMatrix is provided.
  1156. The algorithm performs the following steps:
  1157. - Compute the initial intrinsic parameters (the option only available for planar calibration
  1158. patterns) or read them from the input parameters. The distortion coefficients are all set to
  1159. zeros initially unless some of CALIB_FIX_K? are specified.
  1160. - Estimate the initial camera pose as if the intrinsic parameters have been already known. This is
  1161. done using @ref solvePnP .
  1162. - Run the global Levenberg-Marquardt optimization algorithm to minimize the reprojection error,
  1163. that is, the total sum of squared distances between the observed feature points imagePoints and
  1164. the projected (using the current estimates for camera parameters and the poses) object points
  1165. objectPoints. See @ref projectPoints for details.
  1166. @note
  1167. If you use a non-square (i.e. non-N-by-N) grid and @ref findChessboardCorners for calibration,
  1168. and @ref calibrateCamera returns bad values (zero distortion coefficients, \f$c_x\f$ and
  1169. \f$c_y\f$ very far from the image center, and/or large differences between \f$f_x\f$ and
  1170. \f$f_y\f$ (ratios of 10:1 or more)), then you are probably using patternSize=cvSize(rows,cols)
  1171. instead of using patternSize=cvSize(cols,rows) in @ref findChessboardCorners.
  1172. @sa
  1173. findChessboardCorners, solvePnP, initCameraMatrix2D, stereoCalibrate, undistort
  1174. */
  1175. CV_EXPORTS_AS(calibrateCameraExtended) double calibrateCamera( InputArrayOfArrays objectPoints,
  1176. InputArrayOfArrays imagePoints, Size imageSize,
  1177. InputOutputArray cameraMatrix, InputOutputArray distCoeffs,
  1178. OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs,
  1179. OutputArray stdDeviationsIntrinsics,
  1180. OutputArray stdDeviationsExtrinsics,
  1181. OutputArray perViewErrors,
  1182. int flags = 0, TermCriteria criteria = TermCriteria(
  1183. TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) );
  1184. /** @overload double calibrateCamera( InputArrayOfArrays objectPoints,
  1185. InputArrayOfArrays imagePoints, Size imageSize,
  1186. InputOutputArray cameraMatrix, InputOutputArray distCoeffs,
  1187. OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs,
  1188. OutputArray stdDeviations, OutputArray perViewErrors,
  1189. int flags = 0, TermCriteria criteria = TermCriteria(
  1190. TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) )
  1191. */
  1192. CV_EXPORTS_W double calibrateCamera( InputArrayOfArrays objectPoints,
  1193. InputArrayOfArrays imagePoints, Size imageSize,
  1194. InputOutputArray cameraMatrix, InputOutputArray distCoeffs,
  1195. OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs,
  1196. int flags = 0, TermCriteria criteria = TermCriteria(
  1197. TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) );
  1198. /** @brief Computes useful camera characteristics from the camera intrinsic matrix.
  1199. @param cameraMatrix Input camera intrinsic matrix that can be estimated by calibrateCamera or
  1200. stereoCalibrate .
  1201. @param imageSize Input image size in pixels.
  1202. @param apertureWidth Physical width in mm of the sensor.
  1203. @param apertureHeight Physical height in mm of the sensor.
  1204. @param fovx Output field of view in degrees along the horizontal sensor axis.
  1205. @param fovy Output field of view in degrees along the vertical sensor axis.
  1206. @param focalLength Focal length of the lens in mm.
  1207. @param principalPoint Principal point in mm.
  1208. @param aspectRatio \f$f_y/f_x\f$
  1209. The function computes various useful camera characteristics from the previously estimated camera
  1210. matrix.
  1211. @note
  1212. Do keep in mind that the unity measure 'mm' stands for whatever unit of measure one chooses for
  1213. the chessboard pitch (it can thus be any value).
  1214. */
  1215. CV_EXPORTS_W void calibrationMatrixValues( InputArray cameraMatrix, Size imageSize,
  1216. double apertureWidth, double apertureHeight,
  1217. CV_OUT double& fovx, CV_OUT double& fovy,
  1218. CV_OUT double& focalLength, CV_OUT Point2d& principalPoint,
  1219. CV_OUT double& aspectRatio );
  1220. /** @brief Calibrates a stereo camera set up. This function finds the intrinsic parameters
  1221. for each of the two cameras and the extrinsic parameters between the two cameras.
  1222. @param objectPoints Vector of vectors of the calibration pattern points. The same structure as
  1223. in @ref calibrateCamera. For each pattern view, both cameras need to see the same object
  1224. points. Therefore, objectPoints.size(), imagePoints1.size(), and imagePoints2.size() need to be
  1225. equal as well as objectPoints[i].size(), imagePoints1[i].size(), and imagePoints2[i].size() need to
  1226. be equal for each i.
  1227. @param imagePoints1 Vector of vectors of the projections of the calibration pattern points,
  1228. observed by the first camera. The same structure as in @ref calibrateCamera.
  1229. @param imagePoints2 Vector of vectors of the projections of the calibration pattern points,
  1230. observed by the second camera. The same structure as in @ref calibrateCamera.
  1231. @param cameraMatrix1 Input/output camera intrinsic matrix for the first camera, the same as in
  1232. @ref calibrateCamera. Furthermore, for the stereo case, additional flags may be used, see below.
  1233. @param distCoeffs1 Input/output vector of distortion coefficients, the same as in
  1234. @ref calibrateCamera.
  1235. @param cameraMatrix2 Input/output second camera intrinsic matrix for the second camera. See description for
  1236. cameraMatrix1.
  1237. @param distCoeffs2 Input/output lens distortion coefficients for the second camera. See
  1238. description for distCoeffs1.
  1239. @param imageSize Size of the image used only to initialize the camera intrinsic matrices.
  1240. @param R Output rotation matrix. Together with the translation vector T, this matrix brings
  1241. points given in the first camera's coordinate system to points in the second camera's
  1242. coordinate system. In more technical terms, the tuple of R and T performs a change of basis
  1243. from the first camera's coordinate system to the second camera's coordinate system. Due to its
  1244. duality, this tuple is equivalent to the position of the first camera with respect to the
  1245. second camera coordinate system.
  1246. @param T Output translation vector, see description above.
  1247. @param E Output essential matrix.
  1248. @param F Output fundamental matrix.
  1249. @param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view.
  1250. @param flags Different flags that may be zero or a combination of the following values:
  1251. - @ref CALIB_FIX_INTRINSIC Fix cameraMatrix? and distCoeffs? so that only R, T, E, and F
  1252. matrices are estimated.
  1253. - @ref CALIB_USE_INTRINSIC_GUESS Optimize some or all of the intrinsic parameters
  1254. according to the specified flags. Initial values are provided by the user.
  1255. - @ref CALIB_USE_EXTRINSIC_GUESS R and T contain valid initial values that are optimized further.
  1256. Otherwise R and T are initialized to the median value of the pattern views (each dimension separately).
  1257. - @ref CALIB_FIX_PRINCIPAL_POINT Fix the principal points during the optimization.
  1258. - @ref CALIB_FIX_FOCAL_LENGTH Fix \f$f^{(j)}_x\f$ and \f$f^{(j)}_y\f$ .
  1259. - @ref CALIB_FIX_ASPECT_RATIO Optimize \f$f^{(j)}_y\f$ . Fix the ratio \f$f^{(j)}_x/f^{(j)}_y\f$
  1260. .
  1261. - @ref CALIB_SAME_FOCAL_LENGTH Enforce \f$f^{(0)}_x=f^{(1)}_x\f$ and \f$f^{(0)}_y=f^{(1)}_y\f$ .
  1262. - @ref CALIB_ZERO_TANGENT_DIST Set tangential distortion coefficients for each camera to
  1263. zeros and fix there.
  1264. - @ref CALIB_FIX_K1,..., @ref CALIB_FIX_K6 Do not change the corresponding radial
  1265. distortion coefficient during the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set,
  1266. the coefficient from the supplied distCoeffs matrix is used. Otherwise, it is set to 0.
  1267. - @ref CALIB_RATIONAL_MODEL Enable coefficients k4, k5, and k6. To provide the backward
  1268. compatibility, this extra flag should be explicitly specified to make the calibration
  1269. function use the rational model and return 8 coefficients. If the flag is not set, the
  1270. function computes and returns only 5 distortion coefficients.
  1271. - @ref CALIB_THIN_PRISM_MODEL Coefficients s1, s2, s3 and s4 are enabled. To provide the
  1272. backward compatibility, this extra flag should be explicitly specified to make the
  1273. calibration function use the thin prism model and return 12 coefficients. If the flag is not
  1274. set, the function computes and returns only 5 distortion coefficients.
  1275. - @ref CALIB_FIX_S1_S2_S3_S4 The thin prism distortion coefficients are not changed during
  1276. the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the
  1277. supplied distCoeffs matrix is used. Otherwise, it is set to 0.
  1278. - @ref CALIB_TILTED_MODEL Coefficients tauX and tauY are enabled. To provide the
  1279. backward compatibility, this extra flag should be explicitly specified to make the
  1280. calibration function use the tilted sensor model and return 14 coefficients. If the flag is not
  1281. set, the function computes and returns only 5 distortion coefficients.
  1282. - @ref CALIB_FIX_TAUX_TAUY The coefficients of the tilted sensor model are not changed during
  1283. the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the
  1284. supplied distCoeffs matrix is used. Otherwise, it is set to 0.
  1285. @param criteria Termination criteria for the iterative optimization algorithm.
  1286. The function estimates the transformation between two cameras making a stereo pair. If one computes
  1287. the poses of an object relative to the first camera and to the second camera,
  1288. ( \f$R_1\f$,\f$T_1\f$ ) and (\f$R_2\f$,\f$T_2\f$), respectively, for a stereo camera where the
  1289. relative position and orientation between the two cameras are fixed, then those poses definitely
  1290. relate to each other. This means, if the relative position and orientation (\f$R\f$,\f$T\f$) of the
  1291. 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
  1292. given. This is what the described function does. It computes (\f$R\f$,\f$T\f$) such that:
  1293. \f[R_2=R R_1\f]
  1294. \f[T_2=R T_1 + T.\f]
  1295. Therefore, one can compute the coordinate representation of a 3D point for the second camera's
  1296. coordinate system when given the point's coordinate representation in the first camera's coordinate
  1297. system:
  1298. \f[\begin{bmatrix}
  1299. X_2 \\
  1300. Y_2 \\
  1301. Z_2 \\
  1302. 1
  1303. \end{bmatrix} = \begin{bmatrix}
  1304. R & T \\
  1305. 0 & 1
  1306. \end{bmatrix} \begin{bmatrix}
  1307. X_1 \\
  1308. Y_1 \\
  1309. Z_1 \\
  1310. 1
  1311. \end{bmatrix}.\f]
  1312. Optionally, it computes the essential matrix E:
  1313. \f[E= \vecthreethree{0}{-T_2}{T_1}{T_2}{0}{-T_0}{-T_1}{T_0}{0} R\f]
  1314. where \f$T_i\f$ are components of the translation vector \f$T\f$ : \f$T=[T_0, T_1, T_2]^T\f$ .
  1315. And the function can also compute the fundamental matrix F:
  1316. \f[F = cameraMatrix2^{-T}\cdot E \cdot cameraMatrix1^{-1}\f]
  1317. Besides the stereo-related information, the function can also perform a full calibration of each of
  1318. the two cameras. However, due to the high dimensionality of the parameter space and noise in the
  1319. input data, the function can diverge from the correct solution. If the intrinsic parameters can be
  1320. estimated with high accuracy for each of the cameras individually (for example, using
  1321. #calibrateCamera ), you are recommended to do so and then pass @ref CALIB_FIX_INTRINSIC flag to the
  1322. function along with the computed intrinsic parameters. Otherwise, if all the parameters are
  1323. estimated at once, it makes sense to restrict some parameters, for example, pass
  1324. @ref CALIB_SAME_FOCAL_LENGTH and @ref CALIB_ZERO_TANGENT_DIST flags, which is usually a
  1325. reasonable assumption.
  1326. Similarly to calibrateCamera, the function minimizes the total re-projection error for all the
  1327. points in all the available views from both cameras. The function returns the final value of the
  1328. re-projection error.
  1329. */
  1330. CV_EXPORTS_AS(stereoCalibrateExtended) double stereoCalibrate( InputArrayOfArrays objectPoints,
  1331. InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2,
  1332. InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1,
  1333. InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2,
  1334. Size imageSize, InputOutputArray R,InputOutputArray T, OutputArray E, OutputArray F,
  1335. OutputArray perViewErrors, int flags = CALIB_FIX_INTRINSIC,
  1336. TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6) );
  1337. /// @overload
  1338. CV_EXPORTS_W double stereoCalibrate( InputArrayOfArrays objectPoints,
  1339. InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2,
  1340. InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1,
  1341. InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2,
  1342. Size imageSize, OutputArray R,OutputArray T, OutputArray E, OutputArray F,
  1343. int flags = CALIB_FIX_INTRINSIC,
  1344. TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6) );
  1345. /** @brief Computes rectification transforms for each head of a calibrated stereo camera.
  1346. @param cameraMatrix1 First camera intrinsic matrix.
  1347. @param distCoeffs1 First camera distortion parameters.
  1348. @param cameraMatrix2 Second camera intrinsic matrix.
  1349. @param distCoeffs2 Second camera distortion parameters.
  1350. @param imageSize Size of the image used for stereo calibration.
  1351. @param R Rotation matrix from the coordinate system of the first camera to the second camera,
  1352. see @ref stereoCalibrate.
  1353. @param T Translation vector from the coordinate system of the first camera to the second camera,
  1354. see @ref stereoCalibrate.
  1355. @param R1 Output 3x3 rectification transform (rotation matrix) for the first camera. This matrix
  1356. brings points given in the unrectified first camera's coordinate system to points in the rectified
  1357. first camera's coordinate system. In more technical terms, it performs a change of basis from the
  1358. unrectified first camera's coordinate system to the rectified first camera's coordinate system.
  1359. @param R2 Output 3x3 rectification transform (rotation matrix) for the second camera. This matrix
  1360. brings points given in the unrectified second camera's coordinate system to points in the rectified
  1361. second camera's coordinate system. In more technical terms, it performs a change of basis from the
  1362. unrectified second camera's coordinate system to the rectified second camera's coordinate system.
  1363. @param P1 Output 3x4 projection matrix in the new (rectified) coordinate systems for the first
  1364. camera, i.e. it projects points given in the rectified first camera coordinate system into the
  1365. rectified first camera's image.
  1366. @param P2 Output 3x4 projection matrix in the new (rectified) coordinate systems for the second
  1367. camera, i.e. it projects points given in the rectified first camera coordinate system into the
  1368. rectified second camera's image.
  1369. @param Q Output \f$4 \times 4\f$ disparity-to-depth mapping matrix (see @ref reprojectImageTo3D).
  1370. @param flags Operation flags that may be zero or @ref CALIB_ZERO_DISPARITY . If the flag is set,
  1371. the function makes the principal points of each camera have the same pixel coordinates in the
  1372. rectified views. And if the flag is not set, the function may still shift the images in the
  1373. horizontal or vertical direction (depending on the orientation of epipolar lines) to maximize the
  1374. useful image area.
  1375. @param alpha Free scaling parameter. If it is -1 or absent, the function performs the default
  1376. scaling. Otherwise, the parameter should be between 0 and 1. alpha=0 means that the rectified
  1377. images are zoomed and shifted so that only valid pixels are visible (no black areas after
  1378. rectification). alpha=1 means that the rectified image is decimated and shifted so that all the
  1379. pixels from the original images from the cameras are retained in the rectified images (no source
  1380. image pixels are lost). Any intermediate value yields an intermediate result between
  1381. those two extreme cases.
  1382. @param newImageSize New image resolution after rectification. The same size should be passed to
  1383. #initUndistortRectifyMap (see the stereo_calib.cpp sample in OpenCV samples directory). When (0,0)
  1384. is passed (default), it is set to the original imageSize . Setting it to a larger value can help you
  1385. preserve details in the original image, especially when there is a big radial distortion.
  1386. @param validPixROI1 Optional output rectangles inside the rectified images where all the pixels
  1387. are valid. If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller
  1388. (see the picture below).
  1389. @param validPixROI2 Optional output rectangles inside the rectified images where all the pixels
  1390. are valid. If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller
  1391. (see the picture below).
  1392. The function computes the rotation matrices for each camera that (virtually) make both camera image
  1393. planes the same plane. Consequently, this makes all the epipolar lines parallel and thus simplifies
  1394. the dense stereo correspondence problem. The function takes the matrices computed by #stereoCalibrate
  1395. as input. As output, it provides two rotation matrices and also two projection matrices in the new
  1396. coordinates. The function distinguishes the following two cases:
  1397. - **Horizontal stereo**: the first and the second camera views are shifted relative to each other
  1398. mainly along the x-axis (with possible small vertical shift). In the rectified images, the
  1399. corresponding epipolar lines in the left and right cameras are horizontal and have the same
  1400. y-coordinate. P1 and P2 look like:
  1401. \f[\texttt{P1} = \begin{bmatrix}
  1402. f & 0 & cx_1 & 0 \\
  1403. 0 & f & cy & 0 \\
  1404. 0 & 0 & 1 & 0
  1405. \end{bmatrix}\f]
  1406. \f[\texttt{P2} = \begin{bmatrix}
  1407. f & 0 & cx_2 & T_x \cdot f \\
  1408. 0 & f & cy & 0 \\
  1409. 0 & 0 & 1 & 0
  1410. \end{bmatrix} ,\f]
  1411. \f[\texttt{Q} = \begin{bmatrix}
  1412. 1 & 0 & 0 & -cx_1 \\
  1413. 0 & 1 & 0 & -cy \\
  1414. 0 & 0 & 0 & f \\
  1415. 0 & 0 & -\frac{1}{T_x} & \frac{cx_1 - cx_2}{T_x}
  1416. \end{bmatrix} \f]
  1417. where \f$T_x\f$ is a horizontal shift between the cameras and \f$cx_1=cx_2\f$ if
  1418. @ref CALIB_ZERO_DISPARITY is set.
  1419. - **Vertical stereo**: the first and the second camera views are shifted relative to each other
  1420. mainly in the vertical direction (and probably a bit in the horizontal direction too). The epipolar
  1421. lines in the rectified images are vertical and have the same x-coordinate. P1 and P2 look like:
  1422. \f[\texttt{P1} = \begin{bmatrix}
  1423. f & 0 & cx & 0 \\
  1424. 0 & f & cy_1 & 0 \\
  1425. 0 & 0 & 1 & 0
  1426. \end{bmatrix}\f]
  1427. \f[\texttt{P2} = \begin{bmatrix}
  1428. f & 0 & cx & 0 \\
  1429. 0 & f & cy_2 & T_y \cdot f \\
  1430. 0 & 0 & 1 & 0
  1431. \end{bmatrix},\f]
  1432. \f[\texttt{Q} = \begin{bmatrix}
  1433. 1 & 0 & 0 & -cx \\
  1434. 0 & 1 & 0 & -cy_1 \\
  1435. 0 & 0 & 0 & f \\
  1436. 0 & 0 & -\frac{1}{T_y} & \frac{cy_1 - cy_2}{T_y}
  1437. \end{bmatrix} \f]
  1438. where \f$T_y\f$ is a vertical shift between the cameras and \f$cy_1=cy_2\f$ if
  1439. @ref CALIB_ZERO_DISPARITY is set.
  1440. As you can see, the first three columns of P1 and P2 will effectively be the new "rectified" camera
  1441. matrices. The matrices, together with R1 and R2 , can then be passed to #initUndistortRectifyMap to
  1442. initialize the rectification map for each camera.
  1443. See below the screenshot from the stereo_calib.cpp sample. Some red horizontal lines pass through
  1444. the corresponding image regions. This means that the images are well rectified, which is what most
  1445. stereo correspondence algorithms rely on. The green rectangles are roi1 and roi2 . You see that
  1446. their interiors are all valid pixels.
  1447. ![image](pics/stereo_undistort.jpg)
  1448. */
  1449. CV_EXPORTS_W void stereoRectify( InputArray cameraMatrix1, InputArray distCoeffs1,
  1450. InputArray cameraMatrix2, InputArray distCoeffs2,
  1451. Size imageSize, InputArray R, InputArray T,
  1452. OutputArray R1, OutputArray R2,
  1453. OutputArray P1, OutputArray P2,
  1454. OutputArray Q, int flags = CALIB_ZERO_DISPARITY,
  1455. double alpha = -1, Size newImageSize = Size(),
  1456. CV_OUT Rect* validPixROI1 = 0, CV_OUT Rect* validPixROI2 = 0 );
  1457. /** @brief Computes a rectification transform for an uncalibrated stereo camera.
  1458. @param points1 Array of feature points in the first image.
  1459. @param points2 The corresponding points in the second image. The same formats as in
  1460. #findFundamentalMat are supported.
  1461. @param F Input fundamental matrix. It can be computed from the same set of point pairs using
  1462. #findFundamentalMat .
  1463. @param imgSize Size of the image.
  1464. @param H1 Output rectification homography matrix for the first image.
  1465. @param H2 Output rectification homography matrix for the second image.
  1466. @param threshold Optional threshold used to filter out the outliers. If the parameter is greater
  1467. than zero, all the point pairs that do not comply with the epipolar geometry (that is, the points
  1468. for which \f$|\texttt{points2[i]}^T \cdot \texttt{F} \cdot \texttt{points1[i]}|>\texttt{threshold}\f$ )
  1469. are rejected prior to computing the homographies. Otherwise, all the points are considered inliers.
  1470. The function computes the rectification transformations without knowing intrinsic parameters of the
  1471. cameras and their relative position in the space, which explains the suffix "uncalibrated". Another
  1472. related difference from #stereoRectify is that the function outputs not the rectification
  1473. transformations in the object (3D) space, but the planar perspective transformations encoded by the
  1474. homography matrices H1 and H2 . The function implements the algorithm @cite Hartley99 .
  1475. @note
  1476. While the algorithm does not need to know the intrinsic parameters of the cameras, it heavily
  1477. depends on the epipolar geometry. Therefore, if the camera lenses have a significant distortion,
  1478. it would be better to correct it before computing the fundamental matrix and calling this
  1479. function. For example, distortion coefficients can be estimated for each head of stereo camera
  1480. separately by using #calibrateCamera . Then, the images can be corrected using #undistort , or
  1481. just the point coordinates can be corrected with #undistortPoints .
  1482. */
  1483. CV_EXPORTS_W bool stereoRectifyUncalibrated( InputArray points1, InputArray points2,
  1484. InputArray F, Size imgSize,
  1485. OutputArray H1, OutputArray H2,
  1486. double threshold = 5 );
  1487. //! computes the rectification transformations for 3-head camera, where all the heads are on the same line.
  1488. CV_EXPORTS_W float rectify3Collinear( InputArray cameraMatrix1, InputArray distCoeffs1,
  1489. InputArray cameraMatrix2, InputArray distCoeffs2,
  1490. InputArray cameraMatrix3, InputArray distCoeffs3,
  1491. InputArrayOfArrays imgpt1, InputArrayOfArrays imgpt3,
  1492. Size imageSize, InputArray R12, InputArray T12,
  1493. InputArray R13, InputArray T13,
  1494. OutputArray R1, OutputArray R2, OutputArray R3,
  1495. OutputArray P1, OutputArray P2, OutputArray P3,
  1496. OutputArray Q, double alpha, Size newImgSize,
  1497. CV_OUT Rect* roi1, CV_OUT Rect* roi2, int flags );
  1498. /** @brief Returns the new camera intrinsic matrix based on the free scaling parameter.
  1499. @param cameraMatrix Input camera intrinsic matrix.
  1500. @param distCoeffs Input vector of distortion coefficients
  1501. \f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are
  1502. assumed.
  1503. @param imageSize Original image size.
  1504. @param alpha Free scaling parameter between 0 (when all the pixels in the undistorted image are
  1505. valid) and 1 (when all the source image pixels are retained in the undistorted image). See
  1506. #stereoRectify for details.
  1507. @param newImgSize Image size after rectification. By default, it is set to imageSize .
  1508. @param validPixROI Optional output rectangle that outlines all-good-pixels region in the
  1509. undistorted image. See roi1, roi2 description in #stereoRectify .
  1510. @param centerPrincipalPoint Optional flag that indicates whether in the new camera intrinsic matrix the
  1511. principal point should be at the image center or not. By default, the principal point is chosen to
  1512. best fit a subset of the source image (determined by alpha) to the corrected image.
  1513. @return new_camera_matrix Output new camera intrinsic matrix.
  1514. The function computes and returns the optimal new camera intrinsic matrix based on the free scaling parameter.
  1515. By varying this parameter, you may retrieve only sensible pixels alpha=0 , keep all the original
  1516. image pixels if there is valuable information in the corners alpha=1 , or get something in between.
  1517. When alpha\>0 , the undistorted result is likely to have some black pixels corresponding to
  1518. "virtual" pixels outside of the captured distorted image. The original camera intrinsic matrix, distortion
  1519. coefficients, the computed new camera intrinsic matrix, and newImageSize should be passed to
  1520. #initUndistortRectifyMap to produce the maps for #remap .
  1521. */
  1522. CV_EXPORTS_W Mat getOptimalNewCameraMatrix( InputArray cameraMatrix, InputArray distCoeffs,
  1523. Size imageSize, double alpha, Size newImgSize = Size(),
  1524. CV_OUT Rect* validPixROI = 0,
  1525. bool centerPrincipalPoint = false);
  1526. /** @brief Computes Hand-Eye calibration: \f$_{}^{g}\textrm{T}_c\f$
  1527. @param[in] R_gripper2base Rotation part extracted from the homogeneous matrix that transforms a point
  1528. expressed in the gripper frame to the robot base frame (\f$_{}^{b}\textrm{T}_g\f$).
  1529. This is a vector (`vector<Mat>`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors,
  1530. for all the transformations from gripper frame to robot base frame.
  1531. @param[in] t_gripper2base Translation part extracted from the homogeneous matrix that transforms a point
  1532. expressed in the gripper frame to the robot base frame (\f$_{}^{b}\textrm{T}_g\f$).
  1533. This is a vector (`vector<Mat>`) that contains the `(3x1)` translation vectors for all the transformations
  1534. from gripper frame to robot base frame.
  1535. @param[in] R_target2cam Rotation part extracted from the homogeneous matrix that transforms a point
  1536. expressed in the target frame to the camera frame (\f$_{}^{c}\textrm{T}_t\f$).
  1537. This is a vector (`vector<Mat>`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors,
  1538. for all the transformations from calibration target frame to camera frame.
  1539. @param[in] t_target2cam Rotation part extracted from the homogeneous matrix that transforms a point
  1540. expressed in the target frame to the camera frame (\f$_{}^{c}\textrm{T}_t\f$).
  1541. This is a vector (`vector<Mat>`) that contains the `(3x1)` translation vectors for all the transformations
  1542. from calibration target frame to camera frame.
  1543. @param[out] R_cam2gripper Estimated `(3x3)` rotation part extracted from the homogeneous matrix that transforms a point
  1544. expressed in the camera frame to the gripper frame (\f$_{}^{g}\textrm{T}_c\f$).
  1545. @param[out] t_cam2gripper Estimated `(3x1)` translation part extracted from the homogeneous matrix that transforms a point
  1546. expressed in the camera frame to the gripper frame (\f$_{}^{g}\textrm{T}_c\f$).
  1547. @param[in] method One of the implemented Hand-Eye calibration method, see cv::HandEyeCalibrationMethod
  1548. The function performs the Hand-Eye calibration using various methods. One approach consists in estimating the
  1549. rotation then the translation (separable solutions) and the following methods are implemented:
  1550. - R. Tsai, R. Lenz A New Technique for Fully Autonomous and Efficient 3D Robotics Hand/EyeCalibration \cite Tsai89
  1551. - F. Park, B. Martin Robot Sensor Calibration: Solving AX = XB on the Euclidean Group \cite Park94
  1552. - R. Horaud, F. Dornaika Hand-Eye Calibration \cite Horaud95
  1553. Another approach consists in estimating simultaneously the rotation and the translation (simultaneous solutions),
  1554. with the following implemented method:
  1555. - N. Andreff, R. Horaud, B. Espiau On-line Hand-Eye Calibration \cite Andreff99
  1556. - K. Daniilidis Hand-Eye Calibration Using Dual Quaternions \cite Daniilidis98
  1557. The following picture describes the Hand-Eye calibration problem where the transformation between a camera ("eye")
  1558. mounted on a robot gripper ("hand") has to be estimated.
  1559. ![](pics/hand-eye_figure.png)
  1560. The calibration procedure is the following:
  1561. - a static calibration pattern is used to estimate the transformation between the target frame
  1562. and the camera frame
  1563. - the robot gripper is moved in order to acquire several poses
  1564. - for each pose, the homogeneous transformation between the gripper frame and the robot base frame is recorded using for
  1565. instance the robot kinematics
  1566. \f[
  1567. \begin{bmatrix}
  1568. X_b\\
  1569. Y_b\\
  1570. Z_b\\
  1571. 1
  1572. \end{bmatrix}
  1573. =
  1574. \begin{bmatrix}
  1575. _{}^{b}\textrm{R}_g & _{}^{b}\textrm{t}_g \\
  1576. 0_{1 \times 3} & 1
  1577. \end{bmatrix}
  1578. \begin{bmatrix}
  1579. X_g\\
  1580. Y_g\\
  1581. Z_g\\
  1582. 1
  1583. \end{bmatrix}
  1584. \f]
  1585. - for each pose, the homogeneous transformation between the calibration target frame and the camera frame is recorded using
  1586. for instance a pose estimation method (PnP) from 2D-3D point correspondences
  1587. \f[
  1588. \begin{bmatrix}
  1589. X_c\\
  1590. Y_c\\
  1591. Z_c\\
  1592. 1
  1593. \end{bmatrix}
  1594. =
  1595. \begin{bmatrix}
  1596. _{}^{c}\textrm{R}_t & _{}^{c}\textrm{t}_t \\
  1597. 0_{1 \times 3} & 1
  1598. \end{bmatrix}
  1599. \begin{bmatrix}
  1600. X_t\\
  1601. Y_t\\
  1602. Z_t\\
  1603. 1
  1604. \end{bmatrix}
  1605. \f]
  1606. The Hand-Eye calibration procedure returns the following homogeneous transformation
  1607. \f[
  1608. \begin{bmatrix}
  1609. X_g\\
  1610. Y_g\\
  1611. Z_g\\
  1612. 1
  1613. \end{bmatrix}
  1614. =
  1615. \begin{bmatrix}
  1616. _{}^{g}\textrm{R}_c & _{}^{g}\textrm{t}_c \\
  1617. 0_{1 \times 3} & 1
  1618. \end{bmatrix}
  1619. \begin{bmatrix}
  1620. X_c\\
  1621. Y_c\\
  1622. Z_c\\
  1623. 1
  1624. \end{bmatrix}
  1625. \f]
  1626. This problem is also known as solving the \f$\mathbf{A}\mathbf{X}=\mathbf{X}\mathbf{B}\f$ equation:
  1627. \f[
  1628. \begin{align*}
  1629. ^{b}{\textrm{T}_g}^{(1)} \hspace{0.2em} ^{g}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(1)} &=
  1630. \hspace{0.1em} ^{b}{\textrm{T}_g}^{(2)} \hspace{0.2em} ^{g}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} \\
  1631. (^{b}{\textrm{T}_g}^{(2)})^{-1} \hspace{0.2em} ^{b}{\textrm{T}_g}^{(1)} \hspace{0.2em} ^{g}\textrm{T}_c &=
  1632. \hspace{0.1em} ^{g}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} (^{c}{\textrm{T}_t}^{(1)})^{-1} \\
  1633. \textrm{A}_i \textrm{X} &= \textrm{X} \textrm{B}_i \\
  1634. \end{align*}
  1635. \f]
  1636. \note
  1637. Additional information can be found on this [website](http://campar.in.tum.de/Chair/HandEyeCalibration).
  1638. \note
  1639. A minimum of 2 motions with non parallel rotation axes are necessary to determine the hand-eye transformation.
  1640. So at least 3 different poses are required, but it is strongly recommended to use many more poses.
  1641. */
  1642. CV_EXPORTS_W void calibrateHandEye( InputArrayOfArrays R_gripper2base, InputArrayOfArrays t_gripper2base,
  1643. InputArrayOfArrays R_target2cam, InputArrayOfArrays t_target2cam,
  1644. OutputArray R_cam2gripper, OutputArray t_cam2gripper,
  1645. HandEyeCalibrationMethod method=CALIB_HAND_EYE_TSAI );
  1646. /** @brief Converts points from Euclidean to homogeneous space.
  1647. @param src Input vector of N-dimensional points.
  1648. @param dst Output vector of N+1-dimensional points.
  1649. The function converts points from Euclidean to homogeneous space by appending 1's to the tuple of
  1650. point coordinates. That is, each point (x1, x2, ..., xn) is converted to (x1, x2, ..., xn, 1).
  1651. */
  1652. CV_EXPORTS_W void convertPointsToHomogeneous( InputArray src, OutputArray dst );
  1653. /** @brief Converts points from homogeneous to Euclidean space.
  1654. @param src Input vector of N-dimensional points.
  1655. @param dst Output vector of N-1-dimensional points.
  1656. The function converts points homogeneous to Euclidean space using perspective projection. That is,
  1657. each point (x1, x2, ... x(n-1), xn) is converted to (x1/xn, x2/xn, ..., x(n-1)/xn). When xn=0, the
  1658. output point coordinates will be (0,0,0,...).
  1659. */
  1660. CV_EXPORTS_W void convertPointsFromHomogeneous( InputArray src, OutputArray dst );
  1661. /** @brief Converts points to/from homogeneous coordinates.
  1662. @param src Input array or vector of 2D, 3D, or 4D points.
  1663. @param dst Output vector of 2D, 3D, or 4D points.
  1664. The function converts 2D or 3D points from/to homogeneous coordinates by calling either
  1665. #convertPointsToHomogeneous or #convertPointsFromHomogeneous.
  1666. @note The function is obsolete. Use one of the previous two functions instead.
  1667. */
  1668. CV_EXPORTS void convertPointsHomogeneous( InputArray src, OutputArray dst );
  1669. /** @brief Calculates a fundamental matrix from the corresponding points in two images.
  1670. @param points1 Array of N points from the first image. The point coordinates should be
  1671. floating-point (single or double precision).
  1672. @param points2 Array of the second image points of the same size and format as points1 .
  1673. @param method Method for computing a fundamental matrix.
  1674. - @ref FM_7POINT for a 7-point algorithm. \f$N = 7\f$
  1675. - @ref FM_8POINT for an 8-point algorithm. \f$N \ge 8\f$
  1676. - @ref FM_RANSAC for the RANSAC algorithm. \f$N \ge 8\f$
  1677. - @ref FM_LMEDS for the LMedS algorithm. \f$N \ge 8\f$
  1678. @param ransacReprojThreshold Parameter used only for RANSAC. It is the maximum distance from a point to an epipolar
  1679. line in pixels, beyond which the point is considered an outlier and is not used for computing the
  1680. final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the
  1681. point localization, image resolution, and the image noise.
  1682. @param confidence Parameter used for the RANSAC and LMedS methods only. It specifies a desirable level
  1683. of confidence (probability) that the estimated matrix is correct.
  1684. @param[out] mask optional output mask
  1685. @param maxIters The maximum number of robust method iterations.
  1686. The epipolar geometry is described by the following equation:
  1687. \f[[p_2; 1]^T F [p_1; 1] = 0\f]
  1688. 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
  1689. second images, respectively.
  1690. The function calculates the fundamental matrix using one of four methods listed above and returns
  1691. the found fundamental matrix. Normally just one matrix is found. But in case of the 7-point
  1692. algorithm, the function may return up to 3 solutions ( \f$9 \times 3\f$ matrix that stores all 3
  1693. matrices sequentially).
  1694. The calculated fundamental matrix may be passed further to #computeCorrespondEpilines that finds the
  1695. epipolar lines corresponding to the specified points. It can also be passed to
  1696. #stereoRectifyUncalibrated to compute the rectification transformation. :
  1697. @code
  1698. // Example. Estimation of fundamental matrix using the RANSAC algorithm
  1699. int point_count = 100;
  1700. vector<Point2f> points1(point_count);
  1701. vector<Point2f> points2(point_count);
  1702. // initialize the points here ...
  1703. for( int i = 0; i < point_count; i++ )
  1704. {
  1705. points1[i] = ...;
  1706. points2[i] = ...;
  1707. }
  1708. Mat fundamental_matrix =
  1709. findFundamentalMat(points1, points2, FM_RANSAC, 3, 0.99);
  1710. @endcode
  1711. */
  1712. CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2,
  1713. int method, double ransacReprojThreshold, double confidence,
  1714. int maxIters, OutputArray mask = noArray() );
  1715. /** @overload */
  1716. CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2,
  1717. int method = FM_RANSAC,
  1718. double ransacReprojThreshold = 3., double confidence = 0.99,
  1719. OutputArray mask = noArray() );
  1720. /** @overload */
  1721. CV_EXPORTS Mat findFundamentalMat( InputArray points1, InputArray points2,
  1722. OutputArray mask, int method = FM_RANSAC,
  1723. double ransacReprojThreshold = 3., double confidence = 0.99 );
  1724. /** @brief Calculates an essential matrix from the corresponding points in two images.
  1725. @param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should
  1726. be floating-point (single or double precision).
  1727. @param points2 Array of the second image points of the same size and format as points1 .
  1728. @param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ .
  1729. Note that this function assumes that points1 and points2 are feature points from cameras with the
  1730. same camera intrinsic matrix. If this assumption does not hold for your use case, use
  1731. `undistortPoints()` with `P = cv::NoArray()` for both cameras to transform image points
  1732. to normalized image coordinates, which are valid for the identity camera intrinsic matrix. When
  1733. passing these coordinates, pass the identity matrix for this parameter.
  1734. @param method Method for computing an essential matrix.
  1735. - @ref RANSAC for the RANSAC algorithm.
  1736. - @ref LMEDS for the LMedS algorithm.
  1737. @param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of
  1738. confidence (probability) that the estimated matrix is correct.
  1739. @param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar
  1740. line in pixels, beyond which the point is considered an outlier and is not used for computing the
  1741. final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the
  1742. point localization, image resolution, and the image noise.
  1743. @param mask Output array of N elements, every element of which is set to 0 for outliers and to 1
  1744. for the other points. The array is computed only in the RANSAC and LMedS methods.
  1745. @param maxIters The maximum number of robust method iterations.
  1746. This function estimates essential matrix based on the five-point algorithm solver in @cite Nister03 .
  1747. @cite SteweniusCFS is also a related. The epipolar geometry is described by the following equation:
  1748. \f[[p_2; 1]^T K^{-T} E K^{-1} [p_1; 1] = 0\f]
  1749. 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
  1750. second images, respectively. The result of this function may be passed further to
  1751. #decomposeEssentialMat or #recoverPose to recover the relative pose between cameras.
  1752. */
  1753. CV_EXPORTS_W Mat findEssentialMat( InputArray points1, InputArray points2,
  1754. InputArray cameraMatrix, int method,
  1755. double prob, double threshold,
  1756. int maxIters, OutputArray mask = noArray() );
  1757. /** @overload */
  1758. CV_EXPORTS_W Mat findEssentialMat( InputArray points1, InputArray points2,
  1759. InputArray cameraMatrix, int method = RANSAC,
  1760. double prob = 0.999, double threshold = 1.0,
  1761. OutputArray mask = noArray() );
  1762. /** @overload
  1763. @param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should
  1764. be floating-point (single or double precision).
  1765. @param points2 Array of the second image points of the same size and format as points1 .
  1766. @param focal focal length of the camera. Note that this function assumes that points1 and points2
  1767. are feature points from cameras with same focal length and principal point.
  1768. @param pp principal point of the camera.
  1769. @param method Method for computing a fundamental matrix.
  1770. - @ref RANSAC for the RANSAC algorithm.
  1771. - @ref LMEDS for the LMedS algorithm.
  1772. @param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar
  1773. line in pixels, beyond which the point is considered an outlier and is not used for computing the
  1774. final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the
  1775. point localization, image resolution, and the image noise.
  1776. @param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of
  1777. confidence (probability) that the estimated matrix is correct.
  1778. @param mask Output array of N elements, every element of which is set to 0 for outliers and to 1
  1779. for the other points. The array is computed only in the RANSAC and LMedS methods.
  1780. @param maxIters The maximum number of robust method iterations.
  1781. This function differs from the one above that it computes camera intrinsic matrix from focal length and
  1782. principal point:
  1783. \f[A =
  1784. \begin{bmatrix}
  1785. f & 0 & x_{pp} \\
  1786. 0 & f & y_{pp} \\
  1787. 0 & 0 & 1
  1788. \end{bmatrix}\f]
  1789. */
  1790. CV_EXPORTS_W Mat findEssentialMat( InputArray points1, InputArray points2,
  1791. double focal, Point2d pp,
  1792. int method, double prob,
  1793. double threshold, int maxIters,
  1794. OutputArray mask = noArray() );
  1795. /** @overload */
  1796. CV_EXPORTS_W Mat findEssentialMat( InputArray points1, InputArray points2,
  1797. double focal = 1.0, Point2d pp = Point2d(0, 0),
  1798. int method = RANSAC, double prob = 0.999,
  1799. double threshold = 1.0, OutputArray mask = noArray() );
  1800. /** @brief Decompose an essential matrix to possible rotations and translation.
  1801. @param E The input essential matrix.
  1802. @param R1 One possible rotation matrix.
  1803. @param R2 Another possible rotation matrix.
  1804. @param t One possible translation.
  1805. This function decomposes the essential matrix E using svd decomposition @cite HartleyZ00. In
  1806. general, four possible poses exist for the decomposition of E. They are \f$[R_1, t]\f$,
  1807. \f$[R_1, -t]\f$, \f$[R_2, t]\f$, \f$[R_2, -t]\f$.
  1808. If E gives the epipolar constraint \f$[p_2; 1]^T A^{-T} E A^{-1} [p_1; 1] = 0\f$ between the image
  1809. points \f$p_1\f$ in the first image and \f$p_2\f$ in second image, then any of the tuples
  1810. \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
  1811. camera's coordinate system to the second camera's coordinate system. However, by decomposing E, one
  1812. can only get the direction of the translation. For this reason, the translation t is returned with
  1813. unit length.
  1814. */
  1815. CV_EXPORTS_W void decomposeEssentialMat( InputArray E, OutputArray R1, OutputArray R2, OutputArray t );
  1816. /** @brief Recovers the relative camera rotation and the translation from an estimated essential
  1817. matrix and the corresponding points in two images, using chirality check. Returns the number of
  1818. inliers that pass the check.
  1819. @param E The input essential matrix.
  1820. @param points1 Array of N 2D points from the first image. The point coordinates should be
  1821. floating-point (single or double precision).
  1822. @param points2 Array of the second image points of the same size and format as points1 .
  1823. @param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ .
  1824. Note that this function assumes that points1 and points2 are feature points from cameras with the
  1825. same camera intrinsic matrix.
  1826. @param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple
  1827. that performs a change of basis from the first camera's coordinate system to the second camera's
  1828. coordinate system. Note that, in general, t can not be used for this tuple, see the parameter
  1829. described below.
  1830. @param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and
  1831. therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit
  1832. length.
  1833. @param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks
  1834. inliers in points1 and points2 for the given essential matrix E. Only these inliers will be used to
  1835. recover pose. In the output mask only inliers which pass the chirality check.
  1836. This function decomposes an essential matrix using @ref decomposeEssentialMat and then verifies
  1837. possible pose hypotheses by doing chirality check. The chirality check means that the
  1838. triangulated 3D points should have positive depth. Some details can be found in @cite Nister03.
  1839. This function can be used to process the output E and mask from @ref findEssentialMat. In this
  1840. scenario, points1 and points2 are the same input for findEssentialMat.:
  1841. @code
  1842. // Example. Estimation of fundamental matrix using the RANSAC algorithm
  1843. int point_count = 100;
  1844. vector<Point2f> points1(point_count);
  1845. vector<Point2f> points2(point_count);
  1846. // initialize the points here ...
  1847. for( int i = 0; i < point_count; i++ )
  1848. {
  1849. points1[i] = ...;
  1850. points2[i] = ...;
  1851. }
  1852. // cametra matrix with both focal lengths = 1, and principal point = (0, 0)
  1853. Mat cameraMatrix = Mat::eye(3, 3, CV_64F);
  1854. Mat E, R, t, mask;
  1855. E = findEssentialMat(points1, points2, cameraMatrix, RANSAC, 0.999, 1.0, mask);
  1856. recoverPose(E, points1, points2, cameraMatrix, R, t, mask);
  1857. @endcode
  1858. */
  1859. CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2,
  1860. InputArray cameraMatrix, OutputArray R, OutputArray t,
  1861. InputOutputArray mask = noArray() );
  1862. /** @overload
  1863. @param E The input essential matrix.
  1864. @param points1 Array of N 2D points from the first image. The point coordinates should be
  1865. floating-point (single or double precision).
  1866. @param points2 Array of the second image points of the same size and format as points1 .
  1867. @param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple
  1868. that performs a change of basis from the first camera's coordinate system to the second camera's
  1869. coordinate system. Note that, in general, t can not be used for this tuple, see the parameter
  1870. description below.
  1871. @param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and
  1872. therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit
  1873. length.
  1874. @param focal Focal length of the camera. Note that this function assumes that points1 and points2
  1875. are feature points from cameras with same focal length and principal point.
  1876. @param pp principal point of the camera.
  1877. @param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks
  1878. inliers in points1 and points2 for the given essential matrix E. Only these inliers will be used to
  1879. recover pose. In the output mask only inliers which pass the chirality check.
  1880. This function differs from the one above that it computes camera intrinsic matrix from focal length and
  1881. principal point:
  1882. \f[A =
  1883. \begin{bmatrix}
  1884. f & 0 & x_{pp} \\
  1885. 0 & f & y_{pp} \\
  1886. 0 & 0 & 1
  1887. \end{bmatrix}\f]
  1888. */
  1889. CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2,
  1890. OutputArray R, OutputArray t,
  1891. double focal = 1.0, Point2d pp = Point2d(0, 0),
  1892. InputOutputArray mask = noArray() );
  1893. /** @overload
  1894. @param E The input essential matrix.
  1895. @param points1 Array of N 2D points from the first image. The point coordinates should be
  1896. floating-point (single or double precision).
  1897. @param points2 Array of the second image points of the same size and format as points1.
  1898. @param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ .
  1899. Note that this function assumes that points1 and points2 are feature points from cameras with the
  1900. same camera intrinsic matrix.
  1901. @param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple
  1902. that performs a change of basis from the first camera's coordinate system to the second camera's
  1903. coordinate system. Note that, in general, t can not be used for this tuple, see the parameter
  1904. description below.
  1905. @param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and
  1906. therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit
  1907. length.
  1908. @param distanceThresh threshold distance which is used to filter out far away points (i.e. infinite
  1909. points).
  1910. @param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks
  1911. inliers in points1 and points2 for the given essential matrix E. Only these inliers will be used to
  1912. recover pose. In the output mask only inliers which pass the chirality check.
  1913. @param triangulatedPoints 3D points which were reconstructed by triangulation.
  1914. This function differs from the one above that it outputs the triangulated 3D point that are used for
  1915. the chirality check.
  1916. */
  1917. CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2,
  1918. InputArray cameraMatrix, OutputArray R, OutputArray t, double distanceThresh, InputOutputArray mask = noArray(),
  1919. OutputArray triangulatedPoints = noArray());
  1920. /** @brief For points in an image of a stereo pair, computes the corresponding epilines in the other image.
  1921. @param points Input points. \f$N \times 1\f$ or \f$1 \times N\f$ matrix of type CV_32FC2 or
  1922. vector\<Point2f\> .
  1923. @param whichImage Index of the image (1 or 2) that contains the points .
  1924. @param F Fundamental matrix that can be estimated using #findFundamentalMat or #stereoRectify .
  1925. @param lines Output vector of the epipolar lines corresponding to the points in the other image.
  1926. Each line \f$ax + by + c=0\f$ is encoded by 3 numbers \f$(a, b, c)\f$ .
  1927. For every point in one of the two images of a stereo pair, the function finds the equation of the
  1928. corresponding epipolar line in the other image.
  1929. From the fundamental matrix definition (see #findFundamentalMat ), line \f$l^{(2)}_i\f$ in the second
  1930. image for the point \f$p^{(1)}_i\f$ in the first image (when whichImage=1 ) is computed as:
  1931. \f[l^{(2)}_i = F p^{(1)}_i\f]
  1932. And vice versa, when whichImage=2, \f$l^{(1)}_i\f$ is computed from \f$p^{(2)}_i\f$ as:
  1933. \f[l^{(1)}_i = F^T p^{(2)}_i\f]
  1934. Line coefficients are defined up to a scale. They are normalized so that \f$a_i^2+b_i^2=1\f$ .
  1935. */
  1936. CV_EXPORTS_W void computeCorrespondEpilines( InputArray points, int whichImage,
  1937. InputArray F, OutputArray lines );
  1938. /** @brief This function reconstructs 3-dimensional points (in homogeneous coordinates) by using
  1939. their observations with a stereo camera.
  1940. @param projMatr1 3x4 projection matrix of the first camera, i.e. this matrix projects 3D points
  1941. given in the world's coordinate system into the first image.
  1942. @param projMatr2 3x4 projection matrix of the second camera, i.e. this matrix projects 3D points
  1943. given in the world's coordinate system into the second image.
  1944. @param projPoints1 2xN array of feature points in the first image. In the case of the c++ version,
  1945. it can be also a vector of feature points or two-channel matrix of size 1xN or Nx1.
  1946. @param projPoints2 2xN array of corresponding points in the second image. In the case of the c++
  1947. version, it can be also a vector of feature points or two-channel matrix of size 1xN or Nx1.
  1948. @param points4D 4xN array of reconstructed points in homogeneous coordinates. These points are
  1949. returned in the world's coordinate system.
  1950. @note
  1951. Keep in mind that all input data should be of float type in order for this function to work.
  1952. @note
  1953. If the projection matrices from @ref stereoRectify are used, then the returned points are
  1954. represented in the first camera's rectified coordinate system.
  1955. @sa
  1956. reprojectImageTo3D
  1957. */
  1958. CV_EXPORTS_W void triangulatePoints( InputArray projMatr1, InputArray projMatr2,
  1959. InputArray projPoints1, InputArray projPoints2,
  1960. OutputArray points4D );
  1961. /** @brief Refines coordinates of corresponding points.
  1962. @param F 3x3 fundamental matrix.
  1963. @param points1 1xN array containing the first set of points.
  1964. @param points2 1xN array containing the second set of points.
  1965. @param newPoints1 The optimized points1.
  1966. @param newPoints2 The optimized points2.
  1967. The function implements the Optimal Triangulation Method (see Multiple View Geometry @cite HartleyZ00 for details).
  1968. For each given point correspondence points1[i] \<-\> points2[i], and a fundamental matrix F, it
  1969. computes the corrected correspondences newPoints1[i] \<-\> newPoints2[i] that minimize the geometric
  1970. error \f$d(points1[i], newPoints1[i])^2 + d(points2[i],newPoints2[i])^2\f$ (where \f$d(a,b)\f$ is the
  1971. geometric distance between points \f$a\f$ and \f$b\f$ ) subject to the epipolar constraint
  1972. \f$newPoints2^T \cdot F \cdot newPoints1 = 0\f$ .
  1973. */
  1974. CV_EXPORTS_W void correctMatches( InputArray F, InputArray points1, InputArray points2,
  1975. OutputArray newPoints1, OutputArray newPoints2 );
  1976. /** @brief Filters off small noise blobs (speckles) in the disparity map
  1977. @param img The input 16-bit signed disparity image
  1978. @param newVal The disparity value used to paint-off the speckles
  1979. @param maxSpeckleSize The maximum speckle size to consider it a speckle. Larger blobs are not
  1980. affected by the algorithm
  1981. @param maxDiff Maximum difference between neighbor disparity pixels to put them into the same
  1982. blob. Note that since StereoBM, StereoSGBM and may be other algorithms return a fixed-point
  1983. disparity map, where disparity values are multiplied by 16, this scale factor should be taken into
  1984. account when specifying this parameter value.
  1985. @param buf The optional temporary buffer to avoid memory allocation within the function.
  1986. */
  1987. CV_EXPORTS_W void filterSpeckles( InputOutputArray img, double newVal,
  1988. int maxSpeckleSize, double maxDiff,
  1989. InputOutputArray buf = noArray() );
  1990. //! computes valid disparity ROI from the valid ROIs of the rectified images (that are returned by cv::stereoRectify())
  1991. CV_EXPORTS_W Rect getValidDisparityROI( Rect roi1, Rect roi2,
  1992. int minDisparity, int numberOfDisparities,
  1993. int blockSize );
  1994. //! validates disparity using the left-right check. The matrix "cost" should be computed by the stereo correspondence algorithm
  1995. CV_EXPORTS_W void validateDisparity( InputOutputArray disparity, InputArray cost,
  1996. int minDisparity, int numberOfDisparities,
  1997. int disp12MaxDisp = 1 );
  1998. /** @brief Reprojects a disparity image to 3D space.
  1999. @param disparity Input single-channel 8-bit unsigned, 16-bit signed, 32-bit signed or 32-bit
  2000. floating-point disparity image. The values of 8-bit / 16-bit signed formats are assumed to have no
  2001. fractional bits. If the disparity is 16-bit signed format, as computed by @ref StereoBM or
  2002. @ref StereoSGBM and maybe other algorithms, it should be divided by 16 (and scaled to float) before
  2003. being used here.
  2004. @param _3dImage Output 3-channel floating-point image of the same size as disparity. Each element of
  2005. _3dImage(x,y) contains 3D coordinates of the point (x,y) computed from the disparity map. If one
  2006. uses Q obtained by @ref stereoRectify, then the returned points are represented in the first
  2007. camera's rectified coordinate system.
  2008. @param Q \f$4 \times 4\f$ perspective transformation matrix that can be obtained with
  2009. @ref stereoRectify.
  2010. @param handleMissingValues Indicates, whether the function should handle missing values (i.e.
  2011. points where the disparity was not computed). If handleMissingValues=true, then pixels with the
  2012. minimal disparity that corresponds to the outliers (see StereoMatcher::compute ) are transformed
  2013. to 3D points with a very large Z value (currently set to 10000).
  2014. @param ddepth The optional output array depth. If it is -1, the output image will have CV_32F
  2015. depth. ddepth can also be set to CV_16S, CV_32S or CV_32F.
  2016. The function transforms a single-channel disparity map to a 3-channel image representing a 3D
  2017. surface. That is, for each pixel (x,y) and the corresponding disparity d=disparity(x,y) , it
  2018. computes:
  2019. \f[\begin{bmatrix}
  2020. X \\
  2021. Y \\
  2022. Z \\
  2023. W
  2024. \end{bmatrix} = Q \begin{bmatrix}
  2025. x \\
  2026. y \\
  2027. \texttt{disparity} (x,y) \\
  2028. z
  2029. \end{bmatrix}.\f]
  2030. @sa
  2031. To reproject a sparse set of points {(x,y,d),...} to 3D space, use perspectiveTransform.
  2032. */
  2033. CV_EXPORTS_W void reprojectImageTo3D( InputArray disparity,
  2034. OutputArray _3dImage, InputArray Q,
  2035. bool handleMissingValues = false,
  2036. int ddepth = -1 );
  2037. /** @brief Calculates the Sampson Distance between two points.
  2038. The function cv::sampsonDistance calculates and returns the first order approximation of the geometric error as:
  2039. \f[
  2040. sd( \texttt{pt1} , \texttt{pt2} )=
  2041. \frac{(\texttt{pt2}^t \cdot \texttt{F} \cdot \texttt{pt1})^2}
  2042. {((\texttt{F} \cdot \texttt{pt1})(0))^2 +
  2043. ((\texttt{F} \cdot \texttt{pt1})(1))^2 +
  2044. ((\texttt{F}^t \cdot \texttt{pt2})(0))^2 +
  2045. ((\texttt{F}^t \cdot \texttt{pt2})(1))^2}
  2046. \f]
  2047. The fundamental matrix may be calculated using the cv::findFundamentalMat function. See @cite HartleyZ00 11.4.3 for details.
  2048. @param pt1 first homogeneous 2d point
  2049. @param pt2 second homogeneous 2d point
  2050. @param F fundamental matrix
  2051. @return The computed Sampson distance.
  2052. */
  2053. CV_EXPORTS_W double sampsonDistance(InputArray pt1, InputArray pt2, InputArray F);
  2054. /** @brief Computes an optimal affine transformation between two 3D point sets.
  2055. It computes
  2056. \f[
  2057. \begin{bmatrix}
  2058. x\\
  2059. y\\
  2060. z\\
  2061. \end{bmatrix}
  2062. =
  2063. \begin{bmatrix}
  2064. a_{11} & a_{12} & a_{13}\\
  2065. a_{21} & a_{22} & a_{23}\\
  2066. a_{31} & a_{32} & a_{33}\\
  2067. \end{bmatrix}
  2068. \begin{bmatrix}
  2069. X\\
  2070. Y\\
  2071. Z\\
  2072. \end{bmatrix}
  2073. +
  2074. \begin{bmatrix}
  2075. b_1\\
  2076. b_2\\
  2077. b_3\\
  2078. \end{bmatrix}
  2079. \f]
  2080. @param src First input 3D point set containing \f$(X,Y,Z)\f$.
  2081. @param dst Second input 3D point set containing \f$(x,y,z)\f$.
  2082. @param out Output 3D affine transformation matrix \f$3 \times 4\f$ of the form
  2083. \f[
  2084. \begin{bmatrix}
  2085. a_{11} & a_{12} & a_{13} & b_1\\
  2086. a_{21} & a_{22} & a_{23} & b_2\\
  2087. a_{31} & a_{32} & a_{33} & b_3\\
  2088. \end{bmatrix}
  2089. \f]
  2090. @param inliers Output vector indicating which points are inliers (1-inlier, 0-outlier).
  2091. @param ransacThreshold Maximum reprojection error in the RANSAC algorithm to consider a point as
  2092. an inlier.
  2093. @param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything
  2094. between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation
  2095. significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation.
  2096. The function estimates an optimal 3D affine transformation between two 3D point sets using the
  2097. RANSAC algorithm.
  2098. */
  2099. CV_EXPORTS_W int estimateAffine3D(InputArray src, InputArray dst,
  2100. OutputArray out, OutputArray inliers,
  2101. double ransacThreshold = 3, double confidence = 0.99);
  2102. /** @brief Computes an optimal affine transformation between two 2D point sets.
  2103. It computes
  2104. \f[
  2105. \begin{bmatrix}
  2106. x\\
  2107. y\\
  2108. \end{bmatrix}
  2109. =
  2110. \begin{bmatrix}
  2111. a_{11} & a_{12}\\
  2112. a_{21} & a_{22}\\
  2113. \end{bmatrix}
  2114. \begin{bmatrix}
  2115. X\\
  2116. Y\\
  2117. \end{bmatrix}
  2118. +
  2119. \begin{bmatrix}
  2120. b_1\\
  2121. b_2\\
  2122. \end{bmatrix}
  2123. \f]
  2124. @param from First input 2D point set containing \f$(X,Y)\f$.
  2125. @param to Second input 2D point set containing \f$(x,y)\f$.
  2126. @param inliers Output vector indicating which points are inliers (1-inlier, 0-outlier).
  2127. @param method Robust method used to compute transformation. The following methods are possible:
  2128. - @ref RANSAC - RANSAC-based robust method
  2129. - @ref LMEDS - Least-Median robust method
  2130. RANSAC is the default method.
  2131. @param ransacReprojThreshold Maximum reprojection error in the RANSAC algorithm to consider
  2132. a point as an inlier. Applies only to RANSAC.
  2133. @param maxIters The maximum number of robust method iterations.
  2134. @param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything
  2135. between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation
  2136. significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation.
  2137. @param refineIters Maximum number of iterations of refining algorithm (Levenberg-Marquardt).
  2138. Passing 0 will disable refining, so the output matrix will be output of robust method.
  2139. @return Output 2D affine transformation matrix \f$2 \times 3\f$ or empty matrix if transformation
  2140. could not be estimated. The returned matrix has the following form:
  2141. \f[
  2142. \begin{bmatrix}
  2143. a_{11} & a_{12} & b_1\\
  2144. a_{21} & a_{22} & b_2\\
  2145. \end{bmatrix}
  2146. \f]
  2147. The function estimates an optimal 2D affine transformation between two 2D point sets using the
  2148. selected robust algorithm.
  2149. The computed transformation is then refined further (using only inliers) with the
  2150. Levenberg-Marquardt method to reduce the re-projection error even more.
  2151. @note
  2152. The RANSAC method can handle practically any ratio of outliers but needs a threshold to
  2153. distinguish inliers from outliers. The method LMeDS does not need any threshold but it works
  2154. correctly only when there are more than 50% of inliers.
  2155. @sa estimateAffinePartial2D, getAffineTransform
  2156. */
  2157. CV_EXPORTS_W cv::Mat estimateAffine2D(InputArray from, InputArray to, OutputArray inliers = noArray(),
  2158. int method = RANSAC, double ransacReprojThreshold = 3,
  2159. size_t maxIters = 2000, double confidence = 0.99,
  2160. size_t refineIters = 10);
  2161. /** @brief Computes an optimal limited affine transformation with 4 degrees of freedom between
  2162. two 2D point sets.
  2163. @param from First input 2D point set.
  2164. @param to Second input 2D point set.
  2165. @param inliers Output vector indicating which points are inliers.
  2166. @param method Robust method used to compute transformation. The following methods are possible:
  2167. - @ref RANSAC - RANSAC-based robust method
  2168. - @ref LMEDS - Least-Median robust method
  2169. RANSAC is the default method.
  2170. @param ransacReprojThreshold Maximum reprojection error in the RANSAC algorithm to consider
  2171. a point as an inlier. Applies only to RANSAC.
  2172. @param maxIters The maximum number of robust method iterations.
  2173. @param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything
  2174. between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation
  2175. significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation.
  2176. @param refineIters Maximum number of iterations of refining algorithm (Levenberg-Marquardt).
  2177. Passing 0 will disable refining, so the output matrix will be output of robust method.
  2178. @return Output 2D affine transformation (4 degrees of freedom) matrix \f$2 \times 3\f$ or
  2179. empty matrix if transformation could not be estimated.
  2180. The function estimates an optimal 2D affine transformation with 4 degrees of freedom limited to
  2181. combinations of translation, rotation, and uniform scaling. Uses the selected algorithm for robust
  2182. estimation.
  2183. The computed transformation is then refined further (using only inliers) with the
  2184. Levenberg-Marquardt method to reduce the re-projection error even more.
  2185. Estimated transformation matrix is:
  2186. \f[ \begin{bmatrix} \cos(\theta) \cdot s & -\sin(\theta) \cdot s & t_x \\
  2187. \sin(\theta) \cdot s & \cos(\theta) \cdot s & t_y
  2188. \end{bmatrix} \f]
  2189. Where \f$ \theta \f$ is the rotation angle, \f$ s \f$ the scaling factor and \f$ t_x, t_y \f$ are
  2190. translations in \f$ x, y \f$ axes respectively.
  2191. @note
  2192. The RANSAC method can handle practically any ratio of outliers but need a threshold to
  2193. distinguish inliers from outliers. The method LMeDS does not need any threshold but it works
  2194. correctly only when there are more than 50% of inliers.
  2195. @sa estimateAffine2D, getAffineTransform
  2196. */
  2197. CV_EXPORTS_W cv::Mat estimateAffinePartial2D(InputArray from, InputArray to, OutputArray inliers = noArray(),
  2198. int method = RANSAC, double ransacReprojThreshold = 3,
  2199. size_t maxIters = 2000, double confidence = 0.99,
  2200. size_t refineIters = 10);
  2201. /** @example samples/cpp/tutorial_code/features2D/Homography/decompose_homography.cpp
  2202. An example program with homography decomposition.
  2203. Check @ref tutorial_homography "the corresponding tutorial" for more details.
  2204. */
  2205. /** @brief Decompose a homography matrix to rotation(s), translation(s) and plane normal(s).
  2206. @param H The input homography matrix between two images.
  2207. @param K The input camera intrinsic matrix.
  2208. @param rotations Array of rotation matrices.
  2209. @param translations Array of translation matrices.
  2210. @param normals Array of plane normal matrices.
  2211. This function extracts relative camera motion between two views of a planar object and returns up to
  2212. four mathematical solution tuples of rotation, translation, and plane normal. The decomposition of
  2213. the homography matrix H is described in detail in @cite Malis2007.
  2214. If the homography H, induced by the plane, gives the constraint
  2215. \f[s_i \vecthree{x'_i}{y'_i}{1} \sim H \vecthree{x_i}{y_i}{1}\f] on the source image points
  2216. \f$p_i\f$ and the destination image points \f$p'_i\f$, then the tuple of rotations[k] and
  2217. translations[k] is a change of basis from the source camera's coordinate system to the destination
  2218. camera's coordinate system. However, by decomposing H, one can only get the translation normalized
  2219. by the (typically unknown) depth of the scene, i.e. its direction but with normalized length.
  2220. If point correspondences are available, at least two solutions may further be invalidated, by
  2221. applying positive depth constraint, i.e. all points must be in front of the camera.
  2222. */
  2223. CV_EXPORTS_W int decomposeHomographyMat(InputArray H,
  2224. InputArray K,
  2225. OutputArrayOfArrays rotations,
  2226. OutputArrayOfArrays translations,
  2227. OutputArrayOfArrays normals);
  2228. /** @brief Filters homography decompositions based on additional information.
  2229. @param rotations Vector of rotation matrices.
  2230. @param normals Vector of plane normal matrices.
  2231. @param beforePoints Vector of (rectified) visible reference points before the homography is applied
  2232. @param afterPoints Vector of (rectified) visible reference points after the homography is applied
  2233. @param possibleSolutions Vector of int indices representing the viable solution set after filtering
  2234. @param pointsMask optional Mat/Vector of 8u type representing the mask for the inliers as given by the #findHomography function
  2235. This function is intended to filter the output of the #decomposeHomographyMat based on additional
  2236. information as described in @cite Malis2007 . The summary of the method: the #decomposeHomographyMat function
  2237. returns 2 unique solutions and their "opposites" for a total of 4 solutions. If we have access to the
  2238. sets of points visible in the camera frame before and after the homography transformation is applied,
  2239. we can determine which are the true potential solutions and which are the opposites by verifying which
  2240. homographies are consistent with all visible reference points being in front of the camera. The inputs
  2241. are left unchanged; the filtered solution set is returned as indices into the existing one.
  2242. */
  2243. CV_EXPORTS_W void filterHomographyDecompByVisibleRefpoints(InputArrayOfArrays rotations,
  2244. InputArrayOfArrays normals,
  2245. InputArray beforePoints,
  2246. InputArray afterPoints,
  2247. OutputArray possibleSolutions,
  2248. InputArray pointsMask = noArray());
  2249. /** @brief The base class for stereo correspondence algorithms.
  2250. */
  2251. class CV_EXPORTS_W StereoMatcher : public Algorithm
  2252. {
  2253. public:
  2254. enum { DISP_SHIFT = 4,
  2255. DISP_SCALE = (1 << DISP_SHIFT)
  2256. };
  2257. /** @brief Computes disparity map for the specified stereo pair
  2258. @param left Left 8-bit single-channel image.
  2259. @param right Right image of the same size and the same type as the left one.
  2260. @param disparity Output disparity map. It has the same size as the input images. Some algorithms,
  2261. like StereoBM or StereoSGBM compute 16-bit fixed-point disparity map (where each disparity value
  2262. has 4 fractional bits), whereas other algorithms output 32-bit floating-point disparity map.
  2263. */
  2264. CV_WRAP virtual void compute( InputArray left, InputArray right,
  2265. OutputArray disparity ) = 0;
  2266. CV_WRAP virtual int getMinDisparity() const = 0;
  2267. CV_WRAP virtual void setMinDisparity(int minDisparity) = 0;
  2268. CV_WRAP virtual int getNumDisparities() const = 0;
  2269. CV_WRAP virtual void setNumDisparities(int numDisparities) = 0;
  2270. CV_WRAP virtual int getBlockSize() const = 0;
  2271. CV_WRAP virtual void setBlockSize(int blockSize) = 0;
  2272. CV_WRAP virtual int getSpeckleWindowSize() const = 0;
  2273. CV_WRAP virtual void setSpeckleWindowSize(int speckleWindowSize) = 0;
  2274. CV_WRAP virtual int getSpeckleRange() const = 0;
  2275. CV_WRAP virtual void setSpeckleRange(int speckleRange) = 0;
  2276. CV_WRAP virtual int getDisp12MaxDiff() const = 0;
  2277. CV_WRAP virtual void setDisp12MaxDiff(int disp12MaxDiff) = 0;
  2278. };
  2279. /** @brief Class for computing stereo correspondence using the block matching algorithm, introduced and
  2280. contributed to OpenCV by K. Konolige.
  2281. */
  2282. class CV_EXPORTS_W StereoBM : public StereoMatcher
  2283. {
  2284. public:
  2285. enum { PREFILTER_NORMALIZED_RESPONSE = 0,
  2286. PREFILTER_XSOBEL = 1
  2287. };
  2288. CV_WRAP virtual int getPreFilterType() const = 0;
  2289. CV_WRAP virtual void setPreFilterType(int preFilterType) = 0;
  2290. CV_WRAP virtual int getPreFilterSize() const = 0;
  2291. CV_WRAP virtual void setPreFilterSize(int preFilterSize) = 0;
  2292. CV_WRAP virtual int getPreFilterCap() const = 0;
  2293. CV_WRAP virtual void setPreFilterCap(int preFilterCap) = 0;
  2294. CV_WRAP virtual int getTextureThreshold() const = 0;
  2295. CV_WRAP virtual void setTextureThreshold(int textureThreshold) = 0;
  2296. CV_WRAP virtual int getUniquenessRatio() const = 0;
  2297. CV_WRAP virtual void setUniquenessRatio(int uniquenessRatio) = 0;
  2298. CV_WRAP virtual int getSmallerBlockSize() const = 0;
  2299. CV_WRAP virtual void setSmallerBlockSize(int blockSize) = 0;
  2300. CV_WRAP virtual Rect getROI1() const = 0;
  2301. CV_WRAP virtual void setROI1(Rect roi1) = 0;
  2302. CV_WRAP virtual Rect getROI2() const = 0;
  2303. CV_WRAP virtual void setROI2(Rect roi2) = 0;
  2304. /** @brief Creates StereoBM object
  2305. @param numDisparities the disparity search range. For each pixel algorithm will find the best
  2306. disparity from 0 (default minimum disparity) to numDisparities. The search range can then be
  2307. shifted by changing the minimum disparity.
  2308. @param blockSize the linear size of the blocks compared by the algorithm. The size should be odd
  2309. (as the block is centered at the current pixel). Larger block size implies smoother, though less
  2310. accurate disparity map. Smaller block size gives more detailed disparity map, but there is higher
  2311. chance for algorithm to find a wrong correspondence.
  2312. The function create StereoBM object. You can then call StereoBM::compute() to compute disparity for
  2313. a specific stereo pair.
  2314. */
  2315. CV_WRAP static Ptr<StereoBM> create(int numDisparities = 0, int blockSize = 21);
  2316. };
  2317. /** @brief The class implements the modified H. Hirschmuller algorithm @cite HH08 that differs from the original
  2318. one as follows:
  2319. - By default, the algorithm is single-pass, which means that you consider only 5 directions
  2320. instead of 8. Set mode=StereoSGBM::MODE_HH in createStereoSGBM to run the full variant of the
  2321. algorithm but beware that it may consume a lot of memory.
  2322. - The algorithm matches blocks, not individual pixels. Though, setting blockSize=1 reduces the
  2323. blocks to single pixels.
  2324. - Mutual information cost function is not implemented. Instead, a simpler Birchfield-Tomasi
  2325. sub-pixel metric from @cite BT98 is used. Though, the color images are supported as well.
  2326. - Some pre- and post- processing steps from K. Konolige algorithm StereoBM are included, for
  2327. example: pre-filtering (StereoBM::PREFILTER_XSOBEL type) and post-filtering (uniqueness
  2328. check, quadratic interpolation and speckle filtering).
  2329. @note
  2330. - (Python) An example illustrating the use of the StereoSGBM matching algorithm can be found
  2331. at opencv_source_code/samples/python/stereo_match.py
  2332. */
  2333. class CV_EXPORTS_W StereoSGBM : public StereoMatcher
  2334. {
  2335. public:
  2336. enum
  2337. {
  2338. MODE_SGBM = 0,
  2339. MODE_HH = 1,
  2340. MODE_SGBM_3WAY = 2,
  2341. MODE_HH4 = 3
  2342. };
  2343. CV_WRAP virtual int getPreFilterCap() const = 0;
  2344. CV_WRAP virtual void setPreFilterCap(int preFilterCap) = 0;
  2345. CV_WRAP virtual int getUniquenessRatio() const = 0;
  2346. CV_WRAP virtual void setUniquenessRatio(int uniquenessRatio) = 0;
  2347. CV_WRAP virtual int getP1() const = 0;
  2348. CV_WRAP virtual void setP1(int P1) = 0;
  2349. CV_WRAP virtual int getP2() const = 0;
  2350. CV_WRAP virtual void setP2(int P2) = 0;
  2351. CV_WRAP virtual int getMode() const = 0;
  2352. CV_WRAP virtual void setMode(int mode) = 0;
  2353. /** @brief Creates StereoSGBM object
  2354. @param minDisparity Minimum possible disparity value. Normally, it is zero but sometimes
  2355. rectification algorithms can shift images, so this parameter needs to be adjusted accordingly.
  2356. @param numDisparities Maximum disparity minus minimum disparity. The value is always greater than
  2357. zero. In the current implementation, this parameter must be divisible by 16.
  2358. @param blockSize Matched block size. It must be an odd number \>=1 . Normally, it should be
  2359. somewhere in the 3..11 range.
  2360. @param P1 The first parameter controlling the disparity smoothness. See below.
  2361. @param P2 The second parameter controlling the disparity smoothness. The larger the values are,
  2362. the smoother the disparity is. P1 is the penalty on the disparity change by plus or minus 1
  2363. between neighbor pixels. P2 is the penalty on the disparity change by more than 1 between neighbor
  2364. pixels. The algorithm requires P2 \> P1 . See stereo_match.cpp sample where some reasonably good
  2365. P1 and P2 values are shown (like 8\*number_of_image_channels\*blockSize\*blockSize and
  2366. 32\*number_of_image_channels\*blockSize\*blockSize , respectively).
  2367. @param disp12MaxDiff Maximum allowed difference (in integer pixel units) in the left-right
  2368. disparity check. Set it to a non-positive value to disable the check.
  2369. @param preFilterCap Truncation value for the prefiltered image pixels. The algorithm first
  2370. computes x-derivative at each pixel and clips its value by [-preFilterCap, preFilterCap] interval.
  2371. The result values are passed to the Birchfield-Tomasi pixel cost function.
  2372. @param uniquenessRatio Margin in percentage by which the best (minimum) computed cost function
  2373. value should "win" the second best value to consider the found match correct. Normally, a value
  2374. within the 5-15 range is good enough.
  2375. @param speckleWindowSize Maximum size of smooth disparity regions to consider their noise speckles
  2376. and invalidate. Set it to 0 to disable speckle filtering. Otherwise, set it somewhere in the
  2377. 50-200 range.
  2378. @param speckleRange Maximum disparity variation within each connected component. If you do speckle
  2379. filtering, set the parameter to a positive value, it will be implicitly multiplied by 16.
  2380. Normally, 1 or 2 is good enough.
  2381. @param mode Set it to StereoSGBM::MODE_HH to run the full-scale two-pass dynamic programming
  2382. algorithm. It will consume O(W\*H\*numDisparities) bytes, which is large for 640x480 stereo and
  2383. huge for HD-size pictures. By default, it is set to false .
  2384. The first constructor initializes StereoSGBM with all the default parameters. So, you only have to
  2385. set StereoSGBM::numDisparities at minimum. The second constructor enables you to set each parameter
  2386. to a custom value.
  2387. */
  2388. CV_WRAP static Ptr<StereoSGBM> create(int minDisparity = 0, int numDisparities = 16, int blockSize = 3,
  2389. int P1 = 0, int P2 = 0, int disp12MaxDiff = 0,
  2390. int preFilterCap = 0, int uniquenessRatio = 0,
  2391. int speckleWindowSize = 0, int speckleRange = 0,
  2392. int mode = StereoSGBM::MODE_SGBM);
  2393. };
  2394. //! @} calib3d
  2395. /** @brief The methods in this namespace use a so-called fisheye camera model.
  2396. @ingroup calib3d_fisheye
  2397. */
  2398. namespace fisheye
  2399. {
  2400. //! @addtogroup calib3d_fisheye
  2401. //! @{
  2402. enum{
  2403. CALIB_USE_INTRINSIC_GUESS = 1 << 0,
  2404. CALIB_RECOMPUTE_EXTRINSIC = 1 << 1,
  2405. CALIB_CHECK_COND = 1 << 2,
  2406. CALIB_FIX_SKEW = 1 << 3,
  2407. CALIB_FIX_K1 = 1 << 4,
  2408. CALIB_FIX_K2 = 1 << 5,
  2409. CALIB_FIX_K3 = 1 << 6,
  2410. CALIB_FIX_K4 = 1 << 7,
  2411. CALIB_FIX_INTRINSIC = 1 << 8,
  2412. CALIB_FIX_PRINCIPAL_POINT = 1 << 9,
  2413. CALIB_ZERO_DISPARITY = 1 << 10
  2414. };
  2415. /** @brief Projects points using fisheye model
  2416. @param objectPoints Array of object points, 1xN/Nx1 3-channel (or vector\<Point3f\> ), where N is
  2417. the number of points in the view.
  2418. @param imagePoints Output array of image points, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel, or
  2419. vector\<Point2f\>.
  2420. @param affine
  2421. @param K Camera intrinsic matrix \f$cameramatrix{K}\f$.
  2422. @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
  2423. @param alpha The skew coefficient.
  2424. @param jacobian Optional output 2Nx15 jacobian matrix of derivatives of image points with respect
  2425. to components of the focal lengths, coordinates of the principal point, distortion coefficients,
  2426. rotation vector, translation vector, and the skew. In the old interface different components of
  2427. the jacobian are returned via different output parameters.
  2428. The function computes projections of 3D points to the image plane given intrinsic and extrinsic
  2429. camera parameters. Optionally, the function computes Jacobians - matrices of partial derivatives of
  2430. image points coordinates (as functions of all the input parameters) with respect to the particular
  2431. parameters, intrinsic and/or extrinsic.
  2432. */
  2433. CV_EXPORTS void projectPoints(InputArray objectPoints, OutputArray imagePoints, const Affine3d& affine,
  2434. InputArray K, InputArray D, double alpha = 0, OutputArray jacobian = noArray());
  2435. /** @overload */
  2436. CV_EXPORTS_W void projectPoints(InputArray objectPoints, OutputArray imagePoints, InputArray rvec, InputArray tvec,
  2437. InputArray K, InputArray D, double alpha = 0, OutputArray jacobian = noArray());
  2438. /** @brief Distorts 2D points using fisheye model.
  2439. @param undistorted Array of object points, 1xN/Nx1 2-channel (or vector\<Point2f\> ), where N is
  2440. the number of points in the view.
  2441. @param K Camera intrinsic matrix \f$cameramatrix{K}\f$.
  2442. @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
  2443. @param alpha The skew coefficient.
  2444. @param distorted Output array of image points, 1xN/Nx1 2-channel, or vector\<Point2f\> .
  2445. Note that the function assumes the camera intrinsic matrix of the undistorted points to be identity.
  2446. This means if you want to transform back points undistorted with undistortPoints() you have to
  2447. multiply them with \f$P^{-1}\f$.
  2448. */
  2449. CV_EXPORTS_W void distortPoints(InputArray undistorted, OutputArray distorted, InputArray K, InputArray D, double alpha = 0);
  2450. /** @brief Undistorts 2D points using fisheye model
  2451. @param distorted Array of object points, 1xN/Nx1 2-channel (or vector\<Point2f\> ), where N is the
  2452. number of points in the view.
  2453. @param K Camera intrinsic matrix \f$cameramatrix{K}\f$.
  2454. @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
  2455. @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3
  2456. 1-channel or 1x1 3-channel
  2457. @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4)
  2458. @param undistorted Output array of image points, 1xN/Nx1 2-channel, or vector\<Point2f\> .
  2459. */
  2460. CV_EXPORTS_W void undistortPoints(InputArray distorted, OutputArray undistorted,
  2461. InputArray K, InputArray D, InputArray R = noArray(), InputArray P = noArray());
  2462. /** @brief Computes undistortion and rectification maps for image transform by cv::remap(). If D is empty zero
  2463. distortion is used, if R or P is empty identity matrixes are used.
  2464. @param K Camera intrinsic matrix \f$cameramatrix{K}\f$.
  2465. @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
  2466. @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3
  2467. 1-channel or 1x1 3-channel
  2468. @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4)
  2469. @param size Undistorted image size.
  2470. @param m1type Type of the first output map that can be CV_32FC1 or CV_16SC2 . See convertMaps()
  2471. for details.
  2472. @param map1 The first output map.
  2473. @param map2 The second output map.
  2474. */
  2475. CV_EXPORTS_W void initUndistortRectifyMap(InputArray K, InputArray D, InputArray R, InputArray P,
  2476. const cv::Size& size, int m1type, OutputArray map1, OutputArray map2);
  2477. /** @brief Transforms an image to compensate for fisheye lens distortion.
  2478. @param distorted image with fisheye lens distortion.
  2479. @param undistorted Output image with compensated fisheye lens distortion.
  2480. @param K Camera intrinsic matrix \f$cameramatrix{K}\f$.
  2481. @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
  2482. @param Knew Camera intrinsic matrix of the distorted image. By default, it is the identity matrix but you
  2483. may additionally scale and shift the result by using a different matrix.
  2484. @param new_size the new size
  2485. The function transforms an image to compensate radial and tangential lens distortion.
  2486. The function is simply a combination of fisheye::initUndistortRectifyMap (with unity R ) and remap
  2487. (with bilinear interpolation). See the former function for details of the transformation being
  2488. performed.
  2489. See below the results of undistortImage.
  2490. - a\) result of undistort of perspective camera model (all possible coefficients (k_1, k_2, k_3,
  2491. k_4, k_5, k_6) of distortion were optimized under calibration)
  2492. - b\) result of fisheye::undistortImage of fisheye camera model (all possible coefficients (k_1, k_2,
  2493. k_3, k_4) of fisheye distortion were optimized under calibration)
  2494. - c\) original image was captured with fisheye lens
  2495. Pictures a) and b) almost the same. But if we consider points of image located far from the center
  2496. of image, we can notice that on image a) these points are distorted.
  2497. ![image](pics/fisheye_undistorted.jpg)
  2498. */
  2499. CV_EXPORTS_W void undistortImage(InputArray distorted, OutputArray undistorted,
  2500. InputArray K, InputArray D, InputArray Knew = cv::noArray(), const Size& new_size = Size());
  2501. /** @brief Estimates new camera intrinsic matrix for undistortion or rectification.
  2502. @param K Camera intrinsic matrix \f$cameramatrix{K}\f$.
  2503. @param image_size Size of the image
  2504. @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$.
  2505. @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3
  2506. 1-channel or 1x1 3-channel
  2507. @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4)
  2508. @param balance Sets the new focal length in range between the min focal length and the max focal
  2509. length. Balance is in range of [0, 1].
  2510. @param new_size the new size
  2511. @param fov_scale Divisor for new focal length.
  2512. */
  2513. CV_EXPORTS_W void estimateNewCameraMatrixForUndistortRectify(InputArray K, InputArray D, const Size &image_size, InputArray R,
  2514. OutputArray P, double balance = 0.0, const Size& new_size = Size(), double fov_scale = 1.0);
  2515. /** @brief Performs camera calibration
  2516. @param objectPoints vector of vectors of calibration pattern points in the calibration pattern
  2517. coordinate space.
  2518. @param imagePoints vector of vectors of the projections of calibration pattern points.
  2519. imagePoints.size() and objectPoints.size() and imagePoints[i].size() must be equal to
  2520. objectPoints[i].size() for each i.
  2521. @param image_size Size of the image used only to initialize the camera intrinsic matrix.
  2522. @param K Output 3x3 floating-point camera intrinsic matrix
  2523. \f$\cameramatrix{A}\f$ . If
  2524. @ref fisheye::CALIB_USE_INTRINSIC_GUESS is specified, some or all of fx, fy, cx, cy must be
  2525. initialized before calling the function.
  2526. @param D Output vector of distortion coefficients \f$\distcoeffsfisheye\f$.
  2527. @param rvecs Output vector of rotation vectors (see Rodrigues ) estimated for each pattern view.
  2528. That is, each k-th rotation vector together with the corresponding k-th translation vector (see
  2529. the next output parameter description) brings the calibration pattern from the model coordinate
  2530. space (in which object points are specified) to the world coordinate space, that is, a real
  2531. position of the calibration pattern in the k-th pattern view (k=0.. *M* -1).
  2532. @param tvecs Output vector of translation vectors estimated for each pattern view.
  2533. @param flags Different flags that may be zero or a combination of the following values:
  2534. - @ref fisheye::CALIB_USE_INTRINSIC_GUESS cameraMatrix contains valid initial values of
  2535. fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image
  2536. center ( imageSize is used), and focal distances are computed in a least-squares fashion.
  2537. - @ref fisheye::CALIB_RECOMPUTE_EXTRINSIC Extrinsic will be recomputed after each iteration
  2538. of intrinsic optimization.
  2539. - @ref fisheye::CALIB_CHECK_COND The functions will check validity of condition number.
  2540. - @ref fisheye::CALIB_FIX_SKEW Skew coefficient (alpha) is set to zero and stay zero.
  2541. - @ref fisheye::CALIB_FIX_K1,..., @ref fisheye::CALIB_FIX_K4 Selected distortion coefficients
  2542. are set to zeros and stay zero.
  2543. - @ref fisheye::CALIB_FIX_PRINCIPAL_POINT The principal point is not changed during the global
  2544. optimization. It stays at the center or at a different location specified when @ref fisheye::CALIB_USE_INTRINSIC_GUESS is set too.
  2545. @param criteria Termination criteria for the iterative optimization algorithm.
  2546. */
  2547. CV_EXPORTS_W double calibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, const Size& image_size,
  2548. InputOutputArray K, InputOutputArray D, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, int flags = 0,
  2549. TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON));
  2550. /** @brief Stereo rectification for fisheye camera model
  2551. @param K1 First camera intrinsic matrix.
  2552. @param D1 First camera distortion parameters.
  2553. @param K2 Second camera intrinsic matrix.
  2554. @param D2 Second camera distortion parameters.
  2555. @param imageSize Size of the image used for stereo calibration.
  2556. @param R Rotation matrix between the coordinate systems of the first and the second
  2557. cameras.
  2558. @param tvec Translation vector between coordinate systems of the cameras.
  2559. @param R1 Output 3x3 rectification transform (rotation matrix) for the first camera.
  2560. @param R2 Output 3x3 rectification transform (rotation matrix) for the second camera.
  2561. @param P1 Output 3x4 projection matrix in the new (rectified) coordinate systems for the first
  2562. camera.
  2563. @param P2 Output 3x4 projection matrix in the new (rectified) coordinate systems for the second
  2564. camera.
  2565. @param Q Output \f$4 \times 4\f$ disparity-to-depth mapping matrix (see #reprojectImageTo3D ).
  2566. @param flags Operation flags that may be zero or @ref fisheye::CALIB_ZERO_DISPARITY . If the flag is set,
  2567. the function makes the principal points of each camera have the same pixel coordinates in the
  2568. rectified views. And if the flag is not set, the function may still shift the images in the
  2569. horizontal or vertical direction (depending on the orientation of epipolar lines) to maximize the
  2570. useful image area.
  2571. @param newImageSize New image resolution after rectification. The same size should be passed to
  2572. #initUndistortRectifyMap (see the stereo_calib.cpp sample in OpenCV samples directory). When (0,0)
  2573. is passed (default), it is set to the original imageSize . Setting it to larger value can help you
  2574. preserve details in the original image, especially when there is a big radial distortion.
  2575. @param balance Sets the new focal length in range between the min focal length and the max focal
  2576. length. Balance is in range of [0, 1].
  2577. @param fov_scale Divisor for new focal length.
  2578. */
  2579. CV_EXPORTS_W void stereoRectify(InputArray K1, InputArray D1, InputArray K2, InputArray D2, const Size &imageSize, InputArray R, InputArray tvec,
  2580. OutputArray R1, OutputArray R2, OutputArray P1, OutputArray P2, OutputArray Q, int flags, const Size &newImageSize = Size(),
  2581. double balance = 0.0, double fov_scale = 1.0);
  2582. /** @brief Performs stereo calibration
  2583. @param objectPoints Vector of vectors of the calibration pattern points.
  2584. @param imagePoints1 Vector of vectors of the projections of the calibration pattern points,
  2585. observed by the first camera.
  2586. @param imagePoints2 Vector of vectors of the projections of the calibration pattern points,
  2587. observed by the second camera.
  2588. @param K1 Input/output first camera intrinsic matrix:
  2589. \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
  2590. any of @ref fisheye::CALIB_USE_INTRINSIC_GUESS , @ref fisheye::CALIB_FIX_INTRINSIC are specified,
  2591. some or all of the matrix components must be initialized.
  2592. @param D1 Input/output vector of distortion coefficients \f$\distcoeffsfisheye\f$ of 4 elements.
  2593. @param K2 Input/output second camera intrinsic matrix. The parameter is similar to K1 .
  2594. @param D2 Input/output lens distortion coefficients for the second camera. The parameter is
  2595. similar to D1 .
  2596. @param imageSize Size of the image used only to initialize camera intrinsic matrix.
  2597. @param R Output rotation matrix between the 1st and the 2nd camera coordinate systems.
  2598. @param T Output translation vector between the coordinate systems of the cameras.
  2599. @param flags Different flags that may be zero or a combination of the following values:
  2600. - @ref fisheye::CALIB_FIX_INTRINSIC Fix K1, K2? and D1, D2? so that only R, T matrices
  2601. are estimated.
  2602. - @ref fisheye::CALIB_USE_INTRINSIC_GUESS K1, K2 contains valid initial values of
  2603. fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image
  2604. center (imageSize is used), and focal distances are computed in a least-squares fashion.
  2605. - @ref fisheye::CALIB_RECOMPUTE_EXTRINSIC Extrinsic will be recomputed after each iteration
  2606. of intrinsic optimization.
  2607. - @ref fisheye::CALIB_CHECK_COND The functions will check validity of condition number.
  2608. - @ref fisheye::CALIB_FIX_SKEW Skew coefficient (alpha) is set to zero and stay zero.
  2609. - @ref fisheye::CALIB_FIX_K1,..., @ref fisheye::CALIB_FIX_K4 Selected distortion coefficients are set to zeros and stay
  2610. zero.
  2611. @param criteria Termination criteria for the iterative optimization algorithm.
  2612. */
  2613. CV_EXPORTS_W double stereoCalibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2,
  2614. InputOutputArray K1, InputOutputArray D1, InputOutputArray K2, InputOutputArray D2, Size imageSize,
  2615. OutputArray R, OutputArray T, int flags = fisheye::CALIB_FIX_INTRINSIC,
  2616. TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON));
  2617. //! @} calib3d_fisheye
  2618. } // end namespace fisheye
  2619. } //end namespace cv
  2620. #ifndef DISABLE_OPENCV_24_COMPATIBILITY
  2621. #include "opencv2/calib3d/calib3d_c.h"
  2622. #endif
  2623. #endif