calib3d.hpp 214 KB

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