calib3d.hpp 233 KB

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