calib3d.hpp 182 KB

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